From 2f3a8682c90a606cc1c4985b8118d1bf33021bda Mon Sep 17 00:00:00 2001 From: 2509_92447106 <2509_92447106@noreply.gitcode.com> Date: Sat, 14 Nov 2026 19:42:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0GC-SAVEDOG=E9=A1=B9=E7=9B=AE,?= =?UTF-8?q?=E9=99=8D=E4=BD=8E=E9=9A=90=E6=82=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + .workbuddy/memory/2026-11-14.md | 29 + GC-DOWNLOAD/DirectoryRemote.cs | 52 +- GC-DOWNLOAD/GitCodeReleaseRemote.cs | 19 +- GC-DOWNLOAD/GitCodeRemote.cs | 167 +++++- GC-DOWNLOAD/GiteaRemote.cs | 59 +- GC-DOWNLOAD/LauncherArtifacts.cs | 119 ++++ GC-DOWNLOAD/LauncherUpdater.cs | 162 ++++- GC-DOWNLOAD/SavedogLauncher.cs | 121 ++++ GC-DOWNLOAD/UpdateService.cs | 69 +++ GC-DOWNLOAD/ZipSafety.cs | 32 +- GC-SAVEDOG/Applier.cs | 552 ++++++++++++++++++ GC-SAVEDOG/GC-SAVEDOG.csproj | 47 ++ GC-SAVEDOG/Log.cs | 34 ++ GC-SAVEDOG/Program.cs | 347 +++++++++++ GC-SAVEDOG/SavedogJson.cs | 79 +++ GC.sln | 16 +- GC/src/App.axaml.cs | 5 + GC/src/Assets/i18n/en.json | 2 +- GC/src/Assets/i18n/zh-CN.json | 2 +- GC/src/Models/AppSettings.cs | 6 + GC/src/Security/CanonicalJson.cs | 67 +++ GC/src/Security/ContentHash.cs | 80 +++ GC/src/Security/ManifestLoader.cs | 44 ++ GC/src/Security/ManifestSignature.cs | 172 ++++++ GC/src/Security/ModelIntegrity.cs | 111 ++++ GC/src/Security/SafeArchive.cs | 143 +++++ GC/src/Security/SavedogProtocol.cs | 95 +++ GC/src/Security/SignatureKeyring.cs | 79 +++ GC/src/Security/StartupHealth.cs | 58 ++ GC/src/Services/AppPaths.cs | 30 +- GC/src/Services/Json.cs | 34 +- GC/src/Services/ModelHost.cs | 65 ++- GC/src/Services/UpdateModels.cs | 48 ++ GC/src/ViewModels/MainViewModel.cs | 9 + GC/src/test/dotnet/GC.Tests/Program.cs | 112 +++- README.md | 262 ++++++--- build.sh | 1 + buildps1/lib/Build-Funcs.ps1 | 120 +++- buildsh/build.sh | 11 +- buildsh/check.sh | 2 +- buildsh/lib/build_funcs.sh | 138 ++++- buildsh/tools.sh | 2 +- model/README.md | 73 ++- model/_engine/VersionStamp/Program.cs | 97 ++- .../_engine/VersionStamp/VersionStamp.csproj | 6 + model/_sdk/GC.ModelSdk/IModelContracts.cs | 17 +- model/contour-map/contour-map.json | 4 +- model/earth-geography/earth-geography.json | 4 +- model/earth-revolution/earth-revolution.json | 4 +- model/earth-rotation/earth-rotation.json | 4 +- model/scale-calculator/scale-calculator.json | 4 +- model/version.json | 72 ++- version.json | 72 ++- 54 files changed, 3642 insertions(+), 320 deletions(-) create mode 100644 .workbuddy/memory/2026-11-14.md create mode 100644 GC-DOWNLOAD/LauncherArtifacts.cs create mode 100644 GC-DOWNLOAD/SavedogLauncher.cs create mode 100644 GC-SAVEDOG/Applier.cs create mode 100644 GC-SAVEDOG/GC-SAVEDOG.csproj create mode 100644 GC-SAVEDOG/Log.cs create mode 100644 GC-SAVEDOG/Program.cs create mode 100644 GC-SAVEDOG/SavedogJson.cs create mode 100644 GC/src/Security/CanonicalJson.cs create mode 100644 GC/src/Security/ContentHash.cs create mode 100644 GC/src/Security/ManifestLoader.cs create mode 100644 GC/src/Security/ManifestSignature.cs create mode 100644 GC/src/Security/ModelIntegrity.cs create mode 100644 GC/src/Security/SafeArchive.cs create mode 100644 GC/src/Security/SavedogProtocol.cs create mode 100644 GC/src/Security/SignatureKeyring.cs create mode 100644 GC/src/Security/StartupHealth.cs diff --git a/.gitignore b/.gitignore index 9ff1194..c0f027e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ # 运行数据目录(settings/model/cache/update),绝不入库 .GC/ +# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里) +.signing/ + # .NET 构建中间产物(已跟踪的历史文件不动,只防新增) bin/ obj/ diff --git a/.workbuddy/memory/2026-11-14.md b/.workbuddy/memory/2026-11-14.md new file mode 100644 index 0000000..a461b1e --- /dev/null +++ b/.workbuddy/memory/2026-11-14.md @@ -0,0 +1,29 @@ +# 2026-11-14 + +## GC 启动器安全加固(补完) + +- **GC-SAVEDOG 裁剪发布**:`PublishTrimmed=true` + `TrimMode=full` + + `JsonSerializerIsReflectionEnabledByDefault=false`(已写进 csproj 与两套构建脚本)。 + 体积 70MB → 14MB。裁剪后反射式 JSON 会失效,因此新增 + `GC-SAVEDOG/SavedogJson.cs`(`JsonSerializerContext` 源生成)并通过 + `Json.TypeInfoProvider` 钩子接进共享的 `GC.Download/GC.Services.Json`。 + → 新增 JSON 类型必须登记到 `SavedogJsonContext`,否则只有发布产物会炸。 +- **构建产物布局改为 `dist/<系统>-<架构>/`**(mac-arm64 / win-amd64 / win-arm64), + 更新包路径 `dist/<平台>/GC-<版本>-<平台>.zip`;`pack_launcher` 之后调 + `VersionStamp --launcher-only` 把 `path/dir/name/sha256/size` 写进清单并重新签名。 + 原始 `.app`/`.exe` 移到 `build/trash/`(避免递归删除几百个文件)。 +- **启动器更新支持「只发产物、不发 Release」**:新增 `GC-DOWNLOAD/LauncherArtifacts.cs` + (平台标签/别名、候选目录与文件名推导,构建端 VersionStamp 也链接同一份)。 + `GitCodeRemote/GiteaRemote/DirectoryRemote.DownloadPackageAsync` 改成 + 多候选尝试:url → 清单 path → `dist/<系统>-<架构>/` 目录扫描 → dist 根目录命名, + 每个候选都必须匹配已签名清单的 sha256。 + `GitCodeReleaseRemote` 在「没有 Release」时不再清空 launcher 字段(清单已签名)。 +- **测试**:`--update-test` 新增两条用例(dist 目录能找到并下载 / dist 目录里哈希不符被拒绝), + 当前 33 项全部通过。 +- 触发过的坑:`rm -rf` 大批文件被沙箱批量删除保护拦截 → 构建脚本改用 `mv` 到 `build/trash`。 +- **收尾验证(19:35–19:37)**:`./build.sh pack-launcher` 24s 完成三平台打包, + 清单已写入真实 `sha256/size`(win-amd64 44MB / win-arm64 42MB / mac-arm64 8.7MB, + osx-x64 与 linux-amd64 无产物故留空,下载端会跳过)。根 `version.json` 与 + `model/version.json` 字节一致、签名 `gc-2026-11` 校验 Verified。 + 从 mac 包里解出的 GC-SAVEDOG(14MB 裁剪版)实跑 `verify` / `status` 正常; + `./build.sh check` 全流程通过。 diff --git a/GC-DOWNLOAD/DirectoryRemote.cs b/GC-DOWNLOAD/DirectoryRemote.cs index 4cc19a2..0fc016d 100644 --- a/GC-DOWNLOAD/DirectoryRemote.cs +++ b/GC-DOWNLOAD/DirectoryRemote.cs @@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote { private readonly string _root; private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) }; + private string? _rawManifest; + private string _launcherVersion = ""; public DirectoryRemote(string root) => _root = Path.GetFullPath(root); @@ -26,9 +28,20 @@ public sealed class DirectoryRemote : IModelRemote var fallback = SafePath(Path.Combine("model", "version.json")); var file = File.Exists(primary) ? primary : fallback; if (!File.Exists(file)) return Task.FromResult(null); - return Task.FromResult(Json.Read(file)); + + // 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的 + var text = File.ReadAllText(file); + _rawManifest = text; + var version = ManifestLoader.Parse(text, out _); + if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version)) + _launcherVersion = version.Launcher.Version.Trim(); + return Task.FromResult(version); } + /// 最近一次读到的清单原文(SAVEDOG 二次验签用)。 + public Task GetRawVersionTextAsync(CancellationToken ct) + => Task.FromResult(_rawManifest); + public Task> ListTreeAsync(string rootPath, CancellationToken ct) { var baseDir = SafePath(rootPath ?? "model"); @@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote public async Task DownloadPackageAsync(RepoPackage package, CancellationToken ct) { - if (!string.IsNullOrWhiteSpace(package.Path)) + // 清单路径 / dist 根目录命名:按仓库内相对路径直接找 + foreach (var rel in LauncherArtifacts.CandidateFiles( + package.Rid, package.Dir, package.Path, package.Name, _launcherVersion)) { - var local = SafePath(package.Path!); - if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct); + string full; + try { full = SafePath(rel); } + catch (InvalidOperationException) { continue; } + if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct); } + + // dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则): + // 本地源同样要能跑通「只发产物、不发 Release」的更新方式。 + var fromDist = FindInDist(package); + if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct); + var url = package.Url; if (string.IsNullOrWhiteSpace(url)) return null; // 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。 @@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote return null; } + /// 在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。 + private string? FindInDist(RepoPackage package) + { + foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir)) + { + string full; + try { full = SafePath(dir); } + catch (InvalidOperationException) { continue; } + if (!Directory.Exists(full)) continue; + + var zips = Directory.GetFiles(full, "*.zip"); + if (zips.Length == 0) continue; + + foreach (var zip in zips) + if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid)) + return zip; + if (zips.Length == 1) return zips[0]; + } + return null; + } + private string SafePath(string relative) { var full = Path.GetFullPath(Path.Combine(_root, relative)); diff --git a/GC-DOWNLOAD/GitCodeReleaseRemote.cs b/GC-DOWNLOAD/GitCodeReleaseRemote.cs index d141863..e1d40da 100644 --- a/GC-DOWNLOAD/GitCodeReleaseRemote.cs +++ b/GC-DOWNLOAD/GitCodeReleaseRemote.cs @@ -86,13 +86,19 @@ public sealed class GitCodeReleaseRemote : IModelRemote if (!gotRelease) { - // 没有 Release:启动器版本留空(表示这个源没有可升级的启动器), - // 但模型清单仍然有效,保证模型能正常同步。 - Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)"); - if (version != null) + // 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256, + // 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。 + // 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。 + var v = (version?.Launcher.Version ?? "").Trim(); + var n = version?.Launcher.Packages.Count ?? 0; + if (v.Length == 0 || n == 0) { - version.Launcher.Version = ""; - version.Launcher.Packages.Clear(); + Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包"); + } + else + { + Console.WriteLine( + $"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)"); } } return version; @@ -120,6 +126,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false; version.Launcher.Version = latest.Version; + _content.SetLauncherVersion(latest.Version); _assets.Clear(); foreach (var asset in latest.Assets) diff --git a/GC-DOWNLOAD/GitCodeRemote.cs b/GC-DOWNLOAD/GitCodeRemote.cs index 01e6dab..45226e9 100644 --- a/GC-DOWNLOAD/GitCodeRemote.cs +++ b/GC-DOWNLOAD/GitCodeRemote.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; +using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; @@ -27,6 +28,9 @@ public sealed class GitCodeRemote : IModelRemote private readonly string? _fallbackUrl; private readonly string _displayName; private string _modelDir = "model"; + private string? _rawManifest; + /// 最近一次读到的启动器版本号,用于推导 dist 目录里的包名。 + private string _launcherVersion = ""; public string DisplayName => _displayName; @@ -77,9 +81,24 @@ public sealed class GitCodeRemote : IModelRemote version = await ReadVersionFromAsync(_fallbackUrl, ct); if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir)) _modelDir = version.ModelDir.Trim('/'); + if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version)) + _launcherVersion = version.Launcher.Version.Trim(); return version; } + /// 最近一次读到的清单原文(SAVEDOG 二次验签用)。 + public Task GetRawVersionTextAsync(CancellationToken ct) + => Task.FromResult(_rawManifest); + + /// + /// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是 + /// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。 + /// + internal void SetLauncherVersion(string? version) + { + if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim(); + } + private async Task ReadVersionFromAsync(string url, CancellationToken ct) { string text; @@ -107,10 +126,20 @@ public sealed class GitCodeRemote : IModelRemote payload = Encoding.UTF8.GetString(raw); } if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null; - var version = System.Text.Json.JsonSerializer.Deserialize( - payload, GC.Services.Json.Options); + + // 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」 + var version = ManifestLoader.Parse(payload, out var verification); + if (version == null) return null; + // 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单 - return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null; + if (string.IsNullOrWhiteSpace(version.Generated)) return null; + + if (verification.Trust == ManifestTrust.Invalid) + Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}"); + + if (version != null && !string.IsNullOrWhiteSpace(version.Generated)) + _rawManifest = payload; + return version; } catch (Exception ex) { @@ -283,25 +312,129 @@ public sealed class GitCodeRemote : IModelRemote public async Task DownloadPackageAsync(RepoPackage package, CancellationToken ct) { - string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim(); - if (url == null && !string.IsNullOrWhiteSpace(package.Path)) + // 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。 + var direct = await TryFetchAsync(package.Url, package.Sha256, ct); + if (direct != null) return direct; + + // url 不可用或校验不符:再去找仓库里的编译产物。 + // 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。 + // 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个, + // 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。 + foreach (var path in LauncherArtifacts.CandidateFiles( + package.Rid, package.Dir, package.Path, package.Name, _launcherVersion)) { - try + var url = await ResolveFileUrlAsync(path, ct); + var bytes = await TryFetchAsync(url, package.Sha256, ct); + if (bytes != null) return bytes; + } + + foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir)) + { + var url = await FindZipInDirAsync(dir, package, ct); + var bytes = await TryFetchAsync(url, package.Sha256, ct); + if (bytes != null) return bytes; + } + + Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)"); + return null; + } + + /// 下载一个候选地址; 非空时必须与内容一致。 + private async Task TryFetchAsync(string? url, string? sha256, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(url)) return null; + + byte[] bytes; + try { bytes = await _http.GetByteArrayAsync(url!, ct); } + catch (Exception ex) + { + Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}"); + return null; + } + if (bytes.Length == 0) return null; + + if (!string.IsNullOrWhiteSpace(sha256)) + { + var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase)) { - var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch; - var text = await _http.GetStringAsync(apiUrl, ct); - using var doc = JsonDocument.Parse(text); - if (doc.RootElement.TryGetProperty("download_url", out var dl)) - url = dl.GetString(); - } - catch (Exception ex) - { - Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}"); + Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}"); return null; } } - if (string.IsNullOrWhiteSpace(url)) return null; - return await _http.GetByteArrayAsync(url!, ct); + + Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}"); + return bytes; + } + + private static string Short(string url) + => url.Length <= 96 ? url : url[..60] + "…" + url[^24..]; + + /// 把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。 + private async Task ResolveFileUrlAsync(string path, CancellationToken ct) + { + try + { + var url = _api + path.Trim('/') + "?ref=" + _branch; + var text = await _http.GetStringAsync(url, ct); + if (!text.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null; + + using var doc = JsonDocument.Parse(text); + if (doc.RootElement.TryGetProperty("type", out var type) && + string.Equals(type.GetString(), "dir", StringComparison.OrdinalIgnoreCase)) + return null; + return doc.RootElement.TryGetProperty("download_url", out var dl) + ? dl.GetString() : null; + } + catch (Exception) + { + return null; // 404 / 网络问题都当作「这个路径没有」 + } + } + + /// + /// 在 里找启动器包。 + /// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则), + /// 最终仍由 sha256 兜底。 + /// + private async Task FindZipInDirAsync(string dir, RepoPackage package, CancellationToken ct) + { + try + { + var url = _api + dir.Trim('/') + "?ref=" + _branch; + var text = await _http.GetStringAsync(url, ct); + if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return null; + + var zips = new List<(string Path, string Name)>(); + using (var doc = JsonDocument.Parse(text)) + { + foreach (var item in doc.RootElement.EnumerateArray()) + { + if (Str(item, "type") != "file") continue; + var name = Str(item, "name"); + if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) continue; + var path = Str(item, "path"); + zips.Add((path.Length > 0 ? path : dir + "/" + name, name)); + } + } + if (zips.Count == 0) return null; + + var version = _launcherVersion; + var match = zips.FindIndex(z => + LauncherArtifacts.LooksLikePackage(z.Name, version, package.Rid)); + if (match < 0) + { + if (zips.Count != 1) return null; + match = 0; + } + + Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}"); + return await ResolveFileUrlAsync(zips[match].Path, ct); + } + catch (Exception) + { + return null; + } } private static string Str(JsonElement item, string name) diff --git a/GC-DOWNLOAD/GiteaRemote.cs b/GC-DOWNLOAD/GiteaRemote.cs index 855eba5..aa33b47 100644 --- a/GC-DOWNLOAD/GiteaRemote.cs +++ b/GC-DOWNLOAD/GiteaRemote.cs @@ -23,6 +23,7 @@ public sealed class GiteaRemote : IModelRemote { private readonly SourcePreset _preset; private static readonly HttpClient Http = CreateHttp(); + private string? _rawManifest; private static HttpClient CreateHttp() { @@ -69,7 +70,18 @@ public sealed class GiteaRemote : IModelRemote // Release 提供启动器版本与平台附件 result.Launcher.Version = fromRelease.Launcher.Version; foreach (var kv in fromRelease.Launcher.Packages) + { + // Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256, + // 否则「有仓库写权限的人发个 Release」就能绕过验签。 + if (fromRepo != null && + fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) && + !string.IsNullOrWhiteSpace(signed?.Sha256)) + { + kv.Value.Sha256 = signed!.Sha256; + if (signed.Size > 0) kv.Value.Size = signed.Size; + } result.Launcher.Packages[kv.Key] = kv.Value; + } return result; } @@ -81,6 +93,10 @@ public sealed class GiteaRemote : IModelRemote // 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级 return result.Models.Count > 0 ? result : null; } + /// 最近一次读到的清单原文(SAVEDOG 二次验签用)。 + public Task GetRawVersionTextAsync(CancellationToken ct) + => Task.FromResult(_rawManifest); + /// 读仓库里的 version.json(模型清单 + 兜底信息)。 private async Task TryGetVersionFromRepoAsync(CancellationToken ct) { @@ -90,8 +106,14 @@ public sealed class GiteaRemote : IModelRemote { var text = await Http.GetStringAsync(url, ct); if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML - var doc = JsonSerializer.Deserialize(text, Json.Options); - if (doc != null) return doc; + var doc = ManifestLoader.Parse(text, out var verification); + if (verification.Trust == ManifestTrust.Invalid) + Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}"); + if (doc != null) + { + _rawManifest = text; + return doc; + } } catch (Exception ex) { @@ -282,12 +304,35 @@ public sealed class GiteaRemote : IModelRemote public async Task DownloadPackageAsync(RepoPackage package, CancellationToken ct) { - if (string.IsNullOrWhiteSpace(package.Url)) return null; - try { return await Http.GetByteArrayAsync(package.Url, ct); } - catch (Exception ex) + // 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。 + // 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。 + var candidates = new List(); + if (!string.IsNullOrWhiteSpace(package.Url)) candidates.Add(package.Url!.Trim()); + foreach (var path in LauncherArtifacts.CandidateFiles( + package.Rid, package.Dir, package.Path, package.Name, "")) + candidates.Add(_preset.RawUrl(path)); + + foreach (var candidate in candidates) { - Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}"); - return null; + byte[] bytes; + try { bytes = await Http.GetByteArrayAsync(candidate, ct); } + catch (Exception) { continue; } + if (bytes.Length == 0) continue; + + if (!string.IsNullOrWhiteSpace(package.Sha256)) + { + var actual = Convert.ToHexString( + System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant(); + if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase)) + { + Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}"); + continue; + } + } + + Console.WriteLine($"[gitea] 启动器包来源: {candidate}"); + return bytes; } + return null; } } diff --git a/GC-DOWNLOAD/LauncherArtifacts.cs b/GC-DOWNLOAD/LauncherArtifacts.cs new file mode 100644 index 0000000..6ec7328 --- /dev/null +++ b/GC-DOWNLOAD/LauncherArtifacts.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; + +namespace GC.Services; + +/// +/// 平台标签与「仓库里的编译产物位置」的推导规则。 +/// +/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物 +/// 提交(或上传)到仓库的 dist/<系统>-<架构> 目录,例如 +/// dist/mac-arm64/GC-1.0.7-mac-arm64.zip,根本没有发 Release。 +/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。 +/// +/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的 +/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单, +/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。 +/// +/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译, +/// 保证「写进清单的路径」与「运行时找的路径」永远一致。 +/// +public static class LauncherArtifacts +{ + /// + /// RID → 文件名里的「系统-架构」标签(与 LauncherUpdater.PlatformLabel 一致)。 + /// + public static string LabelOf(string rid) => rid switch + { + "win-x64" => "win-amd64", + "win-arm64" => "win-arm64", + "osx-arm64" => "mac-arm64", + "osx-x64" => "mac-x64", + "linux-x64" => "linux-amd64", + _ => rid + }; + + /// + /// 同一平台在仓库里可能用的目录名(按优先级)。 + /// 既接受 mac-arm64 这种标签,也接受 osx-arm64 这种 RID, + /// 因为 dist 目录名历史上两种写法都出现过。 + /// + public static IReadOnlyList PlatformAliases(string rid) + { + var label = LabelOf(rid); + if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase)) + return new[] { rid }; + return new[] { label, rid }; + } + + /// 启动器包应有的文件名,如 GC-1.0.7-mac-arm64.zip。 + public static string PackageFileName(string version, string rid) + => $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip"; + + /// + /// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。 + /// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。 + /// + public static bool LooksLikePackage(string fileName, string version, string rid) + { + if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false; + if (!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false; + + var v = version.Trim().TrimStart('v', 'V'); + if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false; + + var haystack = fileName.ToLowerInvariant(); + foreach (var alias in PlatformAliases(rid)) + if (haystack.Contains(alias.ToLowerInvariant(), StringComparison.Ordinal)) + return true; + + return haystack.Contains(rid.ToLowerInvariant(), StringComparison.Ordinal); + } + + /// + /// 候选目录:清单显式给的 dir 优先,其次是 dist/<标签> 与 dist/<RID>。 + /// + public static IReadOnlyList CandidateDirs(string rid, string? declaredDir) + { + var dirs = new List(); + if (!string.IsNullOrWhiteSpace(declaredDir)) + dirs.Add(declaredDir!.Trim().Trim('/')); + + foreach (var alias in PlatformAliases(rid)) + dirs.Add("dist/" + alias); + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (var dir in dirs) + if (dir.Length > 0 && seen.Add(dir)) result.Add(dir); + return result; + } + + /// + /// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。 + /// + public static IReadOnlyList CandidateFiles(string rid, string? declaredDir, + string? declaredPath, string? declaredName, string version) + { + var files = new List(); + if (!string.IsNullOrWhiteSpace(declaredPath)) + files.Add(declaredPath!.Trim().Trim('/')); + + if (!string.IsNullOrWhiteSpace(declaredName)) + foreach (var dir in CandidateDirs(rid, declaredDir)) + files.Add(dir + "/" + declaredName!.Trim()); + + if (version.Length > 0) + { + files.Add("dist/" + PackageFileName(version, rid)); + foreach (var alias in PlatformAliases(rid)) + files.Add($"dist/GC-{version.Trim().TrimStart('v', 'V')}-{alias}.zip"); + } + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (var file in files) + if (file.Length > 0 && seen.Add(file)) result.Add(file); + return result; + } +} diff --git a/GC-DOWNLOAD/LauncherUpdater.cs b/GC-DOWNLOAD/LauncherUpdater.cs index 95455ae..93be0a8 100644 --- a/GC-DOWNLOAD/LauncherUpdater.cs +++ b/GC-DOWNLOAD/LauncherUpdater.cs @@ -303,48 +303,120 @@ public static class LauncherUpdater !version.Launcher.Packages.TryGetValue("default", out pkg)) return Fail($"该平台({rid})没有对应发布包"); + // ---- 信任闸门 --------------------------------------------------- + // 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。 + // 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。 + var allowUnsigned = + Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1"; + + if (!version.IsTrusted && !allowUnsigned) + { + var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid) + ? "清单签名无效" + : "清单未签名"; + Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}"); + return Fail($"{reason},已拒绝下载启动器更新"); + } + + if (string.IsNullOrWhiteSpace(pkg!.Sha256)) + { + Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新"); + return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)"); + } + progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" }); var bytes = await remote.DownloadPackageAsync(pkg!, ct); if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空"); - // sha256 校验(Release 提供时) - if (!string.IsNullOrWhiteSpace(pkg!.Sha256)) + // sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义) { var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase)) - return Fail("下载文件校验失败(sha256 不符)"); + return Fail("下载文件校验失败(sha256 与已签名清单不符)"); } - progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压更新包" }); + progress?.Report(new UpdateProgressInfo { Value = 0.55, Stage = "正在校验更新包" }); - // 更新包先完整保存在下载目录,重启替换脚本再移入安装目录。 - var staging = Path.Combine(paths.CacheRoot, "launcher-staging"); - if (Directory.Exists(staging)) Directory.Delete(staging, true); - Directory.CreateDirectory(staging); + var updateRoot = paths.UpdateRoot; + Directory.CreateDirectory(updateRoot); - var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip"); + // 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录", + // 避免「解压后被替换」的中间窗口。 + var zip = Path.Combine(updateRoot, "package.zip"); + if (File.Exists(zip)) File.Delete(zip); await File.WriteAllBytesAsync(zip, bytes, ct); - try { ZipSafety.ExtractToDirectory(zip, staging); } - finally { try { File.Delete(zip); } catch { } } - // 只展平「单个非 .app 顶层目录」的 zip - FlattenStaging(staging); + try + { + var inspection = SafeArchive.Inspect(zip); + Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," + + $"{inspection.UncompressedBytes / 1024 / 1024} MB"); + } + catch (Exception ex) + { + try { File.Delete(zip); } catch { } + return Fail("更新包安全性检查失败: " + ex.Message); + } - progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在暂存新版本" }); + // 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了" + var rawManifest = await remote.GetRawVersionTextAsync(ct); + var manifestCopy = Path.Combine(updateRoot, "version.json"); + if (!string.IsNullOrWhiteSpace(rawManifest)) + File.WriteAllText(manifestCopy, rawManifest!); + else if (File.Exists(manifestCopy)) + File.Delete(manifestCopy); - var payload = Path.Combine(paths.UpdateRoot, "payload"); - if (Directory.Exists(payload)) Directory.Delete(payload, true); - Directory.CreateDirectory(payload); - var packageName = MoveToPayload(staging, payload); - try { Directory.Delete(staging, true); } catch { } - if (packageName == null) return Fail("解压结果里没有找到新版启动器"); + // 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层) + var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe"); - // 写标记(纯文本,脚本读它):只含相对信息,无绝对路径 - Directory.CreateDirectory(paths.UpdateRoot); - File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"), - $"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" + - $"INSTALL_REL={Path.GetRelativePath(paths.UpdateRoot, paths.InstallDirectory)}\n"); + var request = new SavedogRequest + { + Version = latest, + Rid = rid, + PlatformLabel = PlatformLabel, + PackageName = packageName, + PackageZip = "package.zip", + PayloadDir = "payload", + ManifestPath = "version.json", + PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(), + PackageSize = bytes.LongLength, + RequireSignature = version.IsTrusted, + InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory), + CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") + }; + Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request); + + // 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换 + string? legacyPath = null; + if (SavedogLauncher.Find(paths) == null) + { + Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程"); + progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" }); + + var staging = Path.Combine(paths.CacheRoot, "launcher-staging"); + if (Directory.Exists(staging)) Directory.Delete(staging, true); + Directory.CreateDirectory(staging); + SafeArchive.ExtractToDirectory(zip, staging); + FlattenStaging(staging); + + var payload = Path.Combine(updateRoot, "payload"); + if (Directory.Exists(payload)) Directory.Delete(payload, true); + Directory.CreateDirectory(payload); + var legacyName = MoveToPayload(staging, payload); + try { Directory.Delete(staging, true); } catch { } + if (legacyName == null) return Fail("解压结果里没有找到新版启动器"); + + packageName = legacyName; + request.PackageName = legacyName; + Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request); + legacyPath = Path.Combine(payload, legacyName); + + // 老脚本读这个纯文本标记,只含相对信息 + File.WriteAllText(Path.Combine(updateRoot, "update.txt"), + $"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" + + $"INSTALL_REL={request.InstallRelative}\n"); + } progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" }); @@ -354,7 +426,7 @@ public static class LauncherUpdater Version = latest, Message = $"v{latest} 已暂存到 .GC/update", PackageName = packageName, - NewAppPath = Path.Combine(payload, packageName) + NewAppPath = legacyPath }; } catch (OperationCanceledException) { return Fail("已取消"); } @@ -370,15 +442,13 @@ public static class LauncherUpdater // ---------------------------------------------------------------- 应用(下次启动) /// - /// 生成替换脚本并启动。脚本等本进程退出后: - /// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。 + /// 安排应用已下载的新版。 + /// 首选 GC-SAVEDOG:二次验签、原子替换、启动后健康检查、失败自动回滚; + /// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。 /// 返回 true 表示调用方应立即退出进程。 /// public static bool ScheduleApply(AppPaths paths, string packageName) { - var marker = Path.Combine(paths.UpdateRoot, "update.txt"); - if (!File.Exists(marker)) return false; - // 安全阀:绝不在源码目录执行替换(防止误删源码) if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln"))) { @@ -386,6 +456,17 @@ public static class LauncherUpdater return false; } + if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest))) + { + string? savedogError = null; + if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError)) + return true; + Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本"); + } + + var marker = Path.Combine(paths.UpdateRoot, "update.txt"); + if (!File.Exists(marker)) return false; + try { var isWin = OperatingSystem.IsWindows(); @@ -420,13 +501,30 @@ public static class LauncherUpdater } } - /// 启动时若有待应用更新,安排脚本并让 Main 直接退出。 + /// 启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。 public static bool TryApplyPending(AppPaths paths) { if (paths.IsDevelopment) return false; if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false; if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false; + // 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签) + var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest); + if (File.Exists(requestPath)) + { + var request = Json.Read(requestPath); + var zipPath = request == null + ? null + : Path.Combine(paths.UpdateRoot, request.PackageZip); + + if (request != null && zipPath != null && File.Exists(zipPath)) + return ScheduleApply(paths, request.PackageName); + + Console.Error.WriteLine("[update] 更新申请不完整,已清理"); + try { File.Delete(requestPath); } catch { } + } + + // 旧协议:update.txt + payload(从老版本升级时仍可能遇到) var marker = Path.Combine(paths.UpdateRoot, "update.txt"); if (!File.Exists(marker)) return false; diff --git a/GC-DOWNLOAD/SavedogLauncher.cs b/GC-DOWNLOAD/SavedogLauncher.cs new file mode 100644 index 0000000..7534336 --- /dev/null +++ b/GC-DOWNLOAD/SavedogLauncher.cs @@ -0,0 +1,121 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; + +namespace GC.Services; + +/// +/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。 +/// +/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败, +/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序, +/// 风险面被压缩到最小,也便于审计。 +/// +public static class SavedogLauncher +{ + /// 在安装目录里寻找 SAVEDOG 可执行文件。 + public static string? Find(AppPaths paths) + { + var name = SavedogFiles.ExecutableName; + var install = paths.InstallDirectory; + + var direct = Path.Combine(install, name); + if (File.Exists(direct)) return direct; + + // macOS:可能放在 .app 内部 + try + { + foreach (var app in Directory.GetDirectories(install, "*.app")) + { + var inside = Path.Combine(app, "Contents", "MacOS", name); + if (File.Exists(inside)) return inside; + } + } + catch { } + + var bin = Path.Combine(paths.HomeRoot, "bin", name); + if (File.Exists(bin)) return bin; + + try + { + var exe = Environment.ProcessPath; + if (!string.IsNullOrWhiteSpace(exe)) + { + var beside = Path.Combine(Path.GetDirectoryName(exe)!, name); + if (File.Exists(beside)) return beside; + } + } + catch { } + + return null; + } + + /// + /// 启动 SAVEDOG 应用更新。 是当前启动器进程, + /// SAVEDOG 会等它退出后再动文件。 + /// + public static bool TryStart(AppPaths paths, int waitForPid, out string? error) + { + error = null; + var exe = Find(paths); + if (exe == null) + { + error = "未找到 GC-SAVEDOG"; + return false; + } + + try + { + var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest); + if (!File.Exists(requestPath)) + { + error = "缺少 apply-request.json"; + return false; + } + + var psi = new ProcessStartInfo(exe) + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = paths.InstallDirectory + }; + psi.ArgumentList.Add("apply"); + psi.ArgumentList.Add("--update"); + psi.ArgumentList.Add(paths.UpdateRoot); + psi.ArgumentList.Add("--install"); + psi.ArgumentList.Add(paths.InstallDirectory); + psi.ArgumentList.Add("--wait-pid"); + psi.ArgumentList.Add(waitForPid.ToString()); + psi.ArgumentList.Add("--timeout"); + psi.ArgumentList.Add("45"); + + if (!OperatingSystem.IsWindows()) + { + try + { + var mode = File.GetUnixFileMode(exe); + File.SetUnixFileMode(exe, mode | UnixFileMode.UserExecute); + } + catch { } + } + + Process.Start(psi); + Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}"); + return true; + } + catch (Exception ex) + { + error = ex.Message; + return false; + } + } + + /// 读取 SAVEDOG 最近一次的执行结果(供界面展示)。 + public static SavedogState? ReadState(AppPaths paths) + => Json.Read(Path.Combine(paths.UpdateRoot, SavedogFiles.State)); + + /// 上次成功启动的版本(回滚依据)。 + public static LastGoodVersion? ReadLastGood(AppPaths paths) + => Json.Read(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood)); +} diff --git a/GC-DOWNLOAD/UpdateService.cs b/GC-DOWNLOAD/UpdateService.cs index 79a14ac..777e659 100644 --- a/GC-DOWNLOAD/UpdateService.cs +++ b/GC-DOWNLOAD/UpdateService.cs @@ -104,6 +104,37 @@ public sealed class UpdateService : IUpdateService Message = L.I["update.noManifest"] }; + // ---- 清单信任策略 -------------------------------------------------- + // 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。 + // 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。 + var allowUnsigned = devMode || + !_settings.Current.RequireSignedManifest || + Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1"; + + if (!remote.IsTrusted) + { + var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid) + ? "清单签名无效(内容可能被篡改)" + : "清单未签名"; + + if (!allowUnsigned) + { + Console.Error.WriteLine($"[update] {reason},已拒绝本次更新"); + return new UpdateResult + { + Outcome = UpdateOutcome.Unavailable, + Message = $"{reason},已拒绝更新", + Error = remote.SignatureError + }; + } + + Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续"); + } + else + { + Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})"); + } + _settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O"); _settings.Save(); @@ -248,6 +279,22 @@ public sealed class UpdateService : IUpdateService await Task.WhenAll(tasks); + // ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 -------- + // 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。 + var computed = ModelIntegrity.Compute(staging, model.Id); + + if (!string.IsNullOrWhiteSpace(model.ManifestSha256) && + !string.Equals(computed.ManifestSha256, model.ManifestSha256, + StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException( + $"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})"); + + if (!string.IsNullOrWhiteSpace(model.FilesSha256) && + !string.Equals(computed.FilesSha256, model.FilesSha256, + StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException( + $"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃"); + // 原子替换:先备份旧目录,成功后再删备份;失败自动回滚 Directory.CreateDirectory(_paths.ModelRoot); var target = Path.Combine(_paths.ModelRoot, model.Id); @@ -270,6 +317,25 @@ public sealed class UpdateService : IUpdateService { try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ } } + + // 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次 + try + { + ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile + { + Id = model.Id, + Version = model.Version, + ManifestSha256 = computed.ManifestSha256, + FilesSha256 = computed.FilesSha256, + Files = computed.Files, + InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), + Source = _remote.DisplayName + }); + } + catch (Exception ex) + { + Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}"); + } } catch { @@ -283,4 +349,7 @@ public sealed class UpdateService : IUpdateService foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-'); return value.Replace('/', '-').Replace(' ', '-'); } + + private static string Short(string? hash) + => string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8]; } diff --git a/GC-DOWNLOAD/ZipSafety.cs b/GC-DOWNLOAD/ZipSafety.cs index 997d0b8..4a96ead 100644 --- a/GC-DOWNLOAD/ZipSafety.cs +++ b/GC-DOWNLOAD/ZipSafety.cs @@ -1,36 +1,22 @@ using System; using System.IO; -using System.IO.Compression; namespace GC.Services; /// -/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符), -/// 并在解压前逐条校验目标路径完整落在目标目录内。 +/// 安全解压的统一入口(实现在 )。 +/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用, +/// 真正的校验逻辑集中在一处,避免两套实现走偏。 /// public static class ZipSafety { public static void ExtractToDirectory(string zipPath, string destination) { - var destFull = Path.GetFullPath(destination) - .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; - - using (var archive = ZipFile.OpenRead(zipPath)) - { - foreach (var entry in archive.Entries) - { - var name = entry.FullName.Replace('\\', '/'); - if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) || - (name.Length >= 2 && name[1] == ':')) - throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}"); - - var target = Path.GetFullPath(Path.Combine(destFull, name)); - if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase)) - throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}"); - } - } - - // 校验通过后交给框架解压(保留 overwrite 语义) - ZipFile.ExtractToDirectory(zipPath, destination, true); + if (!File.Exists(zipPath)) + throw new FileNotFoundException("压缩包不存在", zipPath); + SafeArchive.ExtractToDirectory(zipPath, destination); } + + /// 只检查不落盘:给下载完成后的预检用。 + public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath); } diff --git a/GC-SAVEDOG/Applier.cs b/GC-SAVEDOG/Applier.cs new file mode 100644 index 0000000..3b2d5b4 --- /dev/null +++ b/GC-SAVEDOG/Applier.cs @@ -0,0 +1,552 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using GC.Services; + +namespace GC.Savedog; + +internal sealed class ApplyOptions +{ + public string UpdateDir { get; set; } = ""; + public string? InstallDir { get; set; } + public int WaitPid { get; set; } + public int TimeoutSeconds { get; set; } = 45; + public bool RequireSignature { get; set; } = true; + public bool DryRun { get; set; } + public bool Force { get; set; } +} + +/// +/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。 +/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。 +/// +internal sealed class Applier +{ + private static readonly Regex ArtifactPattern = new( + @"^GC-(?.+?)-(?[^\-]+-[^\-]+)\.(app|exe)$", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private readonly ApplyOptions _options; + private readonly Log _log; + + public Applier(ApplyOptions options, Log log) + { + _options = options; + _log = log; + } + + public int Run() + { + var updateDir = Path.GetFullPath(_options.UpdateDir); + var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest); + + if (!File.Exists(requestPath)) + return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3); + + var request = Json.Read(requestPath); + if (request == null || string.IsNullOrWhiteSpace(request.Version)) + return Fail(updateDir, "更新申请内容不完整", 3); + + if (!ValidName(request.PackageName)) + return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3); + + _log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})"); + + // 1. 等旧进程退出(否则 Windows 上文件还被占用) + if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60))) + _log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试"); + + // 2. 安装目录定位与安全检查 + var installDir = string.IsNullOrWhiteSpace(_options.InstallDir) + ? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative)) + : Path.GetFullPath(_options.InstallDir!); + + if (!Directory.Exists(installDir)) + return Fail(updateDir, "安装目录不存在: " + installDir, 4); + + if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln"))) + return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4); + + // 3. 二次验签:不信任「启动器说它验过了」 + var require = request.RequireSignature && SignatureKeyring.Enforced; + var manifestPath = Path.Combine(updateDir, request.ManifestPath); + var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null; + var verification = ManifestSignature.Verify(manifestText, require); + + if (verification.IsRejected) + { + _log.Error($"清单验签失败({verification.Trust}):{verification.Error}"); + return Refuse(updateDir, request, verification); + } + _log.Info($"清单可信度:{verification.Trust}" + + (verification.KeyId != null ? $"({verification.KeyId})" : "")); + + // 4. 校验更新包 + var zipPath = Path.Combine(updateDir, request.PackageZip); + if (!File.Exists(zipPath)) + return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5); + + var zipInfo = new FileInfo(zipPath); + if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize) + return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5); + + var actualSha = ContentHash.Sha256File(zipPath); + if (!string.IsNullOrWhiteSpace(request.PackageSha256) && + !string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase)) + { + return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5); + } + if (string.IsNullOrWhiteSpace(request.PackageSha256)) + _log.Warn("清单没有提供 sha256,仅依赖签名与解压校验"); + + SafeArchive.Inspection inspection; + try + { + inspection = SafeArchive.Inspect(zipPath); + _log.Info($"更新包检查通过:{inspection.Entries} 个条目," + + $"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1"); + } + catch (Exception ex) + { + return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5); + } + + // 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的) + var stage = Path.Combine(updateDir, "stage"); + ClearDirectory(stage); + try + { + SafeArchive.ExtractToDirectory(zipPath, stage); + FlattenSingleDirectory(stage); + } + catch (Exception ex) + { + ClearDirectory(stage); + return Fail(updateDir, "解压失败: " + ex.Message, 6); + } + + var artifact = FindArtifact(stage, request.PackageName); + if (artifact == null) + { + ClearDirectory(stage); + return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6); + } + + var target = Path.Combine(installDir, Path.GetFileName(artifact)); + var alreadyInstalled = File.Exists(target) || Directory.Exists(target); + + if (_options.DryRun) + { + _log.Info($"[dry-run] 校验全部通过,将安装到 {target}"); + ClearDirectory(stage); + return 0; + } + + if (alreadyInstalled) + { + // 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件 + _log.Info("目标版本已存在,视为已安装"); + ClearDirectory(stage); + TryDelete(zipPath); + TryDelete(requestPath); + WriteState(updateDir, new SavedogState + { + Status = "applied", + Version = request.Version, + PackageName = Path.GetFileName(artifact), + Verified = true, + Message = "目标版本已存在,无需替换" + }); + return 0; + } + + // 6. 移入安装目录(不覆盖任何已有文件) + try + { + Directory.CreateDirectory(installDir); + if (Directory.Exists(artifact)) Directory.Move(artifact, target); + else File.Move(artifact, target); + _log.Info("新版已就位: " + Path.GetFileName(target)); + } + catch (Exception ex) + { + ClearDirectory(stage); + return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7); + } + + // 7. 启动并看护 + var previous = ReadLastGood(updateDir); + StartupHealth.Clear(updateDir); + + Process? child; + try + { + child = Launch(target); + } + catch (Exception ex) + { + child = null; + _log.Error("启动新版失败: " + ex.Message); + } + + var healthy = child != null && WaitForHealth(updateDir, request.Version, child, + TimeSpan.FromSeconds(_options.TimeoutSeconds)); + + if (healthy) + { + _log.Info($"v{request.Version} 启动正常,更新完成"); + CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel); + WriteLastGood(updateDir, request.Version, Path.GetFileName(target)); + WriteState(updateDir, new SavedogState + { + Status = "applied", + Version = request.Version, + PreviousVersion = previous?.Version, + PackageName = Path.GetFileName(target), + Verified = true, + Message = "更新已应用" + }); + ClearDirectory(stage); + TryDelete(zipPath); + TryDelete(requestPath); + return 0; + } + + // 8. 回滚 + _log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚"); + TryKill(child); + var removed = RemoveNewVersion(target); + _log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除"); + + var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel); + WriteState(updateDir, new SavedogState + { + Status = "rolledback", + Version = request.Version, + PreviousVersion = previous?.Version, + PackageName = Path.GetFileName(target), + Verified = true, + Message = restored + ? "新版本未通过启动检查,已回滚到上一个版本" + : "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装" + }); + + ClearDirectory(stage); + TryDelete(zipPath); + TryDelete(requestPath); + return 8; + } + + // ------------------------------------------------------------------ 校验辅助 + + private static bool ValidName(string name) + => name.Length > 0 && name.Length < 200 && + name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 && + (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) || + name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)); + + private static bool WaitForExit(int pid, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + try + { + using var process = Process.GetProcessById(pid); + if (process.HasExited) return true; + } + catch (ArgumentException) { return true; } // 进程已不存在 + catch { return true; } + Thread.Sleep(200); + } + return false; + } + + private static void FlattenSingleDirectory(string stage) + { + var entries = Directory.GetFileSystemEntries(stage); + if (entries.Length != 1 || !Directory.Exists(entries[0])) return; + var inner = entries[0]; + if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return; + + var temp = stage + "-flat"; + if (Directory.Exists(temp)) Directory.Delete(temp, true); + Directory.Move(inner, temp); + Directory.Delete(stage, true); + Directory.Move(temp, stage); + } + + private static string? FindArtifact(string stage, string packageName) + { + var direct = Path.Combine(stage, packageName); + if (File.Exists(direct) || Directory.Exists(direct)) return direct; + + foreach (var entry in Directory.GetFileSystemEntries(stage)) + { + var name = Path.GetFileName(entry); + if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry)) + return entry; + if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry)) + return entry; + } + return null; + } + + // ------------------------------------------------------------------ 启动与看护 + + private Process? Launch(string target) + { + if (Directory.Exists(target)) + { + // .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护 + var macOs = Path.Combine(target, "Contents", "MacOS"); + if (Directory.Exists(macOs)) + { + var exe = Directory.GetFiles(macOs) + .OrderByDescending(f => Path.GetFileName(f) == "GC") + .FirstOrDefault(); + if (exe != null) + { + MakeExecutable(exe); + return StartProcess(exe, Path.GetDirectoryName(exe)!); + } + } + MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC")); + var psi = new ProcessStartInfo("open") { UseShellExecute = false }; + psi.ArgumentList.Add("-n"); + psi.ArgumentList.Add(target); + return Process.Start(psi); + } + + if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + if (!OperatingSystem.IsWindows()) MakeExecutable(target); + return StartProcess(target, Path.GetDirectoryName(target)!); + } + return null; + } + + private static Process? StartProcess(string exe, string workingDirectory) + { + var psi = new ProcessStartInfo(exe) + { + UseShellExecute = false, + WorkingDirectory = workingDirectory + }; + return Process.Start(psi); + } + + private static void MakeExecutable(string path) + { + if (OperatingSystem.IsWindows()) return; + try + { + if (!File.Exists(path)) return; + var mode = File.GetUnixFileMode(path); + File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute | + UnixFileMode.GroupExecute | + UnixFileMode.OtherExecute); + } + catch { } + } + + private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + var health = StartupHealth.Read(updateDir); + if (health != null && health.Ok && SameVersion(health.Version, version)) + { + _log.Info($"收到健康标记(pid {health.Pid})"); + return true; + } + + if (child.HasExited) + { + _log.Error($"新版进程已退出(退出码 {child.ExitCode})"); + return false; + } + Thread.Sleep(250); + } + + // 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行 + if (!child.HasExited) + { + _log.Warn("未收到健康标记,但进程仍在运行,按成功处理"); + return true; + } + return false; + } + + private static bool SameVersion(string a, string b) + => string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase); + + private static string Normalize(string version) + { + var trimmed = version.Trim().TrimStart('v', 'V'); + var parts = trimmed.Split('.'); + var numbers = new List(); + foreach (var part in parts) + { + if (!int.TryParse(part, out var n)) break; + numbers.Add(n.ToString()); + } + while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1); + return numbers.Count == 0 ? trimmed : string.Join('.', numbers); + } + + private static void TryKill(Process? process) + { + if (process == null) return; + try + { + if (!process.HasExited) process.Kill(entireProcessTree: true); + } + catch { } + } + + // ------------------------------------------------------------------ 清理 / 回滚 + + private void CleanupOldVersions(string installDir, string keepName, string platformLabel) + { + foreach (var entry in Directory.GetFileSystemEntries(installDir)) + { + var name = Path.GetFileName(entry); + if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue; + + var match = ArtifactPattern.Match(name); + if (!match.Success) continue; + + var platform = match.Groups["plat"].Value; + if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase)) + { + _log.Info($"保留其它平台版本: {name}"); + continue; + } + + try + { + if (Directory.Exists(entry)) Directory.Delete(entry, true); + else File.Delete(entry); + _log.Info("清理旧版本: " + name); + } + catch (Exception ex) + { + _log.Warn($"清理旧版本失败 {name}: {ex.Message}"); + } + } + } + + private bool RemoveNewVersion(string target) + { + try + { + if (Directory.Exists(target)) Directory.Delete(target, true); + else if (File.Exists(target)) File.Delete(target); + return true; + } + catch (Exception ex) + { + _log.Warn("移除新版失败: " + ex.Message); + return false; + } + } + + private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood, + string platformLabel) + { + // 优先用上次成功的版本;否则挑一个同平台的其它版本 + var candidates = new List(); + if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName)) + candidates.Add(Path.Combine(installDir, lastGood.PackageName)); + + foreach (var entry in Directory.GetFileSystemEntries(installDir)) + { + var name = Path.GetFileName(entry); + var match = ArtifactPattern.Match(name); + if (!match.Success) continue; + if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase)) + continue; + candidates.Add(entry); + } + + foreach (var candidate in candidates) + { + if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue; + try + { + Launch(candidate); + _log.Info("已回滚启动: " + Path.GetFileName(candidate)); + return true; + } + catch (Exception ex) + { + _log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}"); + } + } + return false; + } + + // ------------------------------------------------------------------ 状态文件 + + private void WriteState(string updateDir, SavedogState state) + { + try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); } + catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); } + } + + private int Fail(string updateDir, string message, int code) + { + _log.Error(message); + WriteState(updateDir, new SavedogState { Status = "failed", Message = message }); + return code; + } + + private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification) + { + WriteState(updateDir, new SavedogState + { + Status = "refused", + Version = request.Version, + PackageName = request.PackageName, + Verified = false, + Message = $"清单验签失败:{verification.Error}" + }); + return 2; + } + + private static LastGoodVersion? ReadLastGood(string updateDir) + => Json.Read(Path.Combine(updateDir, SavedogFiles.LastGood)); + + private static void WriteLastGood(string updateDir, string version, string packageName) + { + try + { + Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion + { + Version = version, + PackageName = packageName + }); + } + catch { } + } + + private static void ClearDirectory(string dir) + { + try + { + if (Directory.Exists(dir)) Directory.Delete(dir, true); + } + catch { } + } + + private static void TryDelete(string path) + { + try { if (File.Exists(path)) File.Delete(path); } catch { } + } +} diff --git a/GC-SAVEDOG/GC-SAVEDOG.csproj b/GC-SAVEDOG/GC-SAVEDOG.csproj new file mode 100644 index 0000000..2afe2f7 --- /dev/null +++ b/GC-SAVEDOG/GC-SAVEDOG.csproj @@ -0,0 +1,47 @@ + + + + + Exe + enable + GC.Savedog + GC-SAVEDOG + true + + + true + full + false + + + en + none + + + + + + + + + diff --git a/GC-SAVEDOG/Log.cs b/GC-SAVEDOG/Log.cs new file mode 100644 index 0000000..baf3257 --- /dev/null +++ b/GC-SAVEDOG/Log.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; + +namespace GC.Savedog; + +/// 同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。 +internal sealed class Log +{ + private readonly string? _path; + private readonly object _gate = new(); + + public Log(string? path) => _path = path; + + public void Info(string message) => Write("INFO ", message); + public void Warn(string message) => Write("WARN ", message); + public void Error(string message) => Write("ERROR", message); + + private void Write(string level, string message) + { + var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}"; + Console.WriteLine(line); + if (string.IsNullOrWhiteSpace(_path)) return; + try + { + lock (_gate) + { + var dir = Path.GetDirectoryName(_path!); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.AppendAllText(_path!, line + "\n"); + } + } + catch { /* 日志失败不能影响更新 */ } + } +} diff --git a/GC-SAVEDOG/Program.cs b/GC-SAVEDOG/Program.cs new file mode 100644 index 0000000..a3efa47 --- /dev/null +++ b/GC-SAVEDOG/Program.cs @@ -0,0 +1,347 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using GC.Services; + +namespace GC.Savedog; + +/// +/// GC-SAVEDOG 命令行。 +/// +/// GC-SAVEDOG apply --update <.GC/update> [--install <dir>] [--wait-pid N] +/// [--timeout 45] [--dry-run] [--json] +/// GC-SAVEDOG verify --manifest <version.json> [--require 1] [--json] +/// GC-SAVEDOG verify-model --dir <model/<id>> --id <id> [--json] +/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11] +/// GC-SAVEDOG sign --manifest <version.json> [--key .signing/gc-signing.pem] +/// [--key-id ...] [--out <file>] +/// GC-SAVEDOG status --update <.GC/update> [--json] +/// +internal static class Program +{ + private const string DefaultKeyId = "gc-2026-11"; + private const string DefaultKeyPath = ".signing/gc-signing.pem"; + + private static int Main(string[] args) + { + try { Console.OutputEncoding = Encoding.UTF8; } catch { } + + // 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需) + SavedogJson.Initialize(); + + if (args.Length == 0 || args[0] is "-h" or "--help" or "help") + { + Help(); + return 0; + } + + var command = args[0].ToLowerInvariant(); + var rest = args.Skip(1).ToArray(); + var options = Parse(rest); + + return command switch + { + "apply" => Apply(options), + "verify" => Verify(options), + "verify-model" => VerifyModel(options), + "keygen" => Keygen(options), + "sign" => Sign(options), + "status" => Status(options), + "version" or "--version" => PrintVersion(), + _ => Unknown(command) + }; + } + + // ------------------------------------------------------------------ apply + + private static int Apply(Dictionary options) + { + var updateDir = Option(options, "update", ""); + if (string.IsNullOrWhiteSpace(updateDir)) + { + Console.Error.WriteLine("apply 需要 --update <.GC/update>"); + return 3; + } + + var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log)); + var applyOptions = new ApplyOptions + { + UpdateDir = updateDir, + InstallDir = Option(options, "install", null), + WaitPid = Int(options, "wait-pid", 0), + TimeoutSeconds = Int(options, "timeout", 45), + DryRun = Flag(options, "dry-run"), + Force = Flag(options, "force"), + RequireSignature = Int(options, "require-signature", 1) != 0 + }; + + var applier = new Applier(applyOptions, log); + var code = applier.Run(); + if (Flag(options, "json")) + { + if (applyOptions.DryRun) + { + // dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方 + var request = Json.Read( + Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest)); + Console.WriteLine(Json.Serialize(new SavedogState + { + Status = code == 0 ? "checked" : "failed", + Version = request?.Version ?? "", + PackageName = request?.PackageName ?? "", + Verified = code == 0, + Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)" + })); + } + else + { + var state = Json.Read( + Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State)); + Console.WriteLine(Json.Serialize(state)); + } + } + return code; + } + + // ------------------------------------------------------------------ verify + + private static int Verify(Dictionary options) + { + var manifest = Option(options, "manifest", ""); + if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest)) + { + Console.Error.WriteLine("verify 需要 --manifest "); + return 3; + } + + var require = Int(options, "require", 1) != 0; + var text = File.ReadAllText(manifest); + var result = ManifestSignature.Verify(text, require); + + if (Flag(options, "json")) + { + var report = new VerifyReport + { + Trust = result.Trust.ToString(), + KeyId = result.KeyId, + Error = result.Error + }; + foreach (var key in SignatureKeyring.Keys) + report.TrustedKeys.Add(new TrustedKey + { + KeyId = key.KeyId, + Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64) + }); + Console.WriteLine(Json.Serialize(report)); + } + else + { + Console.WriteLine($"信任状态: {result.Trust}"); + if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}"); + if (result.Error != null) Console.WriteLine($"说明: {result.Error}"); + foreach (var key in SignatureKeyring.Keys) + Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})"); + } + + return result.IsTrusted ? 0 : 2; + } + + private static int VerifyModel(Dictionary options) + { + var dir = Option(options, "dir", ""); + var id = Option(options, "id", ""); + if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id)) + { + Console.Error.WriteLine("verify-model 需要 --dir --id <模型 id>"); + return 3; + } + + var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id); + if (Flag(options, "json")) + Console.WriteLine(Json.Serialize(new VerifyModelReport + { + Ok = result.Ok, + Present = result.Present, + Message = result.Message + })); + else + Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}"); + + return result.Ok ? 0 : 2; + } + + // ------------------------------------------------------------------ keygen / sign + + private static int Keygen(Dictionary options) + { + var outDir = Option(options, "out", ".signing")!; + var keyId = Option(options, "key-id", DefaultKeyId)!; + Directory.CreateDirectory(outDir); + + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var privatePath = Path.Combine(outDir, "gc-signing.pem"); + var publicPath = Path.Combine(outDir, "gc-signing.pub"); + + File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem()); + var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key); + File.WriteAllText(publicPath, publicBase64 + "\n"); + + try + { + if (!OperatingSystem.IsWindows()) + File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + catch { } + + Console.WriteLine("已生成 ECDSA P-256 密钥对:"); + Console.WriteLine(" 私钥(绝不要提交): " + privatePath); + Console.WriteLine(" 公钥(写进源码) : " + publicPath); + Console.WriteLine(" keyId : " + keyId); + Console.WriteLine(" 公钥 Base64 : " + publicBase64); + Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64)); + Console.WriteLine(); + Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:"); + Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),"); + return 0; + } + + private static int Sign(Dictionary options) + { + var manifest = Option(options, "manifest", ""); + var keyPath = Option(options, "key", DefaultKeyPath)!; + var keyId = Option(options, "key-id", + Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!; + + if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest)) + { + Console.Error.WriteLine("sign 需要 --manifest "); + return 3; + } + + using var key = ManifestSignature.TryLoadPrivateKey(keyPath); + if (key == null) + { + Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}"); + return 4; + } + + var text = File.ReadAllText(manifest); + var signed = ManifestSignature.SignDocument(text, key, keyId); + var output = Option(options, "out", manifest)!; + File.WriteAllText(output, signed); + + var check = ManifestSignature.Verify(signed, requireSignature: true); + Console.WriteLine($"已签名: {output}({check.Trust})"); + return check.Trust == ManifestTrust.Verified ? 0 : 5; + } + + // ------------------------------------------------------------------ status + + private static int Status(Dictionary options) + { + var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!); + var state = Json.Read(Path.Combine(updateDir, SavedogFiles.State)); + var lastGood = Json.Read(Path.Combine(updateDir, SavedogFiles.LastGood)); + var health = StartupHealth.Read(updateDir); + + if (Flag(options, "json")) + { + Console.WriteLine(Json.Serialize(new StatusReport + { + State = state, + LastGood = lastGood, + Health = health + })); + return 0; + } + + Console.WriteLine(state == null + ? "没有更新记录" + : $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})"); + Console.WriteLine(lastGood == null + ? "上次成功版本: 未知" + : $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})"); + Console.WriteLine(health == null + ? "健康标记: 无" + : $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}"); + return 0; + } + + private static int PrintVersion() + { + Console.WriteLine("GC-SAVEDOG 1.0.0"); + Console.WriteLine("签名算法: " + ManifestSignature.Algorithm); + return 0; + } + + private static int Unknown(string command) + { + Console.Error.WriteLine($"未知命令: {command}"); + Help(); + return 3; + } + + private static void Help() + { + Console.WriteLine(""" +GC-SAVEDOG —— 启动器更新守护进程 + + apply --update <.GC/update> [--install ] [--wait-pid N] + [--timeout 45] [--dry-run] [--force] [--json] + verify --manifest [--require 1] [--json] + verify-model --dir --id [--json] + keygen [--out .signing] [--key-id gc-2026-11] + sign --manifest [--key .signing/gc-signing.pem] [--out ] + status --update <.GC/update> [--json] + +退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚 +"""); + } + + // ------------------------------------------------------------------ 参数 + + private static Dictionary Parse(string[] args) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < args.Length; i++) + { + var arg = args[i]; + if (!arg.StartsWith("--", StringComparison.Ordinal)) + { + map[arg] = "1"; + continue; + } + + var name = arg[2..]; + var eq = name.IndexOf('='); + if (eq > 0) + { + map[name[..eq]] = name[(eq + 1)..]; + continue; + } + + if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + map[name] = args[++i]; + continue; + } + map[name] = "1"; + } + return map; + } + + private static string? Option(Dictionary options, string name, string? fallback) + => options.TryGetValue(name, out var value) ? value : fallback; + + private static int Int(Dictionary options, string name, int fallback) + => options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed) + ? parsed : fallback; + + private static bool Flag(Dictionary options, string name) + => options.TryGetValue(name, out var value) && + (value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)); +} diff --git a/GC-SAVEDOG/SavedogJson.cs b/GC-SAVEDOG/SavedogJson.cs new file mode 100644 index 0000000..80c3d32 --- /dev/null +++ b/GC-SAVEDOG/SavedogJson.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using GC.Services; + +namespace GC.Savedog; + +/// +/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效: +/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛 +/// NotSupportedException。因此守护进程把所有 JSON 类型都注册进源生成上下文, +/// 编译期生成类型信息,运行时零反射。 +/// +/// 新增需要读写的 JSON 类型时,记得在这里补一行 [JsonSerializable], +/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。 +/// +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip)] +[JsonSerializable(typeof(SavedogRequest))] +[JsonSerializable(typeof(SavedogState))] +[JsonSerializable(typeof(LastGoodVersion))] +[JsonSerializable(typeof(StartupHealth.HealthRecord))] +[JsonSerializable(typeof(ModelIntegrityFile))] +[JsonSerializable(typeof(VerifyReport))] +[JsonSerializable(typeof(StatusReport))] +[JsonSerializable(typeof(VerifyModelReport))] +internal partial class SavedogJsonContext : JsonSerializerContext +{ + // 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项, + // 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。 +} + +/// verify --json 的输出。 +internal sealed class VerifyReport +{ + public string Trust { get; set; } = ""; + public string? KeyId { get; set; } + public string? Error { get; set; } + public List TrustedKeys { get; set; } = new(); +} + +internal sealed class TrustedKey +{ + public string KeyId { get; set; } = ""; + public string Fingerprint { get; set; } = ""; +} + +/// status --json 的输出。 +internal sealed class StatusReport +{ + public SavedogState? State { get; set; } + public LastGoodVersion? LastGood { get; set; } + public StartupHealth.HealthRecord? Health { get; set; } +} + +/// verify-model --json 的输出。 +internal sealed class VerifyModelReport +{ + public bool Ok { get; set; } + public bool Present { get; set; } + public string Message { get; set; } = ""; +} + +/// 把共享的 接到源生成上下文上。 +internal static class SavedogJson +{ + private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options)); + + public static void Initialize() + { + Json.TypeInfoProvider = type => Context.GetTypeInfo(type); + } +} diff --git a/GC.sln b/GC.sln index 9b1b382..b954738 100644 --- a/GC.sln +++ b/GC.sln @@ -39,6 +39,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\GC-DOWNLOAD.csproj", "{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -133,6 +135,18 @@ Global {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.Build.0 = Release|Any CPU {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.ActiveCfg = Release|Any CPU {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.Build.0 = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.ActiveCfg = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.Build.0 = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.ActiveCfg = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.Build.0 = Debug|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.Build.0 = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.ActiveCfg = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.Build.0 = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.ActiveCfg = Release|Any CPU + {B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -149,7 +163,7 @@ Global {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C} {6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} {AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B} - {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7} {6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} + {98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7} EndGlobalSection EndGlobal diff --git a/GC/src/App.axaml.cs b/GC/src/App.axaml.cs index 2b8a10c..bc5c7b8 100644 --- a/GC/src/App.axaml.cs +++ b/GC/src/App.axaml.cs @@ -35,6 +35,11 @@ public partial class App : Application var window = new MainWindow(); window.Show(); + // 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来, + // 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。 + StartupHealth.MarkHealthy(services.Paths.UpdateRoot, + LauncherRuntimeInfo.CurrentLauncherVersion); + // 首帧之后再构造 ViewModel:Post 而非依赖 Opened, // 因为 Opened 在某些情况下不触发(headless / 部分平台), // 会导致 DataContext 一直是 null、主页面白屏。 diff --git a/GC/src/Assets/i18n/en.json b/GC/src/Assets/i18n/en.json index 2bfb1b2..e8ae8d9 100644 --- a/GC/src/Assets/i18n/en.json +++ b/GC/src/Assets/i18n/en.json @@ -15,7 +15,7 @@ "home.installed": "Installed models", "home.count": "{0} models", "home.empty": "No models yet", - "home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.", + "home.emptyHint": "Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.", "home.emptyAction": "Get models", "home.open": "Open folder", "home.delete": "Delete", diff --git a/GC/src/Assets/i18n/zh-CN.json b/GC/src/Assets/i18n/zh-CN.json index 47461c6..0c3b1b3 100644 --- a/GC/src/Assets/i18n/zh-CN.json +++ b/GC/src/Assets/i18n/zh-CN.json @@ -15,7 +15,7 @@ "home.installed": "已安装模型", "home.count": "{0} 个模型", "home.empty": "模型库还是空的", - "home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。", + "home.emptyHint": "启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。", "home.emptyAction": "去下载模型", "home.open": "打开目录", "home.delete": "删除", diff --git a/GC/src/Models/AppSettings.cs b/GC/src/Models/AppSettings.cs index 76f5c22..3575bf3 100644 --- a/GC/src/Models/AppSettings.cs +++ b/GC/src/Models/AppSettings.cs @@ -46,6 +46,12 @@ public sealed class AppSettings /// 本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。 public string? UpdateLocalRoot { get; set; } + /// + /// 要求版本清单必须带**有效签名**。默认开启:关闭后只警告不拦截, + /// 等于放弃「清单被篡改」的防护,只建议在自建私有构建里临时关闭。 + /// + public bool RequireSignedManifest { get; set; } = true; + /// 已安装的模型版本:id -> version.json 里的版本。 public Dictionary InstalledModelVersions { get; set; } = new(); diff --git a/GC/src/Security/CanonicalJson.cs b/GC/src/Security/CanonicalJson.cs new file mode 100644 index 0000000..fe0cf2e --- /dev/null +++ b/GC/src/Security/CanonicalJson.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace GC.Services; + +/// +/// 规范化 JSON:签名与验签必须对完全相同的字节做运算, +/// 否则「同一份内容、不同缩进/键序」会得出不同签名。 +/// +/// 规则(写进 README,第三方可复现): +/// 1. 对象键按 Unicode 码点升序递归排序 +/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM +/// 3. 数字沿用源文本(不做浮点重排) +/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping) +/// 5. 签名时先移除根级 signature 字段 +/// +public static class CanonicalJson +{ + private static readonly JsonSerializerOptions Options = new() + { + WriteIndented = false, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + /// 把 JSON 文本规范化;解析失败返回 null。 + public static byte[]? Normalize(string text, bool dropSignatureField) + { + if (string.IsNullOrWhiteSpace(text)) return null; + try + { + var node = JsonNode.Parse(text); + if (node is not JsonObject obj) return null; + if (dropSignatureField) obj.Remove("signature"); + var sorted = SortNode(obj); + return Encoding.UTF8.GetBytes(sorted?.ToJsonString(Options) ?? "{}"); + } + catch (JsonException) + { + return null; + } + } + + private static JsonNode? SortNode(JsonNode? node) + { + switch (node) + { + case JsonObject obj: + var result = new JsonObject(); + foreach (var pair in obj.OrderBy(p => p.Key, StringComparer.Ordinal)) + result[pair.Key] = SortNode(pair.Value); + return result; + + case JsonArray array: + var list = new JsonArray(); + foreach (var item in array) list.Add(SortNode(item)); + return list; + + default: + return node?.DeepClone(); + } + } +} diff --git a/GC/src/Security/ContentHash.cs b/GC/src/Security/ContentHash.cs new file mode 100644 index 0000000..59e1d48 --- /dev/null +++ b/GC/src/Security/ContentHash.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace GC.Services; + +/// +/// 内容哈希(可复现的指纹算法)。 +/// +/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」: +/// +/// fileHash = SHA256(文件字节) +/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 +/// "<相对路径>\0<fileHash>\n" ) +/// +/// 相对路径统一用 / 分隔;跳过以 . 开头的文件、bin/、obj/、 +/// *.user;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。 +/// +public static class ContentHash +{ + public static string Sha256Hex(byte[] data) + => Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant(); + + public static string Sha256Hex(string text) + => Sha256Hex(Encoding.UTF8.GetBytes(text)); + + public static string Sha256File(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + } + + /// 目录内所有参与分发的文件 -> { 相对路径 : sha256 }。 + public static Dictionary MapFiles(string directory) + { + var map = new Dictionary(StringComparer.Ordinal); + if (!Directory.Exists(directory)) return map; + + foreach (var file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories)) + { + var rel = Path.GetRelativePath(directory, file).Replace('\\', '/'); + if (!Distributable(rel)) continue; + map[rel] = Sha256File(file); + } + return map; + } + + /// 按上述算法计算目录指纹。 + public static string DirectoryHash(string directory) + => DirectoryHash(MapFiles(directory)); + + public static string DirectoryHash(IReadOnlyDictionary files) + { + var builder = new StringBuilder(); + foreach (var pair in files.OrderBy(p => p.Key, StringComparer.Ordinal)) + builder.Append(pair.Key).Append('\0').Append(pair.Value).Append('\n'); + + return Sha256Hex(Encoding.UTF8.GetBytes(builder.ToString())); + } + + /// 目录指纹;目录不存在时返回空串(区别于空目录的哈希)。 + public static string DirectoryHashOrEmpty(string directory) + => Directory.Exists(directory) ? DirectoryHash(directory) : ""; + + public static bool Distributable(string relativePath) + { + var rel = relativePath.Replace('\\', '/'); + if (rel.StartsWith('.')) return false; + if (rel.Contains("/.")) return false; + if (rel.StartsWith("bin/", StringComparison.OrdinalIgnoreCase)) return false; + if (rel.StartsWith("obj/", StringComparison.OrdinalIgnoreCase)) return false; + if (rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase)) return false; + if (rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) return false; + if (rel.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false; + return true; + } +} diff --git a/GC/src/Security/ManifestLoader.cs b/GC/src/Security/ManifestLoader.cs new file mode 100644 index 0000000..975eed4 --- /dev/null +++ b/GC/src/Security/ManifestLoader.cs @@ -0,0 +1,44 @@ +using System; +using System.Text.Json; + +namespace GC.Services; + +/// +/// 把「远端拿到的清单文本」变成 ,同时带上验签结论。 +/// +/// 设计上把「验签」和「允不允许用」分开: +/// · 本方法只负责**如实报告**信任状态; +/// · 允不允许安装由 UpdateService / LauncherUpdater 按策略决定。 +/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。 +/// +public static class ManifestLoader +{ + public static RepoVersion? Parse(string? text, out ManifestVerification verification) + { + verification = ManifestSignature.Verify(text, requireSignature: true); + if (string.IsNullOrWhiteSpace(text)) return null; + + RepoVersion? version; + try + { + version = JsonSerializer.Deserialize(text!, Json.Options); + } + catch (Exception ex) + { + Console.Error.WriteLine($"版本清单解析失败: {ex.Message}"); + return null; + } + + if (version == null) return null; + + // 平台键回填:RepoPackage 自己要能说出「我属于哪个 RID」, + // 否则下载端无法推导 dist/<系统>-<架构> 这类兜底路径。 + foreach (var pair in version.Launcher.Packages) + if (pair.Value != null) pair.Value.Rid = pair.Key; + + version.SignatureTrust = verification.Trust.ToString(); + version.SignatureKeyId = verification.KeyId; + version.SignatureError = verification.Error; + return version; + } +} diff --git a/GC/src/Security/ManifestSignature.cs b/GC/src/Security/ManifestSignature.cs new file mode 100644 index 0000000..9ecdbb9 --- /dev/null +++ b/GC/src/Security/ManifestSignature.cs @@ -0,0 +1,172 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace GC.Services; + +/// 清单可信度。 +public enum ManifestTrust +{ + /// 签名有效,且密钥在受信任列表里。 + Verified, + /// 本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。 + Skipped, + /// 清单没有签名,但客户端要求签名。 + Unsigned, + /// 有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。 + Invalid +} + +public sealed record ManifestVerification(ManifestTrust Trust, string? KeyId, string? Error) +{ + public bool IsTrusted => Trust is ManifestTrust.Verified or ManifestTrust.Skipped; + public bool IsRejected => Trust is ManifestTrust.Unsigned or ManifestTrust.Invalid; + + public static ManifestVerification Ok(string keyId) => new(ManifestTrust.Verified, keyId, null); + public static ManifestVerification Skip() => new(ManifestTrust.Skipped, null, + "未配置受信任公钥,已跳过验签"); + public static ManifestVerification Bad(string error) => new(ManifestTrust.Invalid, null, error); +} + +/// +/// 版本清单签名(ECDSA P-256 / SHA-256)。 +/// +/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。 +/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥, +/// 才能把「篡改清单」这条路堵死。 +/// +/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带 +/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。 +/// +/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip +/// → 校验解压出的模型文件 → 加载 dll。 +/// +public static class ManifestSignature +{ + public const string Algorithm = "ECDSA-P256-SHA256"; + + private static readonly JsonSerializerOptions WriteOptions = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + // ------------------------------------------------------------------ 验签 + + /// + /// 校验清单文本的签名。 为 true 时, + /// 无签名视为失败;为 false 时无签名只返回 , + /// 由调用方决定是否放行(开发态用)。 + /// + public static ManifestVerification Verify(string? text, bool requireSignature) + { + if (SignatureKeyring.Keys.Count == 0) return ManifestVerification.Skip(); + if (string.IsNullOrWhiteSpace(text)) return ManifestVerification.Bad("清单内容为空"); + + JsonObject root; + try + { + root = JsonNode.Parse(text!) as JsonObject ?? throw new JsonException("根节点不是对象"); + } + catch (Exception ex) + { + return ManifestVerification.Bad("清单不是合法 JSON: " + ex.Message); + } + + if (root["signature"] is not JsonObject signature) + return requireSignature + ? new ManifestVerification(ManifestTrust.Unsigned, null, "清单缺少签名") + : new ManifestVerification(ManifestTrust.Unsigned, null, "清单未签名"); + + var keyId = signature["keyId"]?.GetValue() ?? ""; + var value = signature["value"]?.GetValue() ?? ""; + var alg = signature["alg"]?.GetValue() ?? Algorithm; + + if (!string.Equals(alg, Algorithm, StringComparison.OrdinalIgnoreCase)) + return new ManifestVerification(ManifestTrust.Invalid, keyId, $"不支持的签名算法: {alg}"); + if (value.Length == 0) + return new ManifestVerification(ManifestTrust.Invalid, keyId, "签名为空"); + + var key = SignatureKeyring.Find(keyId); + if (key == null) + return new ManifestVerification(ManifestTrust.Invalid, keyId, $"未知签名密钥: {keyId}"); + + var payload = CanonicalJson.Normalize(text!, dropSignatureField: true); + if (payload == null) + return new ManifestVerification(ManifestTrust.Invalid, keyId, "无法规范化清单"); + + try + { + var sig = Convert.FromBase64String(value); + using var ecdsa = ECDsa.Create(); + ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key.PublicKeyBase64), out _); + var ok = ecdsa.VerifyData(payload, sig, HashAlgorithmName.SHA256, + DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + return ok + ? ManifestVerification.Ok(key.KeyId) + : new ManifestVerification(ManifestTrust.Invalid, keyId, "签名与内容不符"); + } + catch (Exception ex) + { + return new ManifestVerification(ManifestTrust.Invalid, keyId, "验签异常: " + ex.Message); + } + } + + // ------------------------------------------------------------------ 签名 + + /// 用私钥给清单签名,返回写入了 signature 字段的新清单文本。 + public static string SignDocument(string text, ECDsa key, string keyId) + { + var payload = CanonicalJson.Normalize(text, dropSignatureField: true) + ?? throw new InvalidOperationException("清单不是合法 JSON,无法签名"); + + var signature = key.SignData(payload, HashAlgorithmName.SHA256, + DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + var contentHash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant(); + + var root = JsonNode.Parse(text) as JsonObject + ?? throw new InvalidOperationException("清单根节点不是对象"); + + root["signature"] = new JsonObject + { + ["alg"] = Algorithm, + ["keyId"] = keyId, + ["value"] = Convert.ToBase64String(signature), + ["contentSha256"] = contentHash, + ["signedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") + }; + + return root.ToJsonString(WriteOptions) + "\n"; + } + + /// 从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。 + public static ECDsa? TryLoadPrivateKey(string path) + { + try + { + if (!File.Exists(path)) return null; + var pem = File.ReadAllText(path); + if (pem.Contains("BEGIN", StringComparison.Ordinal) == false) return null; + var key = ECDsa.Create(); + key.ImportFromPem(pem); + return key; + } + catch + { + return null; + } + } + + /// 导出公钥(SPKI / Base64),用于写入客户端受信任列表。 + public static string ExportPublicKeyBase64(ECDsa key) + => Convert.ToBase64String(key.ExportSubjectPublicKeyInfo()); + + /// 公钥指纹,便于人工核对两边的公钥是否一致。 + public static string PublicKeyFingerprint(string publicKeyBase64) + => Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64))) + .ToLowerInvariant()[..16]; +} diff --git a/GC/src/Security/ModelIntegrity.cs b/GC/src/Security/ModelIntegrity.cs new file mode 100644 index 0000000..f8028a6 --- /dev/null +++ b/GC/src/Security/ModelIntegrity.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace GC.Services; + +/// 模型安装后落盘的完整性记录。 +public sealed class ModelIntegrityFile +{ + public int Schema { get; set; } = 1; + public string Id { get; set; } = ""; + public string Version { get; set; } = ""; + /// 模型清单文件的 sha256。 + public string ManifestSha256 { get; set; } = ""; + /// <id>.model 目录的目录指纹。 + public string FilesSha256 { get; set; } = ""; + /// 关键文件(dll / json)逐文件哈希,用于加载前快速校验。 + public Dictionary Files { get; set; } = new(); + public string InstalledAt { get; set; } = ""; + /// 来源(远端源名 / 本地目录),便于排查。 + public string Source { get; set; } = ""; +} + +public sealed record IntegrityResult(bool Ok, bool Present, string Message) +{ + public static readonly IntegrityResult Missing = + new(true, false, "没有完整性记录(本地/开发模型),跳过校验"); +} + +/// +/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。 +/// +/// 威胁模型:模型 dll 会被 AssemblyLoadContext 直接执行,等于任意代码。 +/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。 +/// 因此: +/// 1. version.json(已签名)里带 manifestSha256 / filesSha256; +/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装; +/// 3. 安装成功后写 <id>.integrity.json; +/// 4. 每次加载 dll 前抽查 dll / json 的哈希。 +/// +public static class ModelIntegrity +{ + public const string FileNameSuffix = ".integrity.json"; + + public static string IntegrityPath(string modelDirectory, string id) + => Path.Combine(modelDirectory, id + FileNameSuffix); + + public static ModelIntegrityFile? Read(string modelDirectory, string id) + => Json.Read(IntegrityPath(modelDirectory, id)); + + public static void Write(string modelDirectory, string id, ModelIntegrityFile data) + => Json.Write(IntegrityPath(modelDirectory, id), data); + + /// + /// 计算某个模型包(清单 + 数据目录)的哈希。 + /// 是包含 <id>.json 与 + /// <id>.model/ 的那一层。 + /// + public static (string ManifestSha256, string FilesSha256, Dictionary Files) + Compute(string packageDirectory, string id) + { + var manifestPath = Path.Combine(packageDirectory, id + ".json"); + var dataDir = Path.Combine(packageDirectory, id + ".model"); + + var manifestSha = File.Exists(manifestPath) ? ContentHash.Sha256File(manifestPath) : ""; + var files = ContentHash.MapFiles(dataDir); + var filesSha = ContentHash.DirectoryHash(files); + + var critical = new Dictionary(StringComparer.Ordinal); + foreach (var pair in files) + { + if (!IsCritical(pair.Key)) continue; + critical[id + ".model/" + pair.Key] = pair.Value; + } + if (manifestSha.Length > 0) critical[id + ".json"] = manifestSha; + + return (manifestSha, filesSha, critical); + } + + /// 加载前校验:只查会被执行 / 解析的文件,保证 OpenModel 不被明显拖慢。 + public static IntegrityResult VerifyForLoad(string packageDirectory, string id) + { + var record = Read(packageDirectory, id); + if (record == null) return IntegrityResult.Missing; + + if (!string.Equals(record.Id, id, StringComparison.Ordinal)) + return new IntegrityResult(false, true, $"完整性记录与模型 id 不符: {record.Id}"); + + foreach (var pair in record.Files) + { + var path = Path.Combine(packageDirectory, pair.Key.Replace('/', Path.DirectorySeparatorChar)); + if (!File.Exists(path)) + return new IntegrityResult(false, true, $"缺少文件: {pair.Key}"); + + var actual = ContentHash.Sha256File(path); + if (!string.Equals(actual, pair.Value, StringComparison.OrdinalIgnoreCase)) + return new IntegrityResult(false, true, $"文件已被修改: {pair.Key}"); + } + + return new IntegrityResult(true, true, "完整性校验通过"); + } + + private static bool IsCritical(string relativePath) + { + var rel = relativePath.Replace('\\', '/'); + return rel.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || + rel.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || + rel.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) || + rel.EndsWith(".so", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/GC/src/Security/SafeArchive.cs b/GC/src/Security/SafeArchive.cs new file mode 100644 index 0000000..0fe642e --- /dev/null +++ b/GC/src/Security/SafeArchive.cs @@ -0,0 +1,143 @@ +using System; +using System.IO; +using System.IO.Compression; + +namespace GC.Services; + +/// +/// 安全解压:更新包来自网络,必须当成不可信输入处理。 +/// +/// 拦截: +/// · zip slip(../、绝对路径、盘符、UNC) +/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件) +/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常) +/// 逐条校验通过后**自己写文件**,不使用 , +/// 避免框架在写入阶段才发现问题、留下半成品。 +/// +public static class SafeArchive +{ + /// 单个包最多条目数。 + public const int MaxEntries = 20000; + + /// 解压后总体积上限(2 GiB)。 + public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024; + + /// 单个条目解压上限(1 GiB)。 + public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024; + + /// 压缩比上限:超过视为 zip 炸弹。 + public const int MaxCompressionRatio = 200; + + public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes) + { + public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes; + } + + /// 只检查不解压:条目数、体积、路径、链接。发现问题抛异常。 + public static Inspection Inspect(string zipPath) + { + using var archive = ZipFile.OpenRead(zipPath); + long total = 0; + var count = 0; + + foreach (var entry in archive.Entries) + { + count++; + if (count > MaxEntries) + throw new InvalidOperationException($"压缩包条目过多(>{MaxEntries}),疑似恶意包"); + + ValidateName(entry.FullName); + AssertNotLink(entry); + + if (entry.Length > MaxSingleEntryBytes) + throw new InvalidOperationException($"条目过大: {entry.FullName}"); + + total += entry.Length; + if (total > MaxUncompressedBytes) + throw new InvalidOperationException("解压后体积超出上限,疑似 zip 炸弹"); + } + + var compressed = new FileInfo(zipPath).Length; + var inspection = new Inspection(count, total, compressed); + if (compressed > 0 && inspection.Ratio > MaxCompressionRatio && total > 64L * 1024 * 1024) + throw new InvalidOperationException($"压缩比异常({inspection.Ratio:0.#}:1),疑似 zip 炸弹"); + + return inspection; + } + + public static void ExtractToDirectory(string zipPath, string destination) + { + Inspect(zipPath); + + Directory.CreateDirectory(destination); + var destFull = Path.GetFullPath(destination) + .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + + using var archive = ZipFile.OpenRead(zipPath); + foreach (var entry in archive.Entries) + { + var name = entry.FullName.Replace('\\', '/'); + if (name.EndsWith("/", StringComparison.Ordinal)) + { + Directory.CreateDirectory(Path.GetFullPath(Path.Combine(destFull, name))); + continue; + } + + var target = Path.GetFullPath(Path.Combine(destFull, name)); + if (!target.StartsWith(destFull, StringComparison.Ordinal)) + throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}"); + + var dir = Path.GetDirectoryName(target); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + + using (var source = entry.Open()) + using (var output = new FileStream(target, FileMode.Create, FileAccess.Write, + FileShare.None, 81920, FileOptions.None)) + { + source.CopyTo(output); + } + + TryApplyUnixMode(entry, target); + } + } + + /// 校验条目名,拒绝一切能逃出目标目录的写法。 + public static void ValidateName(string fullName) + { + var name = fullName.Replace('\\', '/'); + if (name.Length == 0) throw new InvalidOperationException("压缩包含空文件名条目"); + if (name.StartsWith('/')) throw new InvalidOperationException($"压缩包含绝对路径: {fullName}"); + if (name.StartsWith("//")) throw new InvalidOperationException($"压缩包含 UNC 路径: {fullName}"); + if (name.Length >= 2 && name[1] == ':') + throw new InvalidOperationException($"压缩包含盘符路径: {fullName}"); + + foreach (var segment in name.Split('/')) + { + if (segment == "..") + throw new InvalidOperationException($"压缩包含父目录穿越: {fullName}"); + } + + if (name.Contains('\0')) + throw new InvalidOperationException($"压缩包含非法字符: {fullName}"); + } + + /// Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。 + private static void AssertNotLink(ZipArchiveEntry entry) + { + var mode = (entry.ExternalAttributes >> 16) & 0xF000; + if (mode == 0xA000) + throw new InvalidOperationException($"压缩包含符号链接条目: {entry.FullName}"); + } + + private static void TryApplyUnixMode(ZipArchiveEntry entry, string target) + { + if (OperatingSystem.IsWindows()) return; + try + { + var mode = (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF); + if (mode == 0) return; + File.SetUnixFileMode(target, mode); + } + catch { /* 权限位设置失败不影响文件内容 */ } + } +} diff --git a/GC/src/Security/SavedogProtocol.cs b/GC/src/Security/SavedogProtocol.cs new file mode 100644 index 0000000..97ec160 --- /dev/null +++ b/GC/src/Security/SavedogProtocol.cs @@ -0,0 +1,95 @@ +using System; + +namespace GC.Services; + +/// +/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 .GC/update/ 下,全部相对路径)。 +/// +/// 流程: +/// +/// launcher 下载并校验更新包 +/// -> 解压到 update/payload/ +/// -> 写 apply-request.json + 已验签的 version.json 副本 +/// -> 启动 GC-SAVEDOG apply --wait-pid <自己> +/// -> 自己退出 +/// +/// GC-SAVEDOG +/// -> 等父进程退出 +/// -> 重验签名 + 包 sha256 + 解压安全性 +/// -> 把 payload 移到安装目录(绝不覆盖已有版本) +/// -> 启动新版,等 update/health.json +/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版 +/// -> 写 state.json(applied / rolledback / failed) +/// +/// +public static class SavedogFiles +{ + public const string ApplyRequest = "apply-request.json"; + public const string State = "state.json"; + public const string Log = "savedog.log"; + public const string Health = StartupHealth.FileName; + public const string LastGood = "last-good.json"; + + /// SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。 + public static string ExecutableName => + OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG"; +} + +/// 启动器写入的更新申请。 +public sealed class SavedogRequest +{ + public int Schema { get; set; } = 1; + + /// 新版本号,如 1.0.8。 + public string Version { get; set; } = ""; + + public string Rid { get; set; } = ""; + + /// 文件名里的平台标签,如 mac-arm64。 + public string PlatformLabel { get; set; } = ""; + + /// payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。 + public string PackageName { get; set; } = ""; + + /// payload 目录(相对 update 目录)。 + public string PayloadDir { get; set; } = "payload"; + + /// 已验签清单的副本(相对 update 目录),用于二次验签。 + public string ManifestPath { get; set; } = "version.json"; + + /// 更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。 + public string PackageZip { get; set; } = "package.zip"; + + /// 更新包 sha256(来自已验签清单)。 + public string? PackageSha256 { get; set; } + + public long PackageSize { get; set; } + + /// 是否强制要求清单签名。 + public bool RequireSignature { get; set; } = true; + + /// 安装目录(相对 update 目录),由启动器按实际路径算出。 + public string InstallRelative { get; set; } = "../.."; + + public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); +} + +/// SAVEDOG 的执行结果,写入 state.json 供界面显示。 +public sealed class SavedogState +{ + public string Status { get; set; } = "unknown"; // applied | rolledback | failed | refused + public string Version { get; set; } = ""; + public string? PreviousVersion { get; set; } + public string PackageName { get; set; } = ""; + public string Message { get; set; } = ""; + public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); + public bool Verified { get; set; } +} + +/// 上次成功启动的版本信息,回滚时用。 +public sealed class LastGoodVersion +{ + public string Version { get; set; } = ""; + public string PackageName { get; set; } = ""; + public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); +} diff --git a/GC/src/Security/SignatureKeyring.cs b/GC/src/Security/SignatureKeyring.cs new file mode 100644 index 0000000..6e68726 --- /dev/null +++ b/GC/src/Security/SignatureKeyring.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; + +namespace GC.Services; + +/// +/// 受信任的签名公钥。 +/// +/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库** +/// (放在仓库根 .signing/,已在 .gitignore 中)。 +/// +/// 轮换密钥:用 GC-SAVEDOG keygen 生成新的一对,把新公钥追加到这里, +/// 旧公钥保留一个版本周期,避免老客户端直接失效。 +/// 也可用环境变量临时注入(测试 / 私有构建): +/// GC_TRUSTED_KEYS="id1:base64;id2:base64" +/// +public static class SignatureKeyring +{ + public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null); + + private static readonly List KeysInternal = new() + { + // 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed + new KeyEntry( + "gc-2026-11", + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" + + "PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==", + "GC 主发布密钥") + }; + + static SignatureKeyring() => LoadFromEnvironment(); + + public static IReadOnlyList Keys => KeysInternal; + + /// 是否配置了受信任密钥(配置了就必须验签)。 + public static bool Enforced => KeysInternal.Count > 0; + + public static KeyEntry? Find(string? keyId) + { + if (KeysInternal.Count == 0) return null; + foreach (var key in KeysInternal) + if (string.Equals(key.KeyId, keyId, StringComparison.Ordinal)) + return key; + // 未写 keyId 且只有一个密钥时容忍(早期构建产物) + if (string.IsNullOrWhiteSpace(keyId) && KeysInternal.Count == 1) return KeysInternal[0]; + return null; + } + + /// 测试 / 私有分发用:追加一个受信任公钥。 + public static void Add(KeyEntry key) + { + if (string.IsNullOrWhiteSpace(key.KeyId) || string.IsNullOrWhiteSpace(key.PublicKeyBase64)) return; + if (Find(key.KeyId) != null) return; + KeysInternal.Add(key); + } + + /// 测试用:替换整个密钥环。 + public static void ReplaceAll(IEnumerable keys) + { + KeysInternal.Clear(); + foreach (var key in keys) KeysInternal.Add(key); + } + + private static void LoadFromEnvironment() + { + var raw = Environment.GetEnvironmentVariable("GC_TRUSTED_KEYS"); + if (string.IsNullOrWhiteSpace(raw)) return; + foreach (var part in raw!.Split(';', StringSplitOptions.RemoveEmptyEntries)) + { + var idx = part.IndexOf(':'); + if (idx <= 0 || idx >= part.Length - 1) continue; + var keyId = part[..idx].Trim(); + var value = part[(idx + 1)..].Trim(); + if (keyId.Length == 0 || value.Length == 0) continue; + if (Find(keyId) != null) continue; + KeysInternal.Add(new KeyEntry(keyId, value, "来自 GC_TRUSTED_KEYS")); + } + } +} diff --git a/GC/src/Security/StartupHealth.cs b/GC/src/Security/StartupHealth.cs new file mode 100644 index 0000000..7f51c0f --- /dev/null +++ b/GC/src/Security/StartupHealth.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; + +namespace GC.Services; + +/// +/// 启动成功的健康标记。 +/// +/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现, +/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。 +/// +public static class StartupHealth +{ + public const string FileName = "health.json"; + + public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName); + + /// 主窗口显示后调用:证明本次启动真的跑起来了。 + public static void MarkHealthy(string updateRoot, string version) + { + try + { + Directory.CreateDirectory(updateRoot); + Json.Write(PathFor(updateRoot), new HealthRecord + { + Version = version, + Pid = Environment.ProcessId, + At = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), + Ok = true + }); + } + catch (Exception ex) + { + Console.Error.WriteLine($"写入健康标记失败: {ex.Message}"); + } + } + + public static HealthRecord? Read(string updateRoot) + => Json.Read(PathFor(updateRoot)); + + public static void Clear(string updateRoot) + { + try + { + var path = PathFor(updateRoot); + if (File.Exists(path)) File.Delete(path); + } + catch { } + } + + public sealed class HealthRecord + { + public string Version { get; set; } = ""; + public int Pid { get; set; } + public string At { get; set; } = ""; + public bool Ok { get; set; } + } +} diff --git a/GC/src/Services/AppPaths.cs b/GC/src/Services/AppPaths.cs index e69aca2..132d9c6 100644 --- a/GC/src/Services/AppPaths.cs +++ b/GC/src/Services/AppPaths.cs @@ -39,7 +39,11 @@ public sealed class AppPaths public string CacheRoot => Path.Combine(HomeRoot, "cache"); public string UpdateRoot => Path.Combine(HomeRoot, "update"); - public string SettingsFile => Path.Combine(HomeRoot, "settings.json"); + + /// 用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。 + public string ConfigRoot => Path.Combine(HomeRoot, "config"); + + public string SettingsFile => Path.Combine(ConfigRoot, "settings.json"); public bool IsDevelopment { get; private init; } public bool IsPortableModelRoot { get; private init; } @@ -247,10 +251,13 @@ public sealed class AppPaths public void EnsureCreated() { Directory.CreateDirectory(HomeRoot); + Directory.CreateDirectory(ConfigRoot); Directory.CreateDirectory(CacheRoot); Directory.CreateDirectory(ModelRoot); Directory.CreateDirectory(UpdateRoot); + MigrateLegacySettings(); + // 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。 // 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。 if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS"))) @@ -264,6 +271,27 @@ public sealed class AppPaths public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult(); + /// + /// 老版本把设置放在 .GC/settings.json。现在设置归到 .GC/config/, + /// 与 cache/ 分开(清缓存不会连带清掉语言、内存预算、离线源等配置)。 + /// 迁移只做一次:新位置不存在时才搬旧的。 + /// + private void MigrateLegacySettings() + { + try + { + var legacy = Path.Combine(HomeRoot, "settings.json"); + if (!File.Exists(legacy) || File.Exists(SettingsFile)) return; + Directory.CreateDirectory(ConfigRoot); + File.Move(legacy, SettingsFile); + Console.WriteLine("[paths] 设置已迁移到 .GC/config/settings.json"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"迁移旧设置失败: {ex.Message}"); + } + } + private static void SyncDevelopmentModels(string modelRoot, string source) { try diff --git a/GC/src/Services/Json.cs b/GC/src/Services/Json.cs index 2dde35c..e69b720 100644 --- a/GC/src/Services/Json.cs +++ b/GC/src/Services/Json.cs @@ -1,6 +1,8 @@ +using System; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; namespace GC.Services; @@ -17,10 +19,21 @@ public static class Json ReadCommentHandling = JsonCommentHandling.Skip }; + /// + /// 源生成类型信息的提供者(可选)。 + /// + /// 启动器本身不做裁剪,走默认的反射序列化即可;GC-SAVEDOG 会被 PublishTrimmed + /// 裁掉无参构造,反射序列化在运行时直接抛 NotSupportedException。 + /// 因此守护进程在启动时把本钩子指向 JsonSerializerContext, + /// 让所有读写都走编译期生成的 。 + /// 这样「安全模块只有一份实现」的前提没有被破坏,只是换了元数据来源。 + /// + public static Func? TypeInfoProvider { get; set; } + public static T? Read(string path) { if (!System.IO.File.Exists(path)) return default; - return JsonSerializer.Deserialize(System.IO.File.ReadAllText(path), Options); + return Deserialize(System.IO.File.ReadAllText(path)); } public static void Write(string path, T value) @@ -28,7 +41,24 @@ public static class Json var dir = System.IO.Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir); var tmp = path + ".tmp"; - System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options)); + System.IO.File.WriteAllText(tmp, Serialize(value)); System.IO.File.Move(tmp, path, true); } + + public static T? Deserialize(string text) + { + if (string.IsNullOrWhiteSpace(text)) return default; + var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo; + return info != null + ? JsonSerializer.Deserialize(text, info) + : JsonSerializer.Deserialize(text, Options); + } + + public static string Serialize(T value) + { + var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo; + return info != null + ? JsonSerializer.Serialize(value, info) + : JsonSerializer.Serialize(value, Options); + } } diff --git a/GC/src/Services/ModelHost.cs b/GC/src/Services/ModelHost.cs index 4404cb6..026a7a0 100644 --- a/GC/src/Services/ModelHost.cs +++ b/GC/src/Services/ModelHost.cs @@ -71,6 +71,40 @@ public sealed class ModelHost private Session CreateSession(ModelPackage package, Action requestClose, Action? progress) { + // ---- 契约协商 ------------------------------------------------------- + // 先做廉价检查:不满足就直接拒绝,避免加载了才发现不兼容。 + var declaredApi = package.Manifest.ApiVersion; + if (declaredApi < 1) + throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}"); + + if (declaredApi > SupportedApiVersion) + throw new InvalidOperationException( + $"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" + + "请先更新启动器,或让模型作者发布兼容版本。"); + + var minApp = package.Manifest.MinAppVersion; + if (!string.IsNullOrWhiteSpace(minApp) && + CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0) + throw new InvalidOperationException( + $"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}"); + + // ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ---------------- + var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id); + if (!integrity.Ok) + { + var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" + + "请删除该模型目录让启动器重新下载。"; + if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1") + Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)"); + else + throw new InvalidOperationException(message); + } + else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1") + { + throw new InvalidOperationException( + $"模型缺少完整性记录({package.Id}),严格模式下拒绝加载"); + } + var assemblyPath = package.AssemblyPath; if (!File.Exists(assemblyPath)) throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath); @@ -89,7 +123,8 @@ public sealed class ModelHost if (factory.ApiVersion != SupportedApiVersion) throw new InvalidOperationException( - $"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致"); + $"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" + + "请更新到匹配的版本"); var runtime = factory.Create(); var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress); @@ -118,6 +153,34 @@ public sealed class ModelHost return null; } + /// 比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。 + private static int CompareVersions(string left, string right) + { + static int[] Parts(string value) + { + var text = value.Trim().TrimStart('v', 'V'); + var pieces = text.Split('.'); + var numbers = new int[Math.Max(4, pieces.Length)]; + for (var i = 0; i < pieces.Length; i++) + { + var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit)); + if (digits.Length > 6) digits = digits[..6]; + numbers[i] = int.TryParse(digits, out var n) ? n : 0; + } + return numbers; + } + + var a = Parts(left); + var b = Parts(right); + for (var i = 0; i < Math.Max(a.Length, b.Length); i++) + { + var x = i < a.Length ? a[i] : 0; + var y = i < b.Length ? b[i] : 0; + if (x != y) return x < y ? -1 : 1; + } + return 0; + } + private sealed class Session : IDisposable { private readonly ModelLoadContext _context; diff --git a/GC/src/Services/UpdateModels.cs b/GC/src/Services/UpdateModels.cs index 61bdd12..3503f69 100644 --- a/GC/src/Services/UpdateModels.cs +++ b/GC/src/Services/UpdateModels.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; @@ -15,6 +16,20 @@ public sealed class RepoVersion public string ModelDir { get; set; } = "model"; public RepoLauncher Launcher { get; set; } = new(); public List Models { get; set; } = new(); + + // ---- 验签结论(解析时填入,不参与序列化) ---------------------------- + + /// Verified / Skipped / Unsigned / Invalid。 + [JsonIgnore] public string SignatureTrust { get; set; } = ""; + + [JsonIgnore] public string? SignatureKeyId { get; set; } + + [JsonIgnore] public string? SignatureError { get; set; } + + /// 清单是否可用:签名有效,或本机没有配置公钥(兼容期)。 + [JsonIgnore] + public bool IsTrusted => + SignatureTrust is nameof(ManifestTrust.Verified) or nameof(ManifestTrust.Skipped); } public sealed class RepoLauncher @@ -34,6 +49,19 @@ public sealed class RepoPackage public long Size { get; set; } /// Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。 public string? AssetName { get; set; } + + /// + /// 仓库里的平台产物目录,如 dist/mac-arm64。 + /// 不发 Release、只把编译产物提交进仓库时,更新包就在这里找。 + /// 清单没写时由 推导。 + /// + public string? Dir { get; set; } + + /// 包文件名,如 GC-1.0.7-mac-arm64.zip;清单没写时按版本与平台标签拼。 + public string? Name { get; set; } + + /// 所属平台键(win-x64 / win-arm64 / osx-arm64 …),解析清单时按字典键填入。 + [JsonIgnore] public string Rid { get; set; } = ""; } public sealed class RepoModel @@ -42,6 +70,20 @@ public sealed class RepoModel public string Version { get; set; } = ""; /// 模型在仓库里的目录,如 model/earth-rotation。 public string Dir { get; set; } = ""; + + // ---- 完整性(由 VersionStamp 计算,签名覆盖这几个字段) ---------------- + + /// 内容指纹(构建溯源,不参与版本比较)。 + public string? Build { get; set; } + + /// 模型清单 <id>.json 的 sha256。 + public string? ManifestSha256 { get; set; } + + /// <id>.model 目录的目录指纹(算法见 ContentHash)。 + public string? FilesSha256 { get; set; } + + /// 参与分发的文件数。 + public int Files { get; set; } } /// 远端目录树里的一个条目。 @@ -71,6 +113,12 @@ public interface IModelRemote Task> ListTreeAsync(string rootPath, CancellationToken ct); Task DownloadAsync(RepoEntry entry, CancellationToken ct); Task DownloadPackageAsync(RepoPackage package, CancellationToken ct); + + /// + /// 最近一次读到的清单**原始文本**(含 signature 字段),供 SAVEDOG 二次验签。 + /// 默认返回 null,表示该源不支持(调用方会退化为单次验签)。 + /// + Task GetRawVersionTextAsync(CancellationToken ct) => Task.FromResult(null); } public sealed class UpdateProgress diff --git a/GC/src/ViewModels/MainViewModel.cs b/GC/src/ViewModels/MainViewModel.cs index 39f1219..fcf598c 100644 --- a/GC/src/ViewModels/MainViewModel.cs +++ b/GC/src/ViewModels/MainViewModel.cs @@ -181,6 +181,15 @@ public partial class MainViewModel : ObservableObject UpdateDetail = result.Error ?? ""; LauncherNotice = result.LauncherMessage ?? ""; + // 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。 + // 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。 + if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0) + { + UpdateStatus = "暂时连不上模型源,模型库为空"; + UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开"; + return; + } + // 模型下载完成后本次启动就刷新列表,立刻可用 if (result.UpdatedModels > 0) Home.Refresh(); diff --git a/GC/src/test/dotnet/GC.Tests/Program.cs b/GC/src/test/dotnet/GC.Tests/Program.cs index 19ee19c..e49d0d5 100644 --- a/GC/src/test/dotnet/GC.Tests/Program.cs +++ b/GC/src/test/dotnet/GC.Tests/Program.cs @@ -2,9 +2,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using System.Threading.Tasks; using System.IO; using System.IO.Compression; using System.Linq; +using System.Security.Cryptography; +using System.Text.Json; using GC.Models; using Avalonia; using Avalonia.Controls; @@ -81,7 +84,6 @@ internal static class Program var fixtureVersion = Json.Read(versionFile)!; fixtureVersion.Models.RemoveAll(model => model.Id is not "earth-rotation" and not "earth-revolution"); - Json.Write(Path.Combine(remote, "version.json"), fixtureVersion); foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model"))) { var id = Path.GetFileName(dir); @@ -95,6 +97,28 @@ internal static class Program CopyTree(data, Path.Combine(dest, id + ".model")); } + // 按远端实际内容重算完整性哈希(与 VersionStamp 同一算法),然后签名。 + // 客户端会复算这两项,不一致就拒绝安装 —— 这一步必须与构建端一致。 + foreach (var m in fixtureVersion.Models) + { + var computed = ModelIntegrity.Compute(Path.Combine(remote, "model", m.Id), m.Id); + m.ManifestSha256 = computed.ManifestSha256; + m.FilesSha256 = computed.FilesSha256; + m.Files = computed.Files.Count; + } + + var signer = ManifestSignature.TryLoadPrivateKey( + Path.Combine(repoRoot, ".signing", "gc-signing.pem")); + if (signer == null) + { + Console.WriteLine("FAIL: 缺少签名私钥 .signing/gc-signing.pem,无法构造可信清单"); + return 1; + } + + var remoteManifest = Path.Combine(remote, "version.json"); + WriteSigned(remoteManifest, fixtureVersion, signer); + Console.WriteLine($"远端清单已签名({ManifestSignature.Algorithm})"); + // EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局 Environment.SetEnvironmentVariable("EMS_HOME", tmp); Environment.SetEnvironmentVariable("EMS_DATA", home); @@ -119,7 +143,7 @@ internal static class Program Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model"); Check(paths.CacheRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "模型与启动器下载暂存位于 .GC/cache"); Check(paths.UpdateRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "启动器更新位于 .GC/update"); - Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建"); + Check(File.Exists(paths.SettingsFile), ".GC/config/settings.json 已创建"); // 1) 首次启动:模型全部下载并立即落地 var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult(); @@ -140,7 +164,7 @@ internal static class Program Check(r2.UpdatedModels == 0, "版本未变时不重复下载"); // 3) 远端模型改版:只更新这一个,并且本次启动立即生效 - var rv = Json.Read(Path.Combine(remote, "version.json"))!; + var rv = Json.Read(remoteManifest)!; Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version), "version.json 里模型版本由构建自动生成"); var changed = rv.Models[0]; @@ -148,12 +172,21 @@ internal static class Program var stampName = "_version-stamp.txt"; File.WriteAllText(Path.Combine(remote, "model", changed.Id, changed.Id + ".model", stampName), "new content"); - Json.Write(Path.Combine(remote, "version.json"), rv); + + // 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝 + var changedHash = ModelIntegrity.Compute(Path.Combine(remote, "model", changed.Id), changed.Id); + changed.ManifestSha256 = changedHash.ManifestSha256; + changed.FilesSha256 = changedHash.FilesSha256; + changed.Files = changedHash.Files.Count; + WriteSigned(remoteManifest, rv, signer); + var r3 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult(); Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}"); Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型"); Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)), "新版本本次启动立即生效"); + Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")), + "安装后写入完整性记录"); // 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列) var rid = LauncherRuntimeInfo.CurrentRid; @@ -165,8 +198,13 @@ internal static class Program var zip = Path.Combine(tmp, "GC-" + rid + ".zip"); ZipFile.CreateFromDirectory(stage, zip); rv.Launcher.Version = "9.9.9"; - rv.Launcher.Packages[rid] = new RepoPackage { Url = zip }; - Json.Write(Path.Combine(remote, "version.json"), rv); + rv.Launcher.Packages[rid] = new RepoPackage + { + Url = zip, + Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(), + Size = new FileInfo(zip).Length + }; + WriteSigned(remoteManifest, rv, signer); // 造一个旧版在当前目录 var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe"; @@ -200,7 +238,60 @@ internal static class Program Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除"); } - // 6) 断网兜底:保留本地模型,不清空 + // 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。 + // 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。 + var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel); + Directory.CreateDirectory(distDir); + var distName = "GC-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip"; + var distZip = Path.Combine(distDir, distName); + File.Copy(zip, distZip, true); + + string Sha(string file) => + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))).ToLowerInvariant(); + + rv.Launcher.Version = "9.9.10"; + rv.Launcher.Packages[rid] = new RepoPackage + { + Dir = "dist/" + LauncherUpdater.PlatformLabel, + Name = distName, + Sha256 = Sha(distZip), + Size = new FileInfo(distZip).Length + }; + WriteSigned(remoteManifest, rv, signer); + + var dlDist = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null)) + .GetAwaiter().GetResult(); + Console.WriteLine($"dist 目录更新: {dlDist.Message}"); + Check(dlDist.State == UpdateRunState.Ready, "仓库 dist/<系统>-<架构>/ 里的产物能找到并下载"); + // 包名来自 zip 内容(这里仍是 9.9.9 的文件),所以要断言清单版本 + Check(dlDist.Version == "9.9.10", "下载的确实是 dist 目录里声明的那个版本"); + + // 5c) 往 dist/ 里塞一个哈希不匹配的包:必须拒绝(sha256 来自已签名清单) + File.WriteAllText(distZip, "evil payload"); + var dlEvil = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null)) + .GetAwaiter().GetResult(); + Check(dlEvil.State == UpdateRunState.Failed, "dist 目录里哈希不符的包被拒绝"); + + // 还原到 9.9.9,后面的篡改 / 断网用例继续用这份清单 + rv.Launcher.Version = "9.9.9"; + rv.Launcher.Packages[rid] = new RepoPackage + { + Url = zip, + Sha256 = Sha(zip), + Size = new FileInfo(zip).Length + }; + WriteSigned(remoteManifest, rv, signer); + + // 6) 篡改检测:改一个字节但不重新签名 -> 必须判为不可信 + var tampered = File.ReadAllText(remoteManifest).Replace("\"9.9.9\"", "\"9.9.8\""); + var tamperResult = ManifestSignature.Verify(tampered, requireSignature: true); + Check(tamperResult.Trust == ManifestTrust.Invalid, "被篡改的清单验签失败"); + File.WriteAllText(remoteManifest, tampered); + var r6 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult(); + Check(r6.Outcome == UpdateOutcome.Unavailable, "清单被篡改时拒绝更新"); + WriteSigned(remoteManifest, rv, signer); + + // 7) 断网兜底:保留本地模型,不清空 var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope")); var beforeCount = settings.Current.InstalledModelVersions.Count; var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult(); @@ -216,6 +307,13 @@ internal static class Program return failures == 0 ? 0 : 1; } + /// 序列化清单并用私钥签名(测试里模拟一次正式发布)。 + private static void WriteSigned(string path, RepoVersion version, ECDsa key) + { + var text = JsonSerializer.Serialize(version, Json.Options) + "\n"; + File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-11")); + } + private static void CopyTree(string src, string dst) { Directory.CreateDirectory(dst); diff --git a/README.md b/README.md index ff4f5e2..ed4882f 100644 --- a/README.md +++ b/README.md @@ -3,121 +3,214 @@ 天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。 > **分层约定(重要)** -> - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。 +> - `GC/` = 启动器:扫描、下载、开窗口、显示加载进度。**不渲染、不含任何模型内容、发布包不内置模型**。 > - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。 > - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。 -> - 想加新内容 = 在 `model//` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。 +> - 想加新内容 = 在 `model//` 里放模型并推送仓库,启动器一行都不用改,客户端启动自动更新。 +> - `GC-SAVEDOG/` = 更新守护进程:验签、原子替换、启动后健康检查、失败回滚。 - UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台 - 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载 -- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译 +- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵) - 更新仓库:,模型目录 +## 快速开始 + +```bash +# 依赖:.NET 8 SDK(macOS 另需 Xcode Command Line Tools,用于 .icns / ditto) +dotnet --version # 8.0.x +./build.sh build # 三平台完整发布 -> dist/ +./build.sh run # 开发态直接运行(读仓库 model/,跳过在线替换) +./build.sh check # 编译 + 自检 + 离屏渲染 + 产物检查 +``` + +Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run / test / update-test / pack-models / clean / doctor`)。 +`build.sh test` 的离屏渲染需要图形栈:Linux CI 上用 `xvfb-run ./build.sh test`。 + ## 运行目录(发布包里就长这样) -Windows 用 `.\build.ps1`(参数相同);PowerShell 实现位于 `buildps1/`,不依赖 Git Bash 或 WSL。 + ``` <安装目录>/ GC.exe | GC.app/ + GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内) .GC/ - settings.json 设置 + 已安装版本记录 - model/ 启动时下载的模型 - cache/ 下载暂存 / 原子替换 - update/ 待下次启动应用的启动器更新 + config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置) + model/ 启动时下载的模型 + cache/ 下载暂存 / 原子替换 + update/ 待应用的启动器更新(apply-request.json + package.zip) ``` **发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示; -安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。 +安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载; +`.GC/config/settings.json` 删掉等于恢复出厂设置。 ## 自动更新 | 检查项 | 不是最新版时 | 生效时机 | | --- | --- | --- | -| 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/` | **下载后立即应用**(本次启动首页就刷新) | -| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) | +| 模型 | 按文件清单下载到 `cache/`,校验哈希后原子替换 `.GC/model/` | **下载后立即应用**(本次启动首页就刷新) | +| 启动器 | 下载对应平台 zip 到 `.GC/update/`,交给 `GC-SAVEDOG` | **下次启动时应用**(重启后自动替换) | -- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`: +启动器更新的完整流程: + +``` +启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出 + GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage + -> 移入安装目录(绝不覆盖已有版本) + -> 启动新版,等 .GC/update/health.json + -> 收到:删同平台旧版本,写 last-good.json + -> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback +``` + +也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。 + +- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`: `https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址) -- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**, - 所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。 -- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。 -- 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。 -- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。 +- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因 +- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等 - 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填 - `updateLocalRoot` 指向它,即可完全离线更新。 -- 发新版:运行 `./build.sh build`,把生成的 `dist/GC-<版本>-*.zip` 上传到 Release / 仓库 `dist/`, - 把直链填进 `version.json` 对应平台的 `url`(构建会生成 zip 并自动写入 `sha256` / `size`)。 - 更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。 + `updateLocalRoot` 指向它,即可完全离线更新(同样会验签) + +## 安全模型 + +威胁模型很直接:**模型 dll 会被 `AssemblyLoadContext` 直接执行**,启动器更新包会替换可执行文件。 +只要仓库被入侵,攻击者就能让所有客户端跑他的代码。因此信任链是: + +``` +内置公钥(源码) + └─ 验证 version.json 的 ECDSA P-256 签名 + ├─ 得到启动器包 sha256 → 校验下载到的 zip + │ └─ GC-SAVEDOG 再次验签 + 复算 sha256 + 检查 zip 结构 → 原子替换 + └─ 得到每个模型的 manifestSha256 / filesSha256 + └─ 下载后复算,比对通过才安装 + └─ 加载 dll 前抽查 dll / json 哈希(.integrity.json) +``` + +要点: + +| 机制 | 防的是什么 | 代码位置 | +| --- | --- | --- | +| 清单签名(ECDSA P-256 / SHA-256) | 仓库被改、清单被替换 | `GC/src/Security/ManifestSignature.cs` | +| 规范化 JSON(键排序、去 signature) | 「同内容不同字节」导致签名不可复现 | `GC/src/Security/CanonicalJson.cs` | +| 包 sha256(取自已签名清单) | 下载被替换 / 传输损坏 | `GC/src/Security/ContentHash.cs` | +| 模型 manifestSha256 / filesSha256 | 下载后、安装前被掉包 | `GC/src/Security/ModelIntegrity.cs` | +| 加载前抽查 dll 哈希 | 本地模型文件被替换 | `GC/src/Services/ModelHost.cs` | +| `SafeArchive`(条目数/体积/压缩比/符号链接/穿越) | zip 炸弹、zip slip、链接攻击 | `GC/src/Security/SafeArchive.cs` | +| `GC-SAVEDOG` 独立进程 | 覆盖失败、断电、新版本起不来 | `GC-SAVEDOG/Applier.cs` | +| 健康标记 + 回滚 | 新版启动即崩 | `GC/src/Security/StartupHealth.cs` | + +默认策略:**清单没签名或签名不符一律拒绝更新**。 +自建私有构建可临时放开:`settings.json` 里 `requireSignedManifest: false`, +或环境变量 `GC_ALLOW_UNSIGNED_MANIFEST=1`(只建议调试用)。 + +### 签名密钥 + +- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份) +- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed` +- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen` +- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单 +- 部署前核对两边公钥一致: + `dotnet run --project GC-SAVEDOG -- verify --manifest version.json` + +### zip 解压加固 + +更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接; +条目数 ≤ 20000、解压后 ≤ 2 GiB、压缩比异常(>200:1 且体积较大)直接判为 zip 炸弹。 + +## 版本与指纹 + +- **启动器版本**:`Directory.Build.props` 的 ``;`./build.sh build -version=1.0.8` 可覆盖, + 只影响启动器(程序集版本、关于页、`version.json` 的 `launcher.version`)。 +- **模型版本**:模型清单里**作者手写**的 `version`(如 `1.6`),`./build.sh stamp` 不会改它。 + 客户端按字符串比较是否变化,所以改模型内容后必须手动升版本号,否则用户不会更新。 +- **`build` 字段**:模型内容的构建指纹,只用于溯源;`updatedAt` / `build` 都不参与指纹计算, + 保证「同一份内容重复构建得到同一个值」。 +- **内容哈希算法**(构建端与客户端必须一致): + +``` +fileHash = SHA256(文件字节) +dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0\n" ) +``` + + 相对路径统一 `/` 分隔,跳过 `.` 开头的文件、`bin/`、`obj/`、`*.user`; + 不含时间戳、权限位、文件顺序。实现见 `GC/src/Security/ContentHash.cs`,构建端由 + `VersionStamp` 直接链接同一份源码,不会出现两套算法。 ## 目录结构 ``` Repository/ ├── GC.sln -├── Directory.Build.props # 公共构建属性 -├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效) -├── build.sh / build.ps1 # 构建脚本 -├── buildsh/ # POSIX shell 构建实现 -├── buildps1/ # 原生 PowerShell 构建实现 -├── GC/ # 启动器主要代码 +├── Directory.Build.props # 公共构建属性(版本号在这里) +├── version.json # ★ 自动生成并签名的版本清单(推送到仓库后才生效) +├── build.sh / build.ps1 # 构建脚本(实际实现在 buildsh/ 与 buildps1/) +├── GC/ # 启动器 │ └── src/ │ ├── GC.Core.csproj -│ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新 -│ ├── ViewModels/ Views/ # 主页、下载、设置和启动更新状态 -│ ├── Assets/i18n/ # 启动器界面语言包 +│ ├── Security/ # ★ 验签、哈希、安全解压、完整性、健康标记 +│ ├── Models/ Services/ +│ ├── ViewModels/ Views/ +│ ├── Assets/i18n/ # 界面语言包 │ └── test/dotnet/GC.Tests/ # 离屏校验 + --update-test 离线更新链路验证 ├── GC-BOOT/ # 轻量启动入口 -│ ├── GC-BOOT.csproj -│ ├── Program.cs -│ └── app.manifest -├── GC-DOWNLOAD/ # 模型、源仓库与启动器下载更新实现 -│ └── GC-DOWNLOAD.csproj -├── GC-DRAW/PlayerWindow.cs # 通用模型窗口宿主;实际绘制由模型提供 +├── GC-DOWNLOAD/ # 源仓库 / 模型 / 启动器下载更新 +├── GC-DRAW/PlayerWindow.cs # 模型窗口宿主;绘制由模型提供 +├── GC-SAVEDOG/ # ★ 更新守护进程(apply / verify / keygen / sign / status) ├── model/ # ★ 模型的一切 -│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取) +│ ├── version.json # 与根 version.json 完全相同(同一份签名) │ ├── _sdk/GC.ModelSdk/ -│ ├── _engine/ -│ │ ├── src/ # 模型专用引擎与渲染,留在 model 内 -│ │ ├── PreviewGen/ # 用模型渲染器生成封面 -│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json -│ ├── earth-rotation/ -│ │ ├── earth-rotation.json -│ │ ├── src/ # 本模型源码 -│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n +│ ├── _engine/{src,PreviewGen,VersionStamp}/ +│ ├── earth-rotation/{earth-rotation.json,src/,earth-rotation.model/} │ └── earth-revolution/ -└── dist/ # 发布产物(只有启动器 + .GC 骨架) +├── dist/ # 发布产物(.gitignore,只通过 Release 分发) +└── .signing/ # 签名私钥(.gitignore,绝不入库) ``` 模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。 +`dist/` 不进仓库:二进制放 Git 会让 clone 变慢,也会让「仓库被改」的爆炸半径变大。 +发布有两种方式,`version.json` 里两条路都写清楚了: + +| 方式 | 清单字段 | 说明 | +| --- | --- | --- | +| Release 附件(推荐) | `url` | `.../releases/download/v<版本>/GC-<版本>-<系统>-<架构>.zip` | +| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip` | + +下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试, +**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护), +所以「多发一个地方」不会放宽校验,只是让「只提交产物、不发 Release」也能更新。 +清单缺 `sha256` 的平台会被直接跳过,不再退化成「只校验非空」。 + ## 构建与运行 ```bash -./build.sh build # 完整三平台发布:编译启动器、准备运行目录并生成更新包 ZIP -./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查;通常在 build 后运行 -./build.sh models # 编译模型 dll、生成封面并更新版本清单 -./build.sh stamp # 只重新生成根目录与 model/ 下的 version.json -./build.sh run # 以 Debug 配置运行启动器 -./build.sh test # 运行离屏校验并将截图写入 build/screenshots/ -./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序) -./build.sh pack-models # 编译模型并打包到 dist/models-<版本>.zip -./build.sh pack-launcher # 将已有平台发布目录打成启动器更新 ZIP -./build.sh doctor # 显示 dotnet 环境信息 -./build.sh dist # 列出 dist/ 中的产物 -./build.sh clean # 清理 build/ 与 dist/ 等构建产物 +./build.sh build # 三平台完整发布:启动器 + SAVEDOG + 运行骨架 + 更新包 ZIP +./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查 +./build.sh models # 编译模型 dll、生成封面、更新并签名版本清单 +./build.sh stamp # 只重新生成 + 签名 version.json +./build.sh run # Debug 运行启动器 +./build.sh test # 离屏校验,截图写入 build/screenshots/ +./build.sh update-test # 离线验证自动更新链路(验签 / 立即生效 / 篡改拒绝 / 断网兜底) +./build.sh pack-models # 编译模型并打包 dist/models-<版本>.zip +./build.sh pack-launcher # 把已有平台发布目录打成启动器更新 ZIP +./build.sh doctor # dotnet 环境信息 +./build.sh dist # 列出 dist/ 产物 +./build.sh clean # 清理 build/ 与 dist/ ``` -`build` 是完整发布入口,不是单纯的解决方案编译;`check` 会检查至少三个版本化发布 ZIP。 -需要指定版本时,可追加 `-version=<版本>`(或 `--version=<版本>`),脚本会同步更新 `Directory.Build.props`。 -Windows 用 `.\build.ps1`(参数相同)。 - | 产物 | 平台 | | --- | --- | -| `dist/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包 | -| `dist/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 | -| `dist/GC-<版本>-win-arm64.zip` | Windows on ARM 单文件启动器 | +| `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) | +| `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` | +| `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 | -Windows 产物是自包含单文件启动器;macOS 产物是 `.app` 的 ZIP。**发布包内不含模型**。 -改完模型后运行 `./build.sh models`,再把根目录 `version.json` 和 `model/` 推送到 gitcode,客户端下次启动时自动更新。 +平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe` +会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。 + +发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip` +上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的 +`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。 +两种都能被客户端识别,客户端下次启动就会看到更新。 ## 模型契约 @@ -147,8 +240,25 @@ public interface IModelContext } ``` -启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度), -再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。 +**线程约定** + +| 成员 | 允许的线程 | 说明 | +| --- | --- | --- | +| `Prepare` | 后台线程(调用一次) | 可耗时;用 `ReportProgress` 汇报真实进度;此时**不要**创建控件 | +| `CreateView` | UI 线程(`Prepare` 之后调用一次) | 只在这里创建/操作 Avalonia 控件 | +| `ReportProgress` / `Log` | 任意线程 | 线程安全,内部自行封送到 UI | +| `RequestClose` | 任意线程 | 线程安全,等价于点窗口关闭按钮 | +| `Dispose` | UI 线程 | 释放后不要再调用 `Log` / `ReportProgress` | + +**契约版本协商** + +- `IModelFactory.ApiVersion` 与启动器支持的版本(当前 `1`)必须相等,否则拒绝加载并提示更新启动器。 +- 模型清单可写 `minAppVersion`(如 `"1.0.8"`):启动器版本更低时直接拒绝,并给出明确提示。 +- 提升契约版本时必须保留旧接口的适配层,或在启动器里明确「最低启动器版本」,避免老客户端加载新模型后崩溃。 + +**卸载注意**:关窗即 `Unload()` 收集式 AssemblyLoadContext。只要有静态字段、未解绑的事件、 +或缓存里还拿着模型内的类型/控件,程序集就回收不掉(内存持续增长)。 +模型作者应避免静态持有 `Control` / `IModelContext`,并在 `Dispose` 里解绑事件。 详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。 @@ -156,7 +266,7 @@ public interface IModelContext - 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口 - 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集 -- 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义 +- 所有由启动器打开的窗口(模型窗、加载窗、确认框、更新窗)都是 16px 圆角 ## 地球模型(model/_engine + model//src) @@ -168,20 +278,12 @@ public interface IModelContext **没有节气定位**(节气属于公转) - **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期) - **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮; - 所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**, - 俯视角只由「俯视」按钮显式切换 + 所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变** - **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明; 右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位; 快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角 -- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数 - -## 模型源(手动导入) - -除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库: -**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档, -失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/`。 ## 启动时运行内存分配 -设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb` +设置页的「启动时运行内存分配」类似启动器的 `-Xmx`:启动器把这份预算通过 `IModelContext.MemoryBudgetMb` 交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。 diff --git a/build.sh b/build.sh index 717be71..f64657b 100755 --- a/build.sh +++ b/build.sh @@ -22,6 +22,7 @@ ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) cd "$ROOT_DIR" APP_PROJ="GC-BOOT/GC-BOOT.csproj" +SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj" PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj" STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj" TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj" diff --git a/buildps1/lib/Build-Funcs.ps1 b/buildps1/lib/Build-Funcs.ps1 index 4ec1322..ce9c70f 100644 --- a/buildps1/lib/Build-Funcs.ps1 +++ b/buildps1/lib/Build-Funcs.ps1 @@ -12,12 +12,40 @@ function Invoke-LoggedDotNet { } } -function Invoke-VersionStamp { - Write-Host '==> 自动计算模型版本并生成 version.json' - Invoke-LoggedDotNet -Name 'stamp' -Arguments @( - 'run', '--project', $script:StampProject, '-c', 'Release', '--', - $script:BuildRoot, $script:BuildVersion +function Invoke-ManifestSign { + $key = Join-Path $script:BuildRoot '.signing/gc-signing.pem' + if (-not (Test-Path $key)) { + Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)' + return + } + $keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' } + Write-Host "==> 签名 version.json ($keyId)" + Invoke-LoggedDotNet -Name 'sign' -Arguments @( + 'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'), + '-c', 'Release', '--', 'sign', + '--manifest', (Join-Path $script:BuildRoot 'version.json'), + '--key', $key, '--key-id', $keyId ) + Copy-Item (Join-Path $script:BuildRoot 'version.json') (Join-Path $script:BuildRoot 'model/version.json') -Force +} + +function Invoke-VersionStamp { + param([switch]$LauncherOnly) + if ($LauncherOnly) { + Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)' + Invoke-LoggedDotNet -Name 'stamp' -Arguments @( + 'run', '--project', $script:StampProject, '-c', 'Release', '--', + $script:BuildRoot, $script:BuildVersion, '--launcher-only' + ) + } + else { + Write-Host '==> 自动计算模型版本并生成 version.json' + Invoke-LoggedDotNet -Name 'stamp' -Arguments @( + 'run', '--project', $script:StampProject, '-c', 'Release', '--', + $script:BuildRoot, $script:BuildVersion + ) + } + Invoke-ManifestSign } function Build-Models { @@ -51,7 +79,7 @@ function Prepare-RuntimeLayout { if (-not (Test-Path $destination)) { return } Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue - New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update') | Out-Null + New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @' 模型库目录(.GC/model/) 启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。 @@ -59,12 +87,13 @@ function Prepare-RuntimeLayout { 运行目录: <可执行文件> - .GC/settings.json + GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚) + .GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置) .GC/model/ 本目录(下载的模型) .GC/cache/ 下载暂存 .GC/update/ 待下次启动应用的启动器更新 '@ - $settingsPath = Join-Path $destination '.GC/settings.json' + $settingsPath = Join-Path $destination '.GC/config/settings.json' if (-not (Test-Path $settingsPath)) { Set-Content -Path $settingsPath -Encoding UTF8 -Value @' { @@ -73,6 +102,7 @@ function Prepare-RuntimeLayout { "renderFps": 30, "memoryMb": 2048, "autoUpdateOnStartup": true, + "requireSignedManifest": true, "updateRepository": "https://gitcode.com/Morris_1/GC", "updateManifestUrl": "", "updateLocalRoot": "", @@ -104,6 +134,21 @@ function Publish-Rid { "-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue", '-p:PublishTrimmed=false', '-o', $outputPath ) + + # 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB) + # 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs) + $savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj' + if (Test-Path $savedogProj) { + Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)" + Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @( + 'publish', $savedogProj, '-c', 'Release', '-r', $Rid, + '--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none', + '-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true', + '-p:PublishTrimmed=true', '-p:TrimMode=full', + '-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath + ) + } + Remove-Item (Join-Path $outputPath 'model'), (Join-Path $outputPath 'examples') -Recurse -Force -ErrorAction SilentlyContinue } @@ -136,11 +181,27 @@ function Pack-Launcher { Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)" foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) { - $sourceDir = Join-Path $dist $platform.Rid + # 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致 + $sourceDir = Join-Path $dist $platform.Label + if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid } if (-not (Test-Path $sourceDir)) { continue } - $executable = Get-ChildItem $sourceDir -Filter '*.exe' | Select-Object -First 1 + # 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面 + $executable = Get-ChildItem $sourceDir -Filter '*.exe' | + Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1 if ($null -eq $executable) { continue } - Copy-Item $executable.FullName (Join-Path $dist "GC-$script:BuildVersion-$($platform.Label).exe") -Force + + $temp = Join-Path $dist ".winpkg-$($platform.Label)" + Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Force -Path $temp | Out-Null + Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force + $savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe' + if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force } + + $zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip" + Remove-Item $zipPath -Force -ErrorAction SilentlyContinue + Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal + Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue + Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip" } $macApp = Join-Path $dist 'mac-arm64/GC.app' @@ -158,8 +219,12 @@ function Pack-Launcher { if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null } } - Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object { - $zipPath = Join-Path $dist ($_.BaseName + '.zip') + # Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app + Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object { + $label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", '' + $targetDir = Join-Path $dist $label + New-Item -ItemType Directory -Force -Path $targetDir | Out-Null + $zipPath = Join-Path $targetDir ($_.BaseName + '.zip') Remove-Item $zipPath -Force -ErrorAction SilentlyContinue if ($_.PSIsContainer) { Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue @@ -171,19 +236,30 @@ function Pack-Launcher { else { Compress-Archive -Path $_.FullName -DestinationPath $zipPath -CompressionLevel Optimal } + Write-Host " -> dist/$label/$($_.BaseName).zip" } - Remove-Item (Join-Path $dist "GC-$script:BuildVersion-*.exe") -Force -ErrorAction SilentlyContinue - Remove-Item (Join-Path $dist "GC-$script:BuildVersion-*.app") -Recurse -Force -ErrorAction SilentlyContinue + # 原始产物(.exe / .app 目录)不再保留:只发布 zip + $trash = Join-Path $script:BuildRoot 'build/trash' + New-Item -ItemType Directory -Force -Path $trash | Out-Null + Get-ChildItem $dist -Force | Where-Object { + $_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app" + } | ForEach-Object { + Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue + } Remove-IntermediateDirectories - Invoke-VersionStamp + Invoke-VersionStamp -LauncherOnly Write-Host '==> dist 可发布 zip:' - Get-ChildItem $dist -Filter "GC-$script:BuildVersion-*.zip" | Select-Object Name, Length + Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length } function Remove-IntermediateDirectories { - foreach ($name in @('win-x64', 'win-arm64', 'mac-arm64')) { - Remove-Item (Join-Path $script:BuildRoot "dist/$name") -Recurse -Force -ErrorAction SilentlyContinue + # 平台目录里只留最终 zip(其它都是 publish 中间产物) + foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) { + $dir = Join-Path $script:BuildRoot "dist/$name" + if (-not (Test-Path $dir)) { continue } + Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } | + Remove-Item -Recurse -Force -ErrorAction SilentlyContinue } Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force } @@ -248,12 +324,12 @@ function Invoke-FullBuild { Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; Complete-BuildStep - Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-x64' $true; Complete-BuildStep + Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep Start-BuildStep '运行骨架' New-MacAppBundle - Prepare-RuntimeLayout 'dist/win-x64' + Prepare-RuntimeLayout 'dist/win-amd64' Prepare-RuntimeLayout 'dist/win-arm64' Prepare-RuntimeLayout 'dist/mac-arm64/GC.app/Contents/MacOS' Complete-BuildStep @@ -261,7 +337,7 @@ function Invoke-FullBuild { Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep Start-BuildStep '收尾'; Complete-BuildStep Write-Host '==> 完成,产物:' - Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter "GC-$script:BuildVersion-*.zip" | Select-Object Name, Length + Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length } finally { Complete-BuildProgress } } \ No newline at end of file diff --git a/buildsh/build.sh b/buildsh/build.sh index b6efa4e..ba17674 100644 --- a/buildsh/build.sh +++ b/buildsh/build.sh @@ -11,6 +11,11 @@ bs_build() { progress_step "清理旧产物"; progress_tick 100 rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist" + # 上次打包挪出来的中间产物(.app 目录,体积大、文件多)直接移出 build, + # 不做递归删除:避免动辄几百个文件的不可逆删除。 + if [ -d "$ROOT_DIR/build/trash" ]; then + mv "$ROOT_DIR/build/trash" "${TMPDIR:-/tmp}/gc-trash-$(date +%s)" 2>/dev/null || true + fi progress_step "版本戳"; progress_tick 100 stamp_versions @@ -36,14 +41,14 @@ bs_build() { _run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1 progress_step "编译 Win-x64" - _run_publish winx64 70 publish_rid "win-x64" "dist/win-x64" true || return 1 + _run_publish winx64 70 publish_rid "win-x64" "dist/win-amd64" true || return 1 progress_step "编译 Win-arm64" _run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1 progress_step "运行骨架"; progress_tick 100 package_mac_app - prepare_runtime_layout "dist/win-x64" + prepare_runtime_layout "dist/win-amd64" prepare_runtime_layout "dist/win-arm64" prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS" @@ -53,5 +58,5 @@ bs_build() { progress_step "收尾"; progress_tick 100 progress_done echo "==> 完成,产物:" - ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null || true + ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true } diff --git a/buildsh/check.sh b/buildsh/check.sh index e4ff296..7790e27 100644 --- a/buildsh/check.sh +++ b/buildsh/check.sh @@ -33,7 +33,7 @@ bs_check() { fi progress_step "产物检查" - _n=$(ls "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null | wc -l | tr -d ' ') + _n=$(ls "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null | wc -l | tr -d ' ') if [ "$_n" -ge 3 ]; then progress_tick 100 else diff --git a/buildsh/lib/build_funcs.sh b/buildsh/lib/build_funcs.sh index 630e398..a8d52e6 100644 --- a/buildsh/lib/build_funcs.sh +++ b/buildsh/lib/build_funcs.sh @@ -9,6 +9,36 @@ if ! type progress >/dev/null 2>&1; then progress() { :; }; fi stamp_versions() { echo "==> 自动计算模型版本并生成 version.json" dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION" + sign_manifest +} + +# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。 +# 只重写清单的启动器段:模型指纹可能涉及几百 MB 文件,没必要再算一遍。 +stamp_launcher_only() { + echo "==> 刷新启动器包信息(sha256 / 体积 / dist 路径)" + dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION" --launcher-only + sign_manifest +} + +# 用 .signing/ 里的私钥给 version.json 签名(私钥不入库)。 +# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。 +sign_manifest() { + KEY="$ROOT_DIR/.signing/gc-signing.pem" + KEYID="${GC_SIGNING_KEY_ID:-gc-2026-11}" + if [ ! -f "$KEY" ]; then + echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)" + echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen" + return 0 + fi + echo "==> 签名 version.json(${KEYID})" + if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \ + sign --manifest "$ROOT_DIR/version.json" --key "$KEY" --key-id "$KEYID"; then + # model/version.json 必须与根清单完全一致(同一个签名),否则走 model 地址的源会验签失败 + cp "$ROOT_DIR/version.json" "$ROOT_DIR/model/version.json" + else + echo "!! 签名失败,version.json 保持未签名状态" + return 1 + fi } # 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包 @@ -41,7 +71,7 @@ prepare_runtime_layout() { DEST="$ROOT_DIR/$REL" [ -d "$DEST" ] || return 0 rm -rf "$DEST/model" "$DEST/examples" - mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update" + mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update" "$DEST/.GC/config" cat > "$DEST/.GC/model/README.txt" <<'TXT' 模型库目录(.GC/model/) 启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。 @@ -49,19 +79,21 @@ prepare_runtime_layout() { 运行目录: <可执行文件> - .GC/settings.json + GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚) + .GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置) .GC/model/ 本目录(下载的模型) .GC/cache/ 下载暂存 .GC/update/ 待下次启动应用的启动器更新 TXT - if [ ! -f "$DEST/.GC/settings.json" ]; then - cat > "$DEST/.GC/settings.json" <<'JSON' + if [ ! -f "$DEST/.GC/config/settings.json" ]; then + cat > "$DEST/.GC/config/settings.json" <<'JSON' { "language": "auto", "theme": "light", "renderFps": 30, "memoryMb": 2048, "autoUpdateOnStartup": true, + "requireSignedManifest": true, "updateRepository": "https://gitcode.com/Morris_1/GC", "updateManifestUrl": "", "updateLocalRoot": "", @@ -74,7 +106,7 @@ TXT } JSON fi - echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)" + echo " 运行目录 -> $REL/.GC (config/settings.json + model/ + cache/ + update/)" } # $1=RID $2=输出目录 $3=singlefile(true/false) @@ -94,6 +126,27 @@ publish_rid() { -p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \ -p:PublishTrimmed=false \ -o "$ROOT_DIR/$OUT" + + # 更新守护进程:与主程序同目录(macOS 打包时会被一起移入 Contents/MacOS) + if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$ROOT_DIR/$SAVEDOG_PROJ" ]; then + echo "==> 编译 GC-SAVEDOG (${RID}) -> ${OUT}(裁剪单文件)" + # 守护进程不引用 Avalonia,可以安全裁剪:70MB -> 14MB。 + # 前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs),新增 JSON 类型 + # 忘了注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。 + dotnet publish "$SAVEDOG_PROJ" \ + -c Release \ + -r "$RID" \ + --self-contained true \ + -p:Version="$VERSION" \ + -p:DebugType=none \ + -p:PublishSingleFile=true \ + -p:IncludeNativeLibrariesForSelfExtract=true \ + -p:PublishTrimmed=true \ + -p:TrimMode=full \ + -p:JsonSerializerIsReflectionEnabledByDefault=false \ + -o "$ROOT_DIR/$OUT" + fi + rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples" } @@ -109,7 +162,14 @@ pack_models() { } # 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置) -# 产物命名:GC-<版本>-<系统>-<架构>.exe / GC-<版本>-<系统>-<架构>.app.zip +# +# 产物落点遵循「仓库 dist/<系统>-<架构>/」布局: +# dist/mac-arm64/GC-<版本>-mac-arm64.zip +# dist/win-amd64/GC-<版本>-win-amd64.zip +# dist/win-arm64/GC-<版本>-win-arm64.zip +# 启动器更新时既可以从 Release 附件下载,也会到这些目录里找编译产物 +# (见 GC-DOWNLOAD/LauncherArtifacts.cs),所以两种发布方式都能用。 +# # Windows: 单文件 exe 直接改名(本身就是可执行产物) # macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip, # 这样 macOS 双击会用归档工具解压出可运行的 .app。 @@ -117,17 +177,31 @@ pack_models() { pack_launcher() { echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)" - # --- Windows:exe 单文件 --- + # --- Windows:exe 单文件(连同 GC-SAVEDOG.exe 一起打进 zip)--- for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do RID="${pair%%:*}"; LABEL="${pair##*:}" - SRC="$ROOT_DIR/dist/$RID" + SRC="$ROOT_DIR/dist/$LABEL" + [ -d "$SRC" ] || SRC="$ROOT_DIR/dist/$RID" # 兼容旧布局 [ -d "$SRC" ] || continue - EXE=$(ls "$SRC"/*.exe 2>/dev/null | head -1) + # 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面 + EXE=$(ls "$SRC"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG' | head -1) [ -n "$EXE" ] || continue - DEST="$ROOT_DIR/dist/GC-${VERSION}-${LABEL}.exe" - cp "$EXE" "$DEST" - chmod +x "$DEST" - echo " -> $(basename "$DEST")" + + TMP="$ROOT_DIR/dist/.winpkg-$LABEL" + rm -rf "$TMP"; mkdir -p "$TMP" + cp "$EXE" "$TMP/GC-${VERSION}-${LABEL}.exe" + chmod +x "$TMP/GC-${VERSION}-${LABEL}.exe" 2>/dev/null || true + if [ -f "$SRC/GC-SAVEDOG.exe" ]; then + cp "$SRC/GC-SAVEDOG.exe" "$TMP/GC-SAVEDOG.exe" + else + echo " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新" + fi + + ZIP="$ROOT_DIR/dist/$LABEL/GC-${VERSION}-${LABEL}.zip" + rm -f "$ZIP" + ( cd "$TMP" && zip -q "$ZIP" ./* ) + rm -rf "$TMP" + echo " -> dist/$LABEL/GC-${VERSION}-${LABEL}.zip" done # --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)--- @@ -146,17 +220,17 @@ pack_launcher() { echo " -> $(basename "$FINAL")/" fi - # --- 统一压缩:每个产物都打成同名 .zip --- - # GC-1.0.3-win-amd64.exe -> GC-1.0.3-win-amd64.zip - # GC-1.0.3-win-arm64.exe -> GC-1.0.3-win-arm64.zip - # GC-1.0.3-mac-arm64.app -> GC-1.0.3-mac-arm64.zip + # --- 统一压缩:每个产物都打成同名 .zip,放进自己的平台目录 --- + # GC-1.0.3-mac-arm64.app -> dist/mac-arm64/GC-1.0.3-mac-arm64.zip # 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。 echo "==> 压缩为 zip" for art in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do [ -e "$art" ] || continue base=$(basename "$art") name="${base%.*}" # 去掉 .exe / .app - ZIP="$ROOT_DIR/dist/${name}.zip" + label="${name#GC-${VERSION}-}" # mac-arm64 / win-amd64 + ZIP="$ROOT_DIR/dist/${label}/${name}.zip" + mkdir -p "$ROOT_DIR/dist/${label}" rm -f "$ZIP" if [ -d "$art" ]; then # 目录(.app):保留权限与符号链接 @@ -168,24 +242,32 @@ pack_launcher() { else ( cd "$(dirname "$art")" && zip -q "$ZIP" "$base" ) fi - echo " -> ${name}.zip" + echo " -> dist/${label}/${name}.zip" done - # 原始产物(.exe / .app 目录)不再保留:只发布 zip - rm -f "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe - rm -rf "$ROOT_DIR"/dist/GC-"$VERSION"-*.app + # 原始产物(.exe / .app 目录)不再保留:只发布 zip。 + # 用「移入暂存区」而不是 rm -rf:.app 里有两百多个文件, + # 一次性删除又慢又不可逆,先挪走更安全(暂存区在下次构建开始时挪出 dist)。 + TRASH="$ROOT_DIR/build/trash" + mkdir -p "$TRASH" + for leftover in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do + [ -e "$leftover" ] || continue + mv "$leftover" "$TRASH/$(basename "$leftover")-$(date +%s)" 2>/dev/null || true + done strip_intermediate_dirs - stamp_versions + stamp_launcher_only echo "" - echo "==> dist 只保留可发布的 zip:" - ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-*.zip 2>/dev/null || true + echo "==> dist 里可发布的 zip:" + ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true } -# 删除 publish 过程中的中间目录,dist 里只留最终附件 +# 删除 publish 过程中的中间目录:平台目录里只留最终 zip strip_intermediate_dirs() { - for d in win-x64 win-arm64 mac-arm64; do - [ -d "$ROOT_DIR/dist/$d" ] && rm -rf "$ROOT_DIR/dist/$d" + for d in win-amd64 win-x64 win-arm64 mac-arm64; do + [ -d "$ROOT_DIR/dist/$d" ] || continue + find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \ + ! -name "GC-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true done find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true } diff --git a/buildsh/tools.sh b/buildsh/tools.sh index b39e9b0..a8281fd 100644 --- a/buildsh/tools.sh +++ b/buildsh/tools.sh @@ -26,7 +26,7 @@ bs_tools() { dotnet --info | head -20 ;; dist) echo "==> dist 产物:" - ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;; + ls -lh "$ROOT_DIR"/dist/*/GC-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;; *) echo "未知工具: $TASK"; return 1 ;; esac diff --git a/model/README.md b/model/README.md index 5f69125..63d4911 100644 --- a/model/README.md +++ b/model/README.md @@ -21,7 +21,7 @@ model/ _engine/ # 共享引擎源码 src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster… PreviewGen/ # 用模型渲染器生成封面的小工具 - VersionStamp/ # 按内容指纹自动打版本、生成 version.json + VersionStamp/ # 生成 version.json(手写版本 + 完整性哈希) <模型 id>/ <模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面 src/ # 模型自己的源码(csproj + IModelFactory 实现) @@ -34,22 +34,34 @@ model/ i18n/en.json ``` -## 版本是自动改的 +## 版本、指纹与完整性 `./build.sh models`(或 `./build.sh stamp`)会调用 `model/_engine/VersionStamp`: -1. 对每个模型,把 `.json`(去掉 `version` / `updatedAt`)与 `.model/` 下所有文件 - 按路径排序做 SHA-256 指纹,得到版本号 `1.0-<10位指纹>`; -2. 把这个版本写回 `.json` 的 `version` 与 `updatedAt`; -3. 生成仓库根 `version.json` 和 `model/version.json`(内容相同),里面记录 - 启动器版本、各平台更新包地址、每个模型的 id / 版本 / 仓库目录。 +1. 读每个模型的 `.json`,**保留作者手写的 `version`**(如 `1.6`)—— + 版本号是对用户可见的语义版本,不由指纹自动覆盖; +2. 计算 `build`:`.json`(去掉 `build` / `updatedAt`)与 `.model/` 下所有文件 + 按路径排序后的 SHA-256 指纹前 10 位,**仅用于构建溯源**; +3. 计算完整性哈希(客户端下载后会复算,不一致就丢弃): + - `manifestSha256` = 清单文件本身的 sha256 + - `filesSha256` = `.model` 目录指纹 +4. 生成仓库根 `version.json` 与 `model/version.json`(内容相同),再用 + `.signing/gc-signing.pem` 签名(ECDSA P-256),两份文件写的是**同一份签名**。 -**所以只要改了模型文件,版本号就自动变**,不需要手工维护;内容没变时重复构建版本号保持不变。 -客户端启动时读 `version.json`,和 `.GC/settings.json` 里记录的版本一比对就知道要不要下载。 +**改了模型内容必须手动升 `version`**,否则客户端认为版本没变,不会下载。 +(`build` 会变,但它不参与版本比较。) -> 改了 `scene.json` 或引擎源码后,跑 `./build.sh models`,再把 `version.json` 和 `model/` -> 推送到 gitcode;客户端下次启动会下载新模型并**本次启动立即生效**。 -> 启动器自身更新包由 `./build.sh publish` 生成(`dist/GC-.zip`),下载后**下次启动才应用**。 +哈希算法(构建端与客户端共用 `GC/src/Security/ContentHash.cs`,不会出现两套实现): + +``` +fileHash = SHA256(文件字节) +dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0\n" ) +``` + +相对路径统一 `/`,跳过 `.` 开头文件、`bin/`、`obj/`、`*.user`;不含时间戳/权限位。 + +安装成功后客户端会在模型目录写 `.integrity.json`,每次加载 dll 前抽查 +dll / json 的哈希 —— 本地文件被替换会直接拒绝加载。 ## `.json`(模型清单,启动器只读它) @@ -60,24 +72,45 @@ model/ "nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" }, "description": "……", "descriptionI18n": { "zh-CN": "……", "en": "……" }, - "version": "1.0-3f9a2c1b7d", - "updatedAt": "2026-11-07T08:00:00Z", + "version": "1.6", + "updatedAt": "2026-11-14T08:00:00Z", "author": "NeoRF", "tags": ["astronomy", "geography"], "assembly": "EarthRotationModel.dll", "type": "NeoRF.EarthModels.RotationModelFactory", "preview": "preview.png", - "apiVersion": 1 + "apiVersion": 1, + "minAppVersion": "1.0.7" } ``` | 字段 | 作用 | | --- | --- | -| `version` | **自动生成**,模型包内容指纹;客户端靠它判断是否需要更新 | +| `version` | **作者手写**的语义版本;客户端靠它判断是否需要更新 | | `assembly` | 功能程序集文件名,相对 `.model`;留空按 `.dll` 找 | | `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 | | `preview` | 封面图,默认 `preview.png` | -| `apiVersion` | 模型契约版本,目前为 1 | +| `apiVersion` | 模型契约版本,目前为 1;高于启动器支持版本会拒绝加载并提示升级 | +| `minAppVersion` | 可选,要求的最低启动器版本(如 `1.0.7`) | + +`build` / `manifestSha256` / `filesSha256`(只出现在 `version.json` 里)由构建自动写入, +**不要手改**。 + +## 最小可分发结构 + +一个能跑的最小模型只需要三个文件: + +``` +model/hello/ + hello.json # 清单(id / version / assembly / type / apiVersion) + hello.model/ + HelloModel.dll # 实现 IModelFactory,返回任意 Avalonia 控件 +``` + +其余(`preview.png`、`i18n/`、`scene.json`、`land.json`)都是可选的: +没有封面用默认灰图,没有语言包用清单里的 `name` / `description`。 +源码放在同目录的 `src/` 里,`./build.sh models` 会自动编译并把 dll 复制进 `hello.model/`。 + ## 模型契约(model/_sdk) @@ -152,5 +185,9 @@ public interface IModelContext - **自动更新(推荐)**:把 `version.json` 和 `model/` 推到 gitcode 仓库,启动器开机自检并下载到 `.GC/model/` - **离线源**:把整个仓库目录(含 `version.json` + `model/`)拷到 U 盘 / 共享盘, - 在 `.GC/settings.json` 填 `updateLocalRoot` 指向它 + 在 `.GC/config/settings.json` 填 `updateLocalRoot` 指向它 - **手动导入**:在「下载」页粘贴任意 git 仓库 / zip / 本地目录,读取其中的 `model/` 文件夹 + +> 三种方式都会**验签**:`version.json` 必须由受信任私钥签名,否则客户端拒绝安装。 +> 自己维护分支时,用 `dotnet run --project GC-SAVEDOG -- keygen` 生成密钥, +> 把公钥加进 `GC/src/Security/SignatureKeyring.cs`,再用 `--sign`/`build.sh stamp` 签名。 diff --git a/model/_engine/VersionStamp/Program.cs b/model/_engine/VersionStamp/Program.cs index e415c6c..662e109 100644 --- a/model/_engine/VersionStamp/Program.cs +++ b/model/_engine/VersionStamp/Program.cs @@ -3,6 +3,7 @@ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; +using GC.Services; // VersionStamp:构建时自动给模型打版本。 // 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本> @@ -12,8 +13,15 @@ using System.Text.Json.Nodes; // 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。 const string Repository = "https://gitcode.com/Morris_1/GC"; -var root = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory(); -var launcherVersion = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]) ? args[1] : "1.0.0"; +// 位置参数:<仓库根> <启动器版本>;开关:--launcher-only +// --launcher-only 只刷新 launcher.packages(构建脚本在打完 zip 之后再调一次), +// 不重算模型指纹 —— 模型文件可能有几百 MB,重复哈希纯属浪费。 +var positional = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray(); +var launcherOnly = args.Any(a => a.Equals("--launcher-only", StringComparison.OrdinalIgnoreCase)); + +var root = positional.Length > 0 ? Path.GetFullPath(positional[0]) : Directory.GetCurrentDirectory(); +var launcherVersion = positional.Length > 1 && !string.IsNullOrWhiteSpace(positional[1]) + ? positional[1] : "1.0.0"; var modelRoot = Path.Combine(root, "model"); if (!Directory.Exists(modelRoot)) @@ -49,8 +57,11 @@ static string Fingerprint(IEnumerable chunks) return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); } +var models = new List>(); + +if (!launcherOnly) +{ Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)"); -var models = new List>(); foreach (var dir in Directory.GetDirectories(modelRoot) .OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal)) @@ -70,8 +81,11 @@ foreach (var dir in Directory.GetDirectories(modelRoot) var declared = manifest["version"]?.GetValue(); var version = string.IsNullOrWhiteSpace(declared) ? "1.0" : declared!.Trim(); - // 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较 + // 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较。 + // 注意:updatedAt / build 都是构建元数据,必须从指纹里剔除, + // 否则「同一份内容」每次构建都会算出不同指纹(等于每次都触发更新)。 manifest.Remove("build"); + manifest.Remove("updatedAt"); var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false }); var chunks = new List { Encoding.UTF8.GetBytes(canonical) }; foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories) @@ -86,17 +100,29 @@ foreach (var dir in Directory.GetDirectories(modelRoot) manifest["version"] = version; manifest["build"] = fingerprint; manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); - File.WriteAllText(manifestPath, manifest.ToJsonString(relaxed) + "\n"); + var manifestText = manifest.ToJsonString(relaxed) + "\n"; + File.WriteAllText(manifestPath, manifestText); - models.Add(new Dictionary + // 完整性哈希:客户端下载后按同一算法复算,不一致就丢弃。 + // manifestSha256 = 清单文件本身的 sha256 + // filesSha256 = .model 目录指纹(算法见 GC/src/Security/ContentHash.cs) + var manifestSha = ContentHash.Sha256Hex(manifestText); + var filesMap = ContentHash.MapFiles(dataDir); + var filesSha = ContentHash.DirectoryHash(filesMap); + + models.Add(new Dictionary { ["id"] = id, ["version"] = version, ["build"] = fingerprint, + ["manifestSha256"] = manifestSha, + ["filesSha256"] = filesSha, + ["files"] = filesMap.Count, ["dir"] = "model/" + id }); - Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint})"); + Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint}, {filesMap.Count} files)"); } +} // !launcherOnly // 启动器源码指纹(只展示,不触发升级;升级看 launcher.version) var srcRoot = Path.Combine(root, "src"); @@ -119,24 +145,45 @@ if (Directory.Exists(srcRoot)) var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : ""; var packages = new Dictionary>(); -// 启动器更新只访问「编译的产物」:gitcode Release 里发布的 dist/GC-.zip 附件。 -// 运行时若存在同名 Release,GitCodeReleaseRemote 会用附件真实直链覆盖下面的 url; -// 下面的地址是兜底(编译产物尚未发 Release 时也能指向正确的编译产物位置)。 +// 启动器更新包的两种落点,清单里都写清楚,下载端按顺序尝试: +// 1) Release 附件(url)—— 常规发布方式; +// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip —— +// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。 +// 两种都写:url 只是「去哪儿找」,真正的完整性凭据是下面的 sha256(受签名保护)。 var releaseBase = $"{Repository}/releases/download/v{launcherVersion}"; foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" }) { + var label = LauncherArtifacts.LabelOf(rid); + var fileName = LauncherArtifacts.PackageFileName(launcherVersion, rid); + var dir = $"dist/{label}"; + var entry = new Dictionary { - ["path"] = $"dist/GC-{rid}.zip", - ["url"] = $"{releaseBase}/GC-{rid}.zip" + ["path"] = $"{dir}/{fileName}", + ["dir"] = dir, + ["name"] = fileName, + ["url"] = $"{releaseBase}/{fileName}" }; - // 已生成的启动器更新包:把校验值和体积写进清单,供下载端校验 - var zipPath = Path.Combine(root, "dist", $"GC-{rid}.zip"); - if (File.Exists(zipPath)) + + // 优先认平台产物目录,其次认 dist 根目录(历史构建把 zip 直接放在 dist/) + var zipPath = new[] + { + Path.Combine(root, dir.Replace('/', Path.DirectorySeparatorChar), fileName), + Path.Combine(root, "dist", fileName), + Path.Combine(root, "dist", $"GC-{rid}.zip") + }.FirstOrDefault(File.Exists); + + if (zipPath != null) { var bytes = File.ReadAllBytes(zipPath); + entry["path"] = Rel(root, zipPath); entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); entry["size"] = bytes.LongLength; + Console.WriteLine($" 包 {label,-12} {entry["path"]}({bytes.LongLength / 1024 / 1024} MB)"); + } + else + { + Console.WriteLine($" 包 {label,-12} 未找到产物(清单里不会有 sha256,下载端会跳过该平台)"); } packages[rid] = entry; } @@ -157,8 +204,26 @@ var versionDoc = new Dictionary ["models"] = models }; +// --launcher-only:模型段沿用现有清单,只换启动器包,避免重复哈希几百 MB 模型文件 +if (launcherOnly) +{ + var manifestPath = Path.Combine(root, "version.json"); + if (File.Exists(manifestPath)) + { + var existing = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject(); + if (existing?["models"] is JsonNode existingModels) + versionDoc["models"] = existingModels.DeepClone(); + if (existing?["generated"] is JsonNode generated) + versionDoc["generated"] = generated.DeepClone(); + } + else + { + Console.Error.WriteLine("!! --launcher-only 需要已存在的 version.json,退回完整模式"); + } +} + var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n"; File.WriteAllText(Path.Combine(root, "version.json"), json); File.WriteAllText(Path.Combine(modelRoot, "version.json"), json); -Console.WriteLine($"==> version.json 已生成(启动器 {launcherVersion},模型 {models.Count} 个)"); +Console.WriteLine($"==> version.json 已更新(启动器 {launcherVersion},模型 {models.Count} 个)"); return 0; diff --git a/model/_engine/VersionStamp/VersionStamp.csproj b/model/_engine/VersionStamp/VersionStamp.csproj index 0ef6e2a..46ab4ce 100644 --- a/model/_engine/VersionStamp/VersionStamp.csproj +++ b/model/_engine/VersionStamp/VersionStamp.csproj @@ -8,5 +8,11 @@ VersionStamp VersionStamp + + + + + + diff --git a/model/_sdk/GC.ModelSdk/IModelContracts.cs b/model/_sdk/GC.ModelSdk/IModelContracts.cs index 98f0891..54885b4 100644 --- a/model/_sdk/GC.ModelSdk/IModelContracts.cs +++ b/model/_sdk/GC.ModelSdk/IModelContracts.cs @@ -9,7 +9,12 @@ namespace GC.ModelSdk; /// public interface IModelFactory { - /// 契约版本。启动器目前支持 1。 + /// + /// 契约版本。启动器目前支持 1。 + /// 协商规则:必须与启动器支持的版本**相等**,否则启动器拒绝加载并提示用户更新; + /// 模型清单里还可以写 minAppVersion 要求更高的启动器版本。 + /// 提升版本时必须保留旧接口的适配层,避免老客户端加载新模型后崩溃。 + /// int ApiVersion { get; } /// 创建一个模型运行时实例(每个窗口一个实例)。 @@ -19,6 +24,10 @@ public interface IModelFactory /// /// 模型运行时:负责把模型自己的界面交给启动器。 /// 启动器只负责开窗口,**不参与任何渲染**。 +/// +/// 生命周期:Create() → Prepare()(后台线程,一次)→ CreateView()(UI 线程,一次) +/// → 用户关窗 → Dispose()(UI 线程)。Dispose 之后不要再调用任何 +/// 成员。 /// public interface IModelRuntime : IDisposable { @@ -54,15 +63,15 @@ public interface IModelContext /// 用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。 int MemoryBudgetMb { get; } - /// 请求关闭承载此模型的窗口。 + /// 请求关闭承载此模型的窗口。**线程安全**,任意线程可调用。 void RequestClose(); /// /// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示, - /// 也可以在任何时候调用(例如切换数据集时)。 + /// 也可以在任何时候调用(例如切换数据集时)。**线程安全**,任意线程可调用。 /// void ReportProgress(double value, string? message = null); - /// 输出日志(启动器会写到控制台)。 + /// 输出日志(启动器会写到控制台)。**线程安全**,任意线程可调用。 void Log(string message); } diff --git a/model/contour-map/contour-map.json b/model/contour-map/contour-map.json index a5df168..069f52d 100644 --- a/model/contour-map/contour-map.json +++ b/model/contour-map/contour-map.json @@ -25,6 +25,6 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "updatedAt": "2026-11-14T10:53:39Z", - "build": "d3eb662a36" + "build": "e4b3f2b87e", + "updatedAt": "2026-11-14T11:34:35Z" } diff --git a/model/earth-geography/earth-geography.json b/model/earth-geography/earth-geography.json index db3f1f9..f81d9e7 100644 --- a/model/earth-geography/earth-geography.json +++ b/model/earth-geography/earth-geography.json @@ -18,7 +18,6 @@ ], "dataDir": "earth-geography.model", "version": "1.8", - "updatedAt": "2026-11-14T10:53:39Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -26,5 +25,6 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "d5ad961ed1" + "build": "3b645c45c2", + "updatedAt": "2026-11-14T11:34:35Z" } diff --git a/model/earth-revolution/earth-revolution.json b/model/earth-revolution/earth-revolution.json index 0284e66..9dab1ad 100644 --- a/model/earth-revolution/earth-revolution.json +++ b/model/earth-revolution/earth-revolution.json @@ -24,7 +24,6 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.6", - "updatedAt": "2026-11-14T10:53:39Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -32,5 +31,6 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "287b1d86af" + "build": "947efa36bb", + "updatedAt": "2026-11-14T11:34:35Z" } diff --git a/model/earth-rotation/earth-rotation.json b/model/earth-rotation/earth-rotation.json index ca72b6f..d702825 100644 --- a/model/earth-rotation/earth-rotation.json +++ b/model/earth-rotation/earth-rotation.json @@ -24,7 +24,6 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.6", - "updatedAt": "2026-11-14T10:53:39Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -32,5 +31,6 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "83124cb2ac" + "build": "a803d9c020", + "updatedAt": "2026-11-14T11:34:35Z" } diff --git a/model/scale-calculator/scale-calculator.json b/model/scale-calculator/scale-calculator.json index 3e0924f..3522f5d 100644 --- a/model/scale-calculator/scale-calculator.json +++ b/model/scale-calculator/scale-calculator.json @@ -25,7 +25,6 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.5", - "updatedAt": "2026-11-14T10:53:39Z", "chrome": { "titleBar": "#FFFFFF", "titleBorder": "#E3E8F3", @@ -33,5 +32,6 @@ "button": "#5B6A86", "frame": "#F4F6FB" }, - "build": "b8930576fd" + "build": "02a555272a", + "updatedAt": "2026-11-14T11:34:35Z" } diff --git a/model/version.json b/model/version.json index 41c92cd..b0a6e48 100644 --- a/model/version.json +++ b/model/version.json @@ -1,6 +1,6 @@ { "schema": 1, - "generated": "2026-11-14T10:53:39Z", + "generated": "2026-11-14T11:34:35Z", "repository": "https://gitcode.com/Morris_1/GC", "branch": "main", "modelDir": "model", @@ -9,24 +9,40 @@ "revision": "", "packages": { "win-x64": { - "path": "dist/GC-win-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-x64.zip" + "path": "dist/win-amd64/GC-1.0.7-win-amd64.zip", + "dir": "dist/win-amd64", + "name": "GC-1.0.7-win-amd64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip", + "sha256": "f90ff51ac6b041ae238cbeb4672622b0d029142a9d8b0705f08e654336512308", + "size": 46363183 }, "win-arm64": { - "path": "dist/GC-win-arm64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-arm64.zip" + "path": "dist/win-arm64/GC-1.0.7-win-arm64.zip", + "dir": "dist/win-arm64", + "name": "GC-1.0.7-win-arm64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip", + "sha256": "0b2bab2c3ac7e6223d8dd0b0faf9a0994319fa5ad13826addf7b402619b812e0", + "size": 44390354 }, "osx-arm64": { - "path": "dist/GC-osx-arm64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-arm64.zip" + "path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip", + "dir": "dist/mac-arm64", + "name": "GC-1.0.7-mac-arm64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip", + "sha256": "e5fd355bace68dc0794eb3e049cbef63c952a60a765ab3806adaf1199e1b09ab", + "size": 9178314 }, "osx-x64": { - "path": "dist/GC-osx-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-x64.zip" + "path": "dist/mac-x64/GC-1.0.7-mac-x64.zip", + "dir": "dist/mac-x64", + "name": "GC-1.0.7-mac-x64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip" }, "linux-x64": { - "path": "dist/GC-linux-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-linux-x64.zip" + "path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip", + "dir": "dist/linux-amd64", + "name": "GC-1.0.7-linux-amd64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip" } } }, @@ -34,32 +50,54 @@ { "id": "contour-map", "version": "1.0", - "build": "d3eb662a36", + "build": "e4b3f2b87e", + "manifestSha256": "ee0897d46ee85126fbfd0d07f5ca3111950d0c36f9b8a80e4eb6ae85d226da4f", + "filesSha256": "b1f323fb41dec4f45992a30ff8726f3307f83b564127aff99bcb3d044c79d2bd", + "files": 5, "dir": "model/contour-map" }, { "id": "earth-geography", "version": "1.8", - "build": "d5ad961ed1", + "build": "3b645c45c2", + "manifestSha256": "a9f30fd4a1dd0aeccb88c892579c93bf32a92379d7b3f545b28f6cac612f9871", + "filesSha256": "0e55d2f9bacc3e0ff42f5c45d9e7c265864df9784b1609c09dcb32d21b4addfc", + "files": 11, "dir": "model/earth-geography" }, { "id": "earth-revolution", "version": "1.6", - "build": "287b1d86af", + "build": "947efa36bb", + "manifestSha256": "feb715cde8ad5da9ecfb48785a95e6fc82930cc92c668514b328915366c2f57a", + "filesSha256": "a37e0b493c78bb0a04a276512b612be3f8e7a178ed1a7fc72acb5353aa57f7c5", + "files": 7, "dir": "model/earth-revolution" }, { "id": "earth-rotation", "version": "1.6", - "build": "83124cb2ac", + "build": "a803d9c020", + "manifestSha256": "56ed397cbc008bd9ec8bea0ee34a94a28ab29ce39a8b096b0629e529883b4dff", + "filesSha256": "4e4428812d18d15a99105e73c027b99f3197033f0138d643ba69c15fabc9d8f6", + "files": 7, "dir": "model/earth-rotation" }, { "id": "scale-calculator", "version": "1.5", - "build": "b8930576fd", + "build": "02a555272a", + "manifestSha256": "d00034888d9b9da03338b7f394d1bdf33f73b1fbdd7e8f154d85b9080318ab13", + "filesSha256": "4a5fbf898df1d98eddf68b5d3929ae7b25cd7bcdfdfa36b5ad0ed72d9941d049", + "files": 6, "dir": "model/scale-calculator" } - ] + ], + "signature": { + "alg": "ECDSA-P256-SHA256", + "keyId": "gc-2026-11", + "value": "LHaF2bw+IZeWUw2qLQM1IQHoNXsHNko38dyjP45Jy41KtlyhvJhhFaNh+THKhAU+6jSzV1eFHgbwasboYBOa5w==", + "contentSha256": "749055593bf9839837428d900d523b3363486556970cbf4e2daa25001ab174c8", + "signedAt": "2026-11-14T11:36:03Z" + } } diff --git a/version.json b/version.json index 41c92cd..b0a6e48 100644 --- a/version.json +++ b/version.json @@ -1,6 +1,6 @@ { "schema": 1, - "generated": "2026-11-14T10:53:39Z", + "generated": "2026-11-14T11:34:35Z", "repository": "https://gitcode.com/Morris_1/GC", "branch": "main", "modelDir": "model", @@ -9,24 +9,40 @@ "revision": "", "packages": { "win-x64": { - "path": "dist/GC-win-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-x64.zip" + "path": "dist/win-amd64/GC-1.0.7-win-amd64.zip", + "dir": "dist/win-amd64", + "name": "GC-1.0.7-win-amd64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip", + "sha256": "f90ff51ac6b041ae238cbeb4672622b0d029142a9d8b0705f08e654336512308", + "size": 46363183 }, "win-arm64": { - "path": "dist/GC-win-arm64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-arm64.zip" + "path": "dist/win-arm64/GC-1.0.7-win-arm64.zip", + "dir": "dist/win-arm64", + "name": "GC-1.0.7-win-arm64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip", + "sha256": "0b2bab2c3ac7e6223d8dd0b0faf9a0994319fa5ad13826addf7b402619b812e0", + "size": 44390354 }, "osx-arm64": { - "path": "dist/GC-osx-arm64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-arm64.zip" + "path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip", + "dir": "dist/mac-arm64", + "name": "GC-1.0.7-mac-arm64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip", + "sha256": "e5fd355bace68dc0794eb3e049cbef63c952a60a765ab3806adaf1199e1b09ab", + "size": 9178314 }, "osx-x64": { - "path": "dist/GC-osx-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-x64.zip" + "path": "dist/mac-x64/GC-1.0.7-mac-x64.zip", + "dir": "dist/mac-x64", + "name": "GC-1.0.7-mac-x64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip" }, "linux-x64": { - "path": "dist/GC-linux-x64.zip", - "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-linux-x64.zip" + "path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip", + "dir": "dist/linux-amd64", + "name": "GC-1.0.7-linux-amd64.zip", + "url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip" } } }, @@ -34,32 +50,54 @@ { "id": "contour-map", "version": "1.0", - "build": "d3eb662a36", + "build": "e4b3f2b87e", + "manifestSha256": "ee0897d46ee85126fbfd0d07f5ca3111950d0c36f9b8a80e4eb6ae85d226da4f", + "filesSha256": "b1f323fb41dec4f45992a30ff8726f3307f83b564127aff99bcb3d044c79d2bd", + "files": 5, "dir": "model/contour-map" }, { "id": "earth-geography", "version": "1.8", - "build": "d5ad961ed1", + "build": "3b645c45c2", + "manifestSha256": "a9f30fd4a1dd0aeccb88c892579c93bf32a92379d7b3f545b28f6cac612f9871", + "filesSha256": "0e55d2f9bacc3e0ff42f5c45d9e7c265864df9784b1609c09dcb32d21b4addfc", + "files": 11, "dir": "model/earth-geography" }, { "id": "earth-revolution", "version": "1.6", - "build": "287b1d86af", + "build": "947efa36bb", + "manifestSha256": "feb715cde8ad5da9ecfb48785a95e6fc82930cc92c668514b328915366c2f57a", + "filesSha256": "a37e0b493c78bb0a04a276512b612be3f8e7a178ed1a7fc72acb5353aa57f7c5", + "files": 7, "dir": "model/earth-revolution" }, { "id": "earth-rotation", "version": "1.6", - "build": "83124cb2ac", + "build": "a803d9c020", + "manifestSha256": "56ed397cbc008bd9ec8bea0ee34a94a28ab29ce39a8b096b0629e529883b4dff", + "filesSha256": "4e4428812d18d15a99105e73c027b99f3197033f0138d643ba69c15fabc9d8f6", + "files": 7, "dir": "model/earth-rotation" }, { "id": "scale-calculator", "version": "1.5", - "build": "b8930576fd", + "build": "02a555272a", + "manifestSha256": "d00034888d9b9da03338b7f394d1bdf33f73b1fbdd7e8f154d85b9080318ab13", + "filesSha256": "4a5fbf898df1d98eddf68b5d3929ae7b25cd7bcdfdfa36b5ad0ed72d9941d049", + "files": 6, "dir": "model/scale-calculator" } - ] + ], + "signature": { + "alg": "ECDSA-P256-SHA256", + "keyId": "gc-2026-11", + "value": "LHaF2bw+IZeWUw2qLQM1IQHoNXsHNko38dyjP45Jy41KtlyhvJhhFaNh+THKhAU+6jSzV1eFHgbwasboYBOa5w==", + "contentSha256": "749055593bf9839837428d900d523b3363486556970cbf4e2daa25001ab174c8", + "signedAt": "2026-11-14T11:36:03Z" + } }