8 Commits
154 changed files with 5628 additions and 1646 deletions

No files matched your search

+3
View File
@@ -1,6 +1,9 @@
# 运行数据目录(settings/model/cache/update),绝不入库 # 运行数据目录(settings/model/cache/update),绝不入库
.GC/ .GC/
# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里)
.signing/
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增) # .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
bin/ bin/
obj/ obj/
+29
View File
@@ -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` 全流程通过。
+5 -4
View File
@@ -1,8 +1,9 @@
<Project> <Project>
<!-- <!--
多目录结构公共属性: 多目录结构公共属性:
src/main/dotnet/<module> 生产代码 GC-BOOT 启动入口
src/test/dotnet/<module> 测试 / 离屏渲染校验 GC/src/ 启动器核心代码
GC/src/test/dotnet/<module> 测试 / 离屏渲染校验
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0 TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
--> -->
<PropertyGroup Condition="'$(TargetFramework)' == ''"> <PropertyGroup Condition="'$(TargetFramework)' == ''">
@@ -21,9 +22,9 @@
--> -->
<AvaloniaVersion>11.3.9</AvaloniaVersion> <AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion> <MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.6</Version> <Version>1.0.7</Version>
<Company>NeoRF</Company> <Company>NeoRF</Company>
<Product>Earth Model Studio</Product> <Product>GC</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage> <NeutralLanguage>zh-Hans</NeutralLanguage>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
+25
View File
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>GC.Boot</RootNamespace>
<AssemblyName>GC</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- 应用图标(Windows exe / 任务栏) -->
<ApplicationIcon>..\GC\src\Assets\icon.ico</ApplicationIcon>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
</ItemGroup>
</Project>
@@ -1,20 +1,22 @@
using System; using System;
using Avalonia; using Avalonia;
using EarthModelStudio.Services; using GC.Services;
using GC.Download;
namespace EarthModelStudio; namespace GC;
internal static class Program internal static class Program
{ {
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args)
{ {
DownloadModuleHost.Factory = new DownloadModuleFactory();
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/) // 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
var paths = AppPaths.Discover(); var paths = AppPaths.Discover();
paths.EnsureCreated(); paths.EnsureCreated();
// 上次下载的启动器新版,到这次启动才应用 // 上次下载的启动器新版,到这次启动才应用
if (LauncherUpdater.TryApplyPending(paths)) return; if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
} }
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" /> <assemblyIdentity version="1.0.0.0" name="GC.Desktop" />
<application xmlns="urn:schemas-microsoft-com:asm.v3"> <application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings> <windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
@@ -5,7 +5,7 @@ using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。 /// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
@@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote
{ {
private readonly string _root; private readonly string _root;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) }; private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
private string? _rawManifest;
private string _launcherVersion = "";
public DirectoryRemote(string root) => _root = Path.GetFullPath(root); 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 fallback = SafePath(Path.Combine("model", "version.json"));
var file = File.Exists(primary) ? primary : fallback; var file = File.Exists(primary) ? primary : fallback;
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null); if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
return Task.FromResult(Json.Read<RepoVersion>(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);
} }
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct) public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{ {
var baseDir = SafePath(rootPath ?? "model"); var baseDir = SafePath(rootPath ?? "model");
@@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct) public async Task<byte[]?> 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!); string full;
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct); 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; var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null; if (string.IsNullOrWhiteSpace(url)) return null;
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。 // 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
@@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote
return null; return null;
} }
/// <summary>在 dist/&lt;系统&gt;-&lt;架构&gt;/ 里找这个平台的启动器包;找不到返回 null。</summary>
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) private string SafePath(string relative)
{ {
var full = Path.GetFullPath(Path.Combine(_root, relative)); var full = Path.GetFullPath(Path.Combine(_root, relative));
@@ -5,21 +5,12 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
public enum DownloadState
{
Queued,
Running,
Completed,
Failed,
Canceled
}
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary> /// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
public sealed partial class DownloadJob : ObservableObject public sealed partial class DownloadJob : ObservableObject, IDownloadJob
{ {
public RemoteModel Model { get; } public RemoteModel Model { get; }
public string Id => Model.Id; public string Id => Model.Id;
@@ -66,13 +57,13 @@ public sealed partial class DownloadJob : ObservableObject
} }
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary> /// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
public sealed class DownloadCenter public sealed class DownloadCenter : IDownloadCenter
{ {
private readonly ModelRepository _repository; private readonly ModelRepository _repository;
private readonly AppPaths _paths; private readonly AppPaths _paths;
private readonly SemaphoreSlim _slots = new(2); private readonly SemaphoreSlim _slots = new(2);
public ObservableCollection<DownloadJob> Jobs { get; } = new(); public ObservableCollection<IDownloadJob> Jobs { get; } = new();
public event Action? Installed; public event Action? Installed;
public DownloadCenter(AppPaths paths, ModelRepository repository) public DownloadCenter(AppPaths paths, ModelRepository repository)
@@ -81,7 +72,7 @@ public sealed class DownloadCenter
_repository = repository; _repository = repository;
} }
public DownloadJob Enqueue(RemoteModel model) public IDownloadJob Enqueue(RemoteModel model)
{ {
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive); var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
if (running != null) return running; if (running != null) return running;
@@ -92,7 +83,7 @@ public sealed class DownloadCenter
return job; return job;
} }
private async Task RunAsync(DownloadJob job) private async Task RunAsync(IDownloadJob job)
{ {
// 在 UI 线程构造,回调自动回到 UI 线程 // 在 UI 线程构造,回调自动回到 UI 线程
var progress = new Progress<(long Done, long Total)>(p => var progress = new Progress<(long Done, long Total)>(p =>
@@ -135,20 +126,20 @@ public sealed class DownloadCenter
} }
} }
public void Cancel(DownloadJob job) public void Cancel(IDownloadJob job)
{ {
try { job.Cts.Cancel(); } catch { } try { job.Cts.Cancel(); } catch { }
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled; if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
} }
public void Retry(DownloadJob job) public void Retry(IDownloadJob job)
{ {
if (job.IsActive) return; if (job.IsActive) return;
Jobs.Remove(job); Jobs.Remove(job);
Enqueue(job.Model); Enqueue(job.Model);
} }
public void Remove(DownloadJob job) public void Remove(IDownloadJob job)
{ {
Cancel(job); Cancel(job);
Jobs.Remove(job); Jobs.Remove(job);
+50
View File
@@ -0,0 +1,50 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
using GC.Services;
namespace GC.Download;
public sealed class DownloadModuleFactory : IDownloadModuleFactory
{
public IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models) =>
new DownloadModule(paths, settings, models);
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
}
internal sealed class DownloadModule : IDownloadModule
{
public IDownloadCenter Downloads { get; }
public IModelSourceClient Sources { get; }
public IUpdateService Updates { get; }
public ISourceSelector Selector { get; }
public ILauncherUpdateService LauncherUpdates { get; }
public DownloadModule(AppPaths paths, SettingsService settings, ModelRepository models)
{
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, models);
Selector = new SourceSelector();
Updates = new UpdateService(paths, settings, UpdateService.CreateRemote(settings.Current));
LauncherUpdates = new LauncherUpdateService();
}
public IModelRemote CreateRemote(SourcePreset preset) => SourceSelector.CreateRemote(preset);
}
internal sealed class LauncherUpdateService : ILauncherUpdateService
{
public Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default) =>
LauncherUpdater.CheckAsync(remote, ct);
public Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default) =>
LauncherUpdater.DownloadAsync(paths, remote, progress, ct);
public bool ScheduleApply(AppPaths paths, string packageName) =>
LauncherUpdater.ScheduleApply(paths, packageName);
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
}
+14
View File
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>enable</Nullable>
<RootNamespace>GC.Download</RootNamespace>
<AssemblyName>GC.Download</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
</ItemGroup>
</Project>
@@ -5,7 +5,7 @@ using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。 /// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
@@ -32,7 +32,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
private static HttpClient CreateHttp() private static HttpClient CreateHttp()
{ {
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0"); client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
client.DefaultRequestHeaders.Accept.ParseAdd("application/json"); client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return client; return client;
} }
@@ -50,9 +50,9 @@ public sealed class GitCodeReleaseRemote : IModelRemote
{ {
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim(); var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri)) if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return ("2509_92447106", "GC"); return ("Morris_1", "GC");
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries); var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return ("2509_92447106", "GC"); if (parts.Length < 2) return ("Morris_1", "GC");
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase) var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1]; ? parts[1][..^4] : parts[1];
return (parts[0], repo); return (parts[0], repo);
@@ -86,13 +86,19 @@ public sealed class GitCodeReleaseRemote : IModelRemote
if (!gotRelease) if (!gotRelease)
{ {
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器), // 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256,
// 但模型清单仍然有效,保证模型能正常同步。 // 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)"); // 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。
if (version != null) var v = (version?.Launcher.Version ?? "").Trim();
var n = version?.Launcher.Packages.Count ?? 0;
if (v.Length == 0 || n == 0)
{ {
version.Launcher.Version = ""; Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
version.Launcher.Packages.Clear(); }
else
{
Console.WriteLine(
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
} }
} }
return version; return version;
@@ -120,6 +126,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false; if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
version.Launcher.Version = latest.Version; version.Launcher.Version = latest.Version;
_content.SetLauncherVersion(latest.Version);
_assets.Clear(); _assets.Clear();
foreach (var asset in latest.Assets) foreach (var asset in latest.Assets)
@@ -2,23 +2,24 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository /// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或 /// (https://gitcode.com/Morris_1/GC),可改成任意 gitcode 仓库或
/// https://gitcode.com/&lt;owner&gt;/&lt;repo&gt;/tree/&lt;branch&gt;/model 这样的地址。 /// https://gitcode.com/&lt;owner&gt;/&lt;repo&gt;/tree/&lt;branch&gt;/model 这样的地址。
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 }; /// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
/// 文件项自带 download_url(raw.gitcode.com/blobs/&lt;sha&gt;/...),可直接下载二进制。 /// 文件项自带 download_url(raw.gitcode.com/blobs/&lt;sha&gt;/...),可直接下载二进制。
/// </summary> /// </summary>
public sealed class GitCodeRemote : IModelRemote public sealed class GitCodeRemote : IModelRemote
{ {
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC"; public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
private readonly HttpClient _http; private readonly HttpClient _http;
private readonly string _api; private readonly string _api;
@@ -27,6 +28,9 @@ public sealed class GitCodeRemote : IModelRemote
private readonly string? _fallbackUrl; private readonly string? _fallbackUrl;
private readonly string _displayName; private readonly string _displayName;
private string _modelDir = "model"; private string _modelDir = "model";
private string? _rawManifest;
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
private string _launcherVersion = "";
public string DisplayName => _displayName; public string DisplayName => _displayName;
@@ -39,7 +43,7 @@ public sealed class GitCodeRemote : IModelRemote
? DefaultRepository : repository!.TrimEnd('/'); ? DefaultRepository : repository!.TrimEnd('/');
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) }; _http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0"); _http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json"); _http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
if (string.IsNullOrWhiteSpace(manifestUrl)) if (string.IsNullOrWhiteSpace(manifestUrl))
@@ -59,9 +63,9 @@ public sealed class GitCodeRemote : IModelRemote
{ {
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim(); var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri)) if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return ("2509_92447106", "GC", "main"); return ("Morris_1", "GC", "main");
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries); var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return ("2509_92447106", "GC", "main"); if (parts.Length < 2) return ("Morris_1", "GC", "main");
var owner = parts[0]; var owner = parts[0];
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase) var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1]; ? parts[1][..^4] : parts[1];
@@ -77,9 +81,24 @@ public sealed class GitCodeRemote : IModelRemote
version = await ReadVersionFromAsync(_fallbackUrl, ct); version = await ReadVersionFromAsync(_fallbackUrl, ct);
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir)) if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
_modelDir = version.ModelDir.Trim('/'); _modelDir = version.ModelDir.Trim('/');
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
_launcherVersion = version.Launcher.Version.Trim();
return version; return version;
} }
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
/// <summary>
/// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是
/// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。
/// </summary>
internal void SetLauncherVersion(string? version)
{
if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim();
}
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct) private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
{ {
string text; string text;
@@ -107,10 +126,20 @@ public sealed class GitCodeRemote : IModelRemote
payload = Encoding.UTF8.GetString(raw); payload = Encoding.UTF8.GetString(raw);
} }
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null; if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
payload, EarthModelStudio.Services.Json.Options); // 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
var version = ManifestLoader.Parse(payload, out var verification);
if (version == null) return null;
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单 // 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) catch (Exception ex)
{ {
@@ -283,25 +312,129 @@ public sealed class GitCodeRemote : IModelRemote
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct) public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{ {
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim(); // 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
if (url == null && !string.IsNullOrWhiteSpace(package.Path)) 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);
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch; if (bytes != null) return bytes;
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();
} }
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;
}
/// <summary>下载一个候选地址;<paramref name="sha256"/> 非空时必须与内容一致。</summary>
private async Task<byte[]?> 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) catch (Exception ex)
{ {
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}"); 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))
{
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
return null; 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..];
/// <summary>把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。</summary>
private async Task<string?> 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 / 网络问题都当作「这个路径没有」
}
}
/// <summary>
/// 在 <paramref name="dir"/> 里找启动器包。
/// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则),
/// 最终仍由 sha256 兜底。
/// </summary>
private async Task<string?> 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) private static string Str(JsonElement item, string name)
@@ -6,7 +6,7 @@ using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。 /// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
@@ -23,11 +23,12 @@ public sealed class GiteaRemote : IModelRemote
{ {
private readonly SourcePreset _preset; private readonly SourcePreset _preset;
private static readonly HttpClient Http = CreateHttp(); private static readonly HttpClient Http = CreateHttp();
private string? _rawManifest;
private static HttpClient CreateHttp() private static HttpClient CreateHttp()
{ {
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0"); c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json"); c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c; return c;
} }
@@ -69,7 +70,18 @@ public sealed class GiteaRemote : IModelRemote
// Release 提供启动器版本与平台附件 // Release 提供启动器版本与平台附件
result.Launcher.Version = fromRelease.Launcher.Version; result.Launcher.Version = fromRelease.Launcher.Version;
foreach (var kv in fromRelease.Launcher.Packages) 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; result.Launcher.Packages[kv.Key] = kv.Value;
}
return result; return result;
} }
@@ -81,6 +93,10 @@ public sealed class GiteaRemote : IModelRemote
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级 // 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
return result.Models.Count > 0 ? result : null; return result.Models.Count > 0 ? result : null;
} }
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary> /// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct) private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
{ {
@@ -90,8 +106,14 @@ public sealed class GiteaRemote : IModelRemote
{ {
var text = await Http.GetStringAsync(url, ct); var text = await Http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options); var doc = ManifestLoader.Parse(text, out var verification);
if (doc != null) return doc; if (verification.Trust == ManifestTrust.Invalid)
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
if (doc != null)
{
_rawManifest = text;
return doc;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -282,12 +304,35 @@ public sealed class GiteaRemote : IModelRemote
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct) public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{ {
if (string.IsNullOrWhiteSpace(package.Url)) return null; // 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
try { return await Http.GetByteArrayAsync(package.Url, ct); } // 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
catch (Exception ex) var candidates = new List<string>();
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}"); 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; return null;
} }
} }
}
+119
View File
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
namespace GC.Services;
/// <summary>
/// 平台标签与「仓库里的编译产物位置」的推导规则。
///
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
/// 提交(或上传)到仓库的 <c>dist/&lt;系统&gt;-&lt;架构&gt;</c> 目录,例如
/// <c>dist/mac-arm64/GC-1.0.7-mac-arm64.zip</c>,根本没有发 Release。
/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。
///
/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的
/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单,
/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。
///
/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译,
/// 保证「写进清单的路径」与「运行时找的路径」永远一致。
/// </summary>
public static class LauncherArtifacts
{
/// <summary>
/// RID → 文件名里的「系统-架构」标签(与 <c>LauncherUpdater.PlatformLabel</c> 一致)。
/// </summary>
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
};
/// <summary>
/// 同一平台在仓库里可能用的目录名(按优先级)。
/// 既接受 <c>mac-arm64</c> 这种标签,也接受 <c>osx-arm64</c> 这种 RID,
/// 因为 dist 目录名历史上两种写法都出现过。
/// </summary>
public static IReadOnlyList<string> PlatformAliases(string rid)
{
var label = LabelOf(rid);
if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase))
return new[] { rid };
return new[] { label, rid };
}
/// <summary>启动器包应有的文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>。</summary>
public static string PackageFileName(string version, string rid)
=> $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
/// <summary>
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
/// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。
/// </summary>
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);
}
/// <summary>
/// 候选目录:清单显式给的 dir 优先,其次是 <c>dist/&lt;标签&gt;</c> 与 <c>dist/&lt;RID&gt;</c>。
/// </summary>
public static IReadOnlyList<string> CandidateDirs(string rid, string? declaredDir)
{
var dirs = new List<string>();
if (!string.IsNullOrWhiteSpace(declaredDir))
dirs.Add(declaredDir!.Trim().Trim('/'));
foreach (var alias in PlatformAliases(rid))
dirs.Add("dist/" + alias);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<string>();
foreach (var dir in dirs)
if (dir.Length > 0 && seen.Add(dir)) result.Add(dir);
return result;
}
/// <summary>
/// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。
/// </summary>
public static IReadOnlyList<string> CandidateFiles(string rid, string? declaredDir,
string? declaredPath, string? declaredName, string version)
{
var files = new List<string>();
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<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<string>();
foreach (var file in files)
if (file.Length > 0 && seen.Add(file)) result.Add(file);
return result;
}
}
@@ -7,7 +7,7 @@ using System.Security.Cryptography;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
// =========================================================================== // ===========================================================================
// 启动器更新模块(唯一实现) // 启动器更新模块(唯一实现)
@@ -23,31 +23,14 @@ namespace EarthModelStudio.Services;
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径 // · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
// =========================================================================== // ===========================================================================
public sealed class UpdateProgressInfo
{
public double Value { get; init; }
public string Stage { get; init; } = "";
}
public enum UpdateRunState { UpToDate, Ready, Failed }
public sealed class UpdateRunResult
{
public UpdateRunState State { get; init; }
public string Version { get; init; } = "";
public string Message { get; init; } = "";
public string? PackageName { get; init; }
public string? NewAppPath { get; init; }
}
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary> /// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
public static class LauncherUpdater public static class LauncherUpdater
{ {
/// <summary>当前运行程序的版本号(来自程序集)。</summary> /// <summary>当前运行程序的版本号(来自程序集)。</summary>
public static string RunningVersion => UpdateService.CurrentLauncherVersion; public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前 RID,如 osx-arm64。</summary> /// <summary>当前 RID,如 osx-arm64。</summary>
public static string CurrentRid => UpdateService.CurrentRid; public static string CurrentRid => LauncherRuntimeInfo.CurrentRid;
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary> /// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
public static string PlatformLabel => CurrentRid switch public static string PlatformLabel => CurrentRid switch
@@ -211,14 +194,14 @@ public static class LauncherUpdater
{ {
using var ms = new MemoryStream(zip); using var ms = new MemoryStream(zip);
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read); using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
// 找主程序:app 内的可执行文件 / EarthModelStudio.dll / 单文件 exe // 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
var entry = archive.Entries.FirstOrDefault(e => var entry = archive.Entries.FirstOrDefault(e =>
e.Name.Equals("EarthModelStudio.dll", StringComparison.OrdinalIgnoreCase)) e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e => ?? archive.Entries.FirstOrDefault(e =>
e.Name.Equals("EarthModelStudio", StringComparison.OrdinalIgnoreCase)) e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e => ?? archive.Entries.FirstOrDefault(e =>
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
e.Name.StartsWith("EarthModelStudio", StringComparison.OrdinalIgnoreCase)); e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
if (entry == null) return null; if (entry == null) return null;
await using var es = entry.Open(); await using var es = entry.Open();
@@ -320,46 +303,120 @@ public static class LauncherUpdater
!version.Launcher.Packages.TryGetValue("default", out pkg)) !version.Launcher.Packages.TryGetValue("default", out pkg))
return Fail($"该平台({rid})没有对应发布包"); 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}" }); progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
var bytes = await remote.DownloadPackageAsync(pkg!, ct); var bytes = await remote.DownloadPackageAsync(pkg!, ct);
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空"); if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
// sha256 校验(Release 提供时) // sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义)
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
{ {
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase)) 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 updateRoot = paths.UpdateRoot;
Directory.CreateDirectory(updateRoot);
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
// 避免「解压后被替换」的中间窗口。
var zip = Path.Combine(updateRoot, "package.zip");
if (File.Exists(zip)) File.Delete(zip);
await File.WriteAllBytesAsync(zip, bytes, ct);
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);
}
// 二次验签用的清单副本: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);
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
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 installDir = paths.InstallDirectory;
Directory.CreateDirectory(installDir);
var staging = Path.Combine(paths.CacheRoot, "launcher-staging"); var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
if (Directory.Exists(staging)) Directory.Delete(staging, true); if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging); Directory.CreateDirectory(staging);
SafeArchive.ExtractToDirectory(zip, staging);
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try { ZipSafety.ExtractToDirectory(zip, staging); }
finally { try { File.Delete(zip); } catch { } }
// 只展平「单个非 .app 顶层目录」的 zip
FlattenStaging(staging); FlattenStaging(staging);
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" }); var payload = Path.Combine(updateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true);
var packageName = MoveToInstallDir(staging, installDir, latest); Directory.CreateDirectory(payload);
var legacyName = MoveToPayload(staging, payload);
try { Directory.Delete(staging, true); } catch { } try { Directory.Delete(staging, true); } catch { }
if (packageName == null) return Fail("解压结果里没有找到新版启动器"); if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径 packageName = legacyName;
Directory.CreateDirectory(paths.UpdateRoot); request.PackageName = legacyName;
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"), Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n"); 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 = "下载完成" }); progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
@@ -367,9 +424,9 @@ public static class LauncherUpdater
{ {
State = UpdateRunState.Ready, State = UpdateRunState.Ready,
Version = latest, Version = latest,
Message = $"v{latest} 已下载到当前目录", Message = $"v{latest} 已暂存到 .GC/update",
PackageName = packageName, PackageName = packageName,
NewAppPath = Path.Combine(installDir, packageName) NewAppPath = legacyPath
}; };
} }
catch (OperationCanceledException) { return Fail("已取消"); } catch (OperationCanceledException) { return Fail("已取消"); }
@@ -385,22 +442,31 @@ public static class LauncherUpdater
// ---------------------------------------------------------------- 应用(下次启动) // ---------------------------------------------------------------- 应用(下次启动)
/// <summary> /// <summary>
/// 生成替换脚本并启动。脚本等本进程退出后: /// 安排应用已下载的新版。
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。 /// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
/// 返回 true 表示调用方应立即退出进程。 /// 返回 true 表示调用方应立即退出进程。
/// </summary> /// </summary>
public static bool ScheduleApply(AppPaths paths, string packageName) 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, "EarthModelStudio.sln"))) if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
{ {
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换"); Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
return false; 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 try
{ {
var isWin = OperatingSystem.IsWindows(); var isWin = OperatingSystem.IsWindows();
@@ -435,20 +501,37 @@ public static class LauncherUpdater
} }
} }
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary> /// <summary>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</summary>
public static bool TryApplyPending(AppPaths paths) public static bool TryApplyPending(AppPaths paths)
{ {
if (paths.IsDevelopment) return false; if (paths.IsDevelopment) return false;
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false; if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "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<SavedogRequest>(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"); var marker = Path.Combine(paths.UpdateRoot, "update.txt");
if (!File.Exists(marker)) return false; if (!File.Exists(marker)) return false;
var name = ReadMarker(marker, "NAME"); var name = ReadMarker(marker, "NAME");
if (string.IsNullOrWhiteSpace(name)) return false; if (string.IsNullOrWhiteSpace(name)) return false;
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) && var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!))) if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
return false; // 新版本不在了,放弃 return false; // 新版本不在了,放弃
return ScheduleApply(paths, name!); return ScheduleApply(paths, name!);
@@ -460,27 +543,33 @@ public static class LauncherUpdater
{ {
var s = new System.Text.StringBuilder(); var s = new System.Text.StringBuilder();
s.AppendLine("#!/bin/sh"); s.AppendLine("#!/bin/sh");
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up"); s.AppendLine("# script lives in .GC/update/ ; install path is recorded relatively");
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)"); s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
s.AppendLine("MARKER=\"$HERE/update.txt\""); s.AppendLine("MARKER=\"$HERE/update.txt\"");
s.AppendLine(); s.AppendLine();
s.AppendLine("# read marker"); s.AppendLine("# read marker");
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)"); s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)"); s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)"); s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then"); s.AppendLine("INSTALLREL=$(sed -n 's/^INSTALL_REL=//p' \"$MARKER\" 2>/dev/null | head -1)");
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ] || [ -z \"$INSTALLREL\" ]; then");
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1"); s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi"); s.AppendLine("fi");
s.AppendLine("NEW=\"$DST/$NEWNAME\""); s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/$INSTALLREL\" && pwd)");
s.AppendLine("if [ ! -e \"$NEW\" ]; then"); s.AppendLine("PAYLOAD=\"$HERE/payload/$NEWNAME\"");
s.AppendLine("if [ ! -e \"$PAYLOAD\" ]; then");
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1"); s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
s.AppendLine("fi"); s.AppendLine("fi");
s.AppendLine(); s.AppendLine();
s.AppendLine("# wait for old process to exit (this script is started by it)"); s.AppendLine("# wait for old process to exit (this script is started by it)");
s.AppendLine("sleep 2"); s.AppendLine("sleep 2");
s.AppendLine(); s.AppendLine();
s.AppendLine("# launch new version first"); s.AppendLine("# move the staged package into the install directory");
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
s.AppendLine("rm -rf \"$NEW\"");
s.AppendLine("mv \"$PAYLOAD\" \"$NEW\"");
s.AppendLine();
s.AppendLine("# launch new version");
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &"); s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &"); s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
s.AppendLine("fi"); s.AppendLine("fi");
@@ -522,18 +611,28 @@ public static class LauncherUpdater
s.AppendLine("@echo off"); s.AppendLine("@echo off");
s.AppendLine("chcp 65001 >nul 2>&1"); s.AppendLine("chcp 65001 >nul 2>&1");
s.AppendLine("set \"HERE=%~dp0\""); s.AppendLine("set \"HERE=%~dp0\"");
s.AppendLine("set \"DST=%~dp0..\\..\"");
s.AppendLine("set \"MARKER=%~dp0update.txt\""); s.AppendLine("set \"MARKER=%~dp0update.txt\"");
s.AppendLine("timeout /t 2 /nobreak >nul"); s.AppendLine("timeout /t 2 /nobreak >nul");
s.AppendLine(); s.AppendLine();
s.AppendLine("set \"NEWNAME=\""); s.AppendLine("set \"NEWNAME=\"");
s.AppendLine("set \"NEWVER=\""); s.AppendLine("set \"NEWVER=\"");
s.AppendLine("set \"NEWPLAT=\""); s.AppendLine("set \"NEWPLAT=\"");
s.AppendLine("set \"INSTALLREL=\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\""); s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\""); s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\""); s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"INSTALL_REL=\" \"%MARKER%\" 2^>nul') do set \"INSTALLREL=%%A\"");
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)"); s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)"); s.AppendLine("if \"%INSTALLREL%\"==\"\" (echo install path missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine("for %%I in (\"%HERE%%INSTALLREL%\") do set \"DST=%%~fI\"");
s.AppendLine("set \"PAYLOAD=%HERE%payload\\%NEWNAME%\"");
s.AppendLine("if not exist \"%PAYLOAD%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
s.AppendLine();
s.AppendLine("rem move the staged package into the install directory");
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" rmdir /S /Q \"%DST%\\%NEWNAME%\" 2>nul");
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" del /Q \"%DST%\\%NEWNAME%\" 2>nul");
s.AppendLine("move \"%PAYLOAD%\" \"%DST%\\%NEWNAME%\" >nul");
s.AppendLine("if errorlevel 1 (echo failed to install update & exit /b 1)");
s.AppendLine(); s.AppendLine();
s.AppendLine("rem launch new version"); s.AppendLine("rem launch new version");
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\""); s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
@@ -574,10 +673,10 @@ public static class LauncherUpdater
} }
/// <summary> /// <summary>
/// 把 staging 里的新版搬到当前目录,与旧版并列。 /// 把 staging 里的新版搬入下载目录的 payload。
/// 返回新版包名(GC-&lt;版本&gt;-&lt;平台&gt;.app/.exe)。.GC 绝不覆盖。 /// 返回新版包名(GC-&lt;版本&gt;-&lt;平台&gt;.app/.exe)。
/// </summary> /// </summary>
private static string? MoveToInstallDir(string staging, string installDir, string latest) private static string? MoveToPayload(string staging, string payload)
{ {
try try
{ {
@@ -585,7 +684,7 @@ public static class LauncherUpdater
{ {
var name = Path.GetFileName(entry); var name = Path.GetFileName(entry);
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue; if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
var dest = Path.Combine(installDir, name); var dest = Path.Combine(payload, name);
if (Directory.Exists(dest)) Directory.Delete(dest, true); if (Directory.Exists(dest)) Directory.Delete(dest, true);
else if (File.Exists(dest)) File.Delete(dest); else if (File.Exists(dest)) File.Delete(dest);
@@ -2,9 +2,9 @@ using System;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
public static class ModelInstaller public static class ModelInstaller
{ {
@@ -7,16 +7,16 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 从链接导入模型源。 /// 从链接导入模型源。
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。 /// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/&lt;id&gt;。 /// 仓库里的 model/ 目录就是模型列表;下载后缓存在应用缓存目录。
/// </summary> /// </summary>
public sealed class ModelSourceClient public sealed class ModelSourceClient : IModelSourceClient
{ {
private readonly AppPaths _paths; private readonly AppPaths _paths;
private static readonly HttpClient Http = CreateHttp(); private static readonly HttpClient Http = CreateHttp();
@@ -26,7 +26,7 @@ public sealed class ModelSourceClient
private static HttpClient CreateHttp() private static HttpClient CreateHttp()
{ {
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)"); client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
return client; return client;
} }
+121
View File
@@ -0,0 +1,121 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace GC.Services;
/// <summary>
/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。
///
/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败,
/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序,
/// 风险面被压缩到最小,也便于审计。
/// </summary>
public static class SavedogLauncher
{
/// <summary>在安装目录里寻找 SAVEDOG 可执行文件。</summary>
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;
}
/// <summary>
/// 启动 SAVEDOG 应用更新。<paramref name="waitForPid"/> 是当前启动器进程,
/// SAVEDOG 会等它退出后再动文件。
/// </summary>
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;
}
}
/// <summary>读取 SAVEDOG 最近一次的执行结果(供界面展示)。</summary>
public static SavedogState? ReadState(AppPaths paths)
=> Json.Read<SavedogState>(Path.Combine(paths.UpdateRoot, SavedogFiles.State));
/// <summary>上次成功启动的版本(回滚依据)。</summary>
public static LastGoodVersion? ReadLastGood(AppPaths paths)
=> Json.Read<LastGoodVersion>(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood));
}
@@ -6,7 +6,7 @@ using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。 /// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
@@ -15,14 +15,14 @@ namespace EarthModelStudio.Services;
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间, /// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
/// 避免每次点下载都重新测速。 /// 避免每次点下载都重新测速。
/// </summary> /// </summary>
public sealed class SourceSelector public sealed class SourceSelector : ISourceSelector
{ {
private static readonly HttpClient Http = CreateHttp(); private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp() private static HttpClient CreateHttp()
{ {
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) }; var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Probe/1.0"); c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
return c; return c;
} }
@@ -8,16 +8,16 @@ using System.Runtime.InteropServices;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换 /// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
/// .GC/model/&lt;id&gt;,本次启动立即生效。任何失败都保留本地已装模型。 /// .GC/model/&lt;id&gt;,本次启动立即生效。任何失败都保留本地已装模型。
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。 /// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
/// </summary> /// </summary>
public sealed class UpdateService public sealed class UpdateService : IUpdateService
{ {
private readonly AppPaths _paths; private readonly AppPaths _paths;
private readonly SettingsService _settings; private readonly SettingsService _settings;
@@ -35,55 +35,6 @@ public sealed class UpdateService
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary> /// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
public void UseRemote(IModelRemote remote) => _remote = remote; public void UseRemote(IModelRemote remote) => _remote = remote;
private static string? _versionOverride;
public static string CurrentLauncherVersion
{
get
{
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
var asm = typeof(UpdateService).Assembly;
var v = asm.GetName().Version;
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
{
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(info))
{
var core = info!.Split('+')[0].Trim();
if (Version.TryParse(core, out var iv))
v = iv;
}
}
if (v == null) return "0.0.0";
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
}
}
/// <summary>测试 / 自检时临时指定版本号。</summary>
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
public static string CurrentRid
{
get
{
var arch = RuntimeInformation.OSArchitecture switch
{
Architecture.Arm64 => "arm64",
Architecture.X86 => "x86",
_ => "x64"
};
if (OperatingSystem.IsWindows()) return "win-" + arch;
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
if (OperatingSystem.IsLinux()) return "linux-" + arch;
return RuntimeInformation.RuntimeIdentifier;
}
}
/// <summary> /// <summary>
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。 /// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。 /// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
@@ -153,6 +104,37 @@ public sealed class UpdateService
Message = L.I["update.noManifest"] 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.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
_settings.Save(); _settings.Save();
@@ -297,6 +279,22 @@ public sealed class UpdateService
await Task.WhenAll(tasks); 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); Directory.CreateDirectory(_paths.ModelRoot);
var target = Path.Combine(_paths.ModelRoot, model.Id); var target = Path.Combine(_paths.ModelRoot, model.Id);
@@ -319,6 +317,25 @@ public sealed class UpdateService
{ {
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ } 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 catch
{ {
@@ -332,4 +349,7 @@ public sealed class UpdateService
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-'); foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-'); return value.Replace('/', '-').Replace(' ', '-');
} }
private static string Short(string? hash)
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
} }
@@ -1,7 +1,7 @@
using System; using System;
using System.Globalization; using System.Globalization;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法, /// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.IO;
namespace GC.Services;
/// <summary>
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
/// </summary>
public static class ZipSafety
{
public static void ExtractToDirectory(string zipPath, string destination)
{
if (!File.Exists(zipPath))
throw new FileNotFoundException("压缩包不存在", zipPath);
SafeArchive.ExtractToDirectory(zipPath, destination);
}
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
}
@@ -1,19 +1,22 @@
using System; using System;
using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using Avalonia; using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Layout; using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Shapes = Avalonia.Controls.Shapes; using Shapes = Avalonia.Controls.Shapes;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.Views; namespace GC.Views;
/// <summary> /// <summary>
/// 模型窗口:**只做窗口宿主**。 /// 模型窗口:**只做窗口宿主**。
@@ -23,6 +26,7 @@ namespace EarthModelStudio.Views;
public sealed class PlayerWindow : Window public sealed class PlayerWindow : Window
{ {
private LoadedModel? _model; private LoadedModel? _model;
private bool _closing;
private Button? _maximizeButton; private Button? _maximizeButton;
private Border? _frame; private Border? _frame;
private TextBlock? _titleText; private TextBlock? _titleText;
@@ -167,7 +171,7 @@ public sealed class PlayerWindow : Window
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized; minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
maximizeButton.Click += (_, _) => ToggleMaximize(); maximizeButton.Click += (_, _) => ToggleMaximize();
closeButton.Click += (_, _) => Close(); closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
_maximizeGlyph = maxBadge.Icon; _maximizeGlyph = maxBadge.Icon;
_restoreGlyph = maxBadge.Icon; _restoreGlyph = maxBadge.Icon;
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4"; _maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
@@ -394,37 +398,23 @@ public sealed class PlayerWindow : Window
} }
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ── // ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
// 关闭键也用品红卡通圆底 + 矢量 ✕:文字符号在中文字体下常被裁切或基线偏移 // 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
var helpBadgeShape = new Shapes.Ellipse
{
Width = 18, Height = 18,
Fill = new SolidColorBrush(Color.Parse("#FF7B7B")),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var helpCross = new Shapes.Path var helpCross = new Shapes.Path
{ {
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"), Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
Stroke = new SolidColorBrush(Color.Parse("#7A1F1F")), Stroke = new SolidColorBrush(btnText),
StrokeThickness = 1.7, StrokeThickness = 1.5,
StrokeLineCap = PenLineCap.Round, StrokeLineCap = PenLineCap.Round,
Fill = null, Fill = null,
Stretch = Stretch.None, Stretch = Stretch.None,
Width = 9, Height = 9, Width = 10, Height = 10,
HorizontalAlignment = HorizontalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center VerticalAlignment = VerticalAlignment.Center
}; };
var helpCrossLayer = new Grid
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
helpCrossLayer.Children.Add(helpBadgeShape);
helpCrossLayer.Children.Add(helpCross);
var helpClose = new Button var helpClose = new Button
{ {
Content = helpCrossLayer, Content = helpCross,
Width = 34, Width = 34,
Height = 26, Height = 26,
Background = Brushes.Transparent, Background = Brushes.Transparent,
@@ -438,14 +428,14 @@ public sealed class PlayerWindow : Window
}; };
helpClose.PointerEntered += (_, _) => helpClose.PointerEntered += (_, _) =>
{ {
helpBadgeShape.Fill = new SolidColorBrush(Color.Parse("#FF9B9B"));
helpClose.Background = new SolidColorBrush(IsLight(frameBg) helpClose.Background = new SolidColorBrush(IsLight(frameBg)
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46")); ? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
helpCross.Stroke = new SolidColorBrush(Colors.White);
}; };
helpClose.PointerExited += (_, _) => helpClose.PointerExited += (_, _) =>
{ {
helpBadgeShape.Fill = new SolidColorBrush(Color.Parse("#FF7B7B"));
helpClose.Background = Brushes.Transparent; helpClose.Background = Brushes.Transparent;
helpCross.Stroke = new SolidColorBrush(btnText);
}; };
var helpTitle = new TextBlock var helpTitle = new TextBlock
@@ -555,7 +545,7 @@ public sealed class PlayerWindow : Window
switch (e.Key) switch (e.Key)
{ {
case Key.Escape: case Key.Escape:
Close(); _ = CloseWithAnimationAsync();
e.Handled = true; e.Handled = true;
break; break;
case Key.F11: case Key.F11:
@@ -567,6 +557,30 @@ public sealed class PlayerWindow : Window
} }
} }
/// <summary>
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
/// 与主窗口的关闭动画保持同一节奏(180ms)。
/// </summary>
private async Task CloseWithAnimationAsync()
{
if (_closing) return;
_closing = true;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(180),
Easing = new CubicEaseIn()
}
};
Opacity = 0;
await Task.Delay(190);
Close();
}
private void OnClosed(object? sender, EventArgs e) private void OnClosed(object? sender, EventArgs e)
{ {
Content = null; Content = null;
+552
View File
@@ -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; }
}
/// <summary>
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
/// </summary>
internal sealed class Applier
{
private static readonly Regex ArtifactPattern = new(
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(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<SavedogRequest>(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<string>();
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<string>();
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<LastGoodVersion>(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 { }
}
}
+47
View File
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
GC-SAVEDOG —— 启动器更新守护进程。
为什么不把替换逻辑留在启动器里:
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
安全原语,保证「校验逻辑与启动器完全同一份实现」。
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<RootNamespace>GC.Savedog</RootNamespace>
<AssemblyName>GC-SAVEDOG</AssemblyName>
<InvariantGlobalization>true</InvariantGlobalization>
<!--
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
会覆盖到。
-->
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>full</TrimMode>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
</ItemGroup>
</Project>
+34
View File
@@ -0,0 +1,34 @@
using System;
using System.IO;
namespace GC.Savedog;
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
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 { /* 日志失败不能影响更新 */ }
}
}
+347
View File
@@ -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;
/// <summary>
/// GC-SAVEDOG 命令行。
///
/// GC-SAVEDOG apply --update &lt;.GC/update&gt; [--install &lt;dir&gt;] [--wait-pid N]
/// [--timeout 45] [--dry-run] [--json]
/// GC-SAVEDOG verify --manifest &lt;version.json&gt; [--require 1] [--json]
/// GC-SAVEDOG verify-model --dir &lt;model/&lt;id&gt;&gt; --id &lt;id&gt; [--json]
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
/// GC-SAVEDOG sign --manifest &lt;version.json&gt; [--key .signing/gc-signing.pem]
/// [--key-id ...] [--out &lt;file&gt;]
/// GC-SAVEDOG status --update &lt;.GC/update&gt; [--json]
/// </summary>
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<string, string> 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<SavedogRequest>(
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<SavedogState>(
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
Console.WriteLine(Json.Serialize(state));
}
}
return code;
}
// ------------------------------------------------------------------ verify
private static int Verify(Dictionary<string, string> options)
{
var manifest = Option(options, "manifest", "");
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
{
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
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<string, string> options)
{
var dir = Option(options, "dir", "");
var id = Option(options, "id", "");
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
{
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --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<string, string> 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<string, string> 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 <version.json>");
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<string, string> options)
{
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
var lastGood = Json.Read<LastGoodVersion>(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 <dir>] [--wait-pid N]
[--timeout 45] [--dry-run] [--force] [--json]
verify --manifest <version.json> [--require 1] [--json]
verify-model --dir <model/ID> --id <ID> [--json]
keygen [--out .signing] [--key-id gc-2026-11]
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
status --update <.GC/update> [--json]
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
""");
}
// ------------------------------------------------------------------ 参数
private static Dictionary<string, string> Parse(string[] args)
{
var map = new Dictionary<string, string>(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<string, string> options, string name, string? fallback)
=> options.TryGetValue(name, out var value) ? value : fallback;
private static int Int(Dictionary<string, string> options, string name, int fallback)
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
? parsed : fallback;
private static bool Flag(Dictionary<string, string> options, string name)
=> options.TryGetValue(name, out var value) &&
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
}
+79
View File
@@ -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;
/// <summary>
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
/// 编译期生成类型信息,运行时零反射。
///
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
/// </summary>
[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 排查。
}
/// <summary><c>verify --json</c> 的输出。</summary>
internal sealed class VerifyReport
{
public string Trust { get; set; } = "";
public string? KeyId { get; set; }
public string? Error { get; set; }
public List<TrustedKey> TrustedKeys { get; set; } = new();
}
internal sealed class TrustedKey
{
public string KeyId { get; set; } = "";
public string Fingerprint { get; set; } = "";
}
/// <summary><c>status --json</c> 的输出。</summary>
internal sealed class StatusReport
{
public SavedogState? State { get; set; }
public LastGoodVersion? LastGood { get; set; }
public StartupHealth.HealthRecord? Health { get; set; }
}
/// <summary><c>verify-model --json</c> 的输出。</summary>
internal sealed class VerifyModelReport
{
public bool Ok { get; set; }
public bool Present { get; set; }
public string Message { get; set; } = "";
}
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
internal static class SavedogJson
{
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
public static void Initialize()
{
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
}
}
+55 -13
View File
@@ -3,23 +3,21 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59 VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-BOOT", "GC-BOOT", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-DOWNLOAD", "GC-DOWNLOAD", "{BCA2AA3E-F98F-43A1-9D31-239103C303F7}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-BOOT", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Tests", "GC\src\test\dotnet\GC.Tests\GC.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.ModelSdk", "model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
EndProject EndProject
@@ -35,6 +33,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.csproj", "{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7D14-0C76-0B88-84F29EAA96CD}"
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 Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -105,15 +111,48 @@ Global
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU {6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.ActiveCfg = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.Build.0 = Debug|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.Build.0 = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.ActiveCfg = Release|Any CPU
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.Build.0 = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.ActiveCfg = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.Build.0 = Debug|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.Build.0 = Release|Any CPU
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.ActiveCfg = Release|Any CPU
{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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771}
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22}
{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} {09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B} {D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4} {C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
@@ -123,5 +162,8 @@ Global
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE} {0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C} {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB} {6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
@@ -1,8 +1,8 @@
<Application xmlns="https://github.com/avaloniaui" <Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:EarthModelStudio.ViewModels" xmlns:vm="using:GC.ViewModels"
xmlns:views="using:EarthModelStudio.Views" xmlns:views="using:GC.Views"
x:Class="EarthModelStudio.App" x:Class="GC.App"
RequestedThemeVariant="Light"> RequestedThemeVariant="Light">
<Application.DataTemplates> <Application.DataTemplates>
@@ -43,6 +43,6 @@
<Application.Styles> <Application.Styles>
<FluentTheme /> <FluentTheme />
<StyleInclude Source="avares://EarthModelStudio/Styles/AppTheme.axaml" /> <StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
</Application.Styles> </Application.Styles>
</Application> </Application>
@@ -4,11 +4,11 @@ using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using EarthModelStudio.Services; using GC.Services;
using EarthModelStudio.ViewModels; using GC.ViewModels;
using EarthModelStudio.Views; using GC.Views;
namespace EarthModelStudio; namespace GC;
public partial class App : Application public partial class App : Application
{ {
@@ -29,9 +29,58 @@ public partial class App : Application
return; return;
} }
var vm = new MainViewModel(services); // 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
var window = new MainWindow { DataContext = vm }; // MainViewModel 会扫描模型、加载封面、读设置,同步做会让
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
var window = new MainWindow();
window.Show();
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
LauncherRuntimeInfo.CurrentLauncherVersion);
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
// 会导致 DataContext 一直是 null、主页面白屏。
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
// 这样窗口能立刻响应,不会卡在白屏。
MainViewModel vm = null!;
Task.Run(() => new MainViewModel(services))
.ContinueWith(t =>
{
vm = t.Result;
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
window.DataContext = vm;
WireMainViewModel(vm, window, services, desktop);
}, Avalonia.Threading.DispatcherPriority.Background);
}, System.Threading.Tasks.TaskScheduler.Default);
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://GC.Core/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
/// <summary>
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
/// </summary>
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
{
_ = desktop;
vm.ConfirmHandler = async message => vm.ConfirmHandler = async message =>
{ {
var dialog = new ConfirmWindow(message); var dialog = new ConfirmWindow(message);
@@ -51,19 +100,7 @@ public partial class App : Application
return await dialog.ShowDialog<bool>(window); return await dialog.ShowDialog<bool>(window);
}; };
// 应用图标:窗口标题栏与任务栏也使用同一图标 // 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://EarthModelStudio/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
// 主窗口已建好,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1") if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{ {
Avalonia.Threading.Dispatcher.UIThread.Post( Avalonia.Threading.Dispatcher.UIThread.Post(
@@ -72,9 +109,6 @@ public partial class App : Application
} }
} }
base.OnFrameworkInitializationCompleted();
}
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary> /// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
private static int SelfTest(AppServices services) private static int SelfTest(AppServices services)
{ {
@@ -15,7 +15,7 @@
"home.installed": "Installed models", "home.installed": "Installed models",
"home.count": "{0} models", "home.count": "{0} models",
"home.empty": "No models yet", "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.emptyAction": "Get models",
"home.open": "Open folder", "home.open": "Open folder",
"home.delete": "Delete", "home.delete": "Delete",
@@ -15,7 +15,7 @@
"home.installed": "已安装模型", "home.installed": "已安装模型",
"home.count": "{0} 个模型", "home.count": "{0} 个模型",
"home.empty": "模型库还是空的", "home.empty": "模型库还是空的",
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。", "home.emptyHint": "启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。",
"home.emptyAction": "去下载模型", "home.emptyAction": "去下载模型",
"home.open": "打开目录", "home.open": "打开目录",
"home.delete": "删除", "home.delete": "删除",
File renamed without changes.
File renamed without changes.
@@ -1,21 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>EarthModelStudio</RootNamespace> <RootNamespace>GC</RootNamespace>
<AssemblyName>EarthModelStudio</AssemblyName> <AssemblyName>GC.Core</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- 应用图标(Windows exe / 任务栏) -->
<ApplicationIcon>Assets\icon.ico</ApplicationIcon>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault> <AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<InvariantGlobalization>false</InvariantGlobalization> <InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="Assets\**" />
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
<Compile Remove="test\**\*.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -25,9 +22,8 @@
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" /> <PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
</ItemGroup> </ItemGroup>
<!-- 模型契约:启动器与模型唯一的共享代码(不含任何渲染/业务) -->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\..\model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" /> <ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -2,7 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace EarthModelStudio.Models; namespace GC.Models;
/// <summary>应用设置,持久化到 data/settings.json。</summary> /// <summary>应用设置,持久化到 data/settings.json。</summary>
public sealed class AppSettings public sealed class AppSettings
@@ -38,7 +38,7 @@ public sealed class AppSettings
public bool AutoUpdateOnStartup { get; set; } = true; public bool AutoUpdateOnStartup { get; set; } = true;
/// <summary>默认更新仓库地址。</summary> /// <summary>默认更新仓库地址。</summary>
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC"; public string UpdateRepository { get; set; } = "https://gitcode.com/Morris_1/GC";
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary> /// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
public string? UpdateManifestUrl { get; set; } public string? UpdateManifestUrl { get; set; }
@@ -46,6 +46,12 @@ public sealed class AppSettings
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary> /// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
public string? UpdateLocalRoot { get; set; } public string? UpdateLocalRoot { get; set; }
/// <summary>
/// 要求版本清单必须带**有效签名**。默认开启:关闭后只警告不拦截,
/// 等于放弃「清单被篡改」的防护,只建议在自建私有构建里临时关闭。
/// </summary>
public bool RequireSignedManifest { get; set; } = true;
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary> /// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
public Dictionary<string, string> InstalledModelVersions { get; set; } = new(); public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
@@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace EarthModelStudio.Models; namespace GC.Models;
/// <summary>model/&lt;id&gt;/&lt;id&gt;.json 的内容。</summary> /// <summary>model/&lt;id&gt;/&lt;id&gt;.json 的内容。</summary>
public sealed class ModelManifest public sealed class ModelManifest
+67
View File
@@ -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;
/// <summary>
/// 规范化 JSON:签名与验签必须对完全相同的字节做运算,
/// 否则「同一份内容、不同缩进/键序」会得出不同签名。
///
/// 规则(写进 README,第三方可复现):
/// 1. 对象键按 Unicode 码点升序递归排序
/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM
/// 3. 数字沿用源文本(不做浮点重排)
/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping)
/// 5. 签名时先移除根级 <c>signature</c> 字段
/// </summary>
public static class CanonicalJson
{
private static readonly JsonSerializerOptions Options = new()
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
/// <summary>把 JSON 文本规范化;解析失败返回 null。</summary>
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();
}
}
}
+80
View File
@@ -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;
/// <summary>
/// 内容哈希(可复现的指纹算法)。
///
/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」:
/// <code>
/// fileHash = SHA256(文件字节)
/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接
/// "<相对路径&gt;\0&lt;fileHash&gt;\n" )
/// </code>
/// 相对路径统一用 <c>/</c> 分隔;跳过以 <c>.</c> 开头的文件、<c>bin/</c>、<c>obj/</c>、
/// <c>*.user</c>;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。
/// </summary>
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();
}
/// <summary>目录内所有参与分发的文件 -> { 相对路径 : sha256 }。</summary>
public static Dictionary<string, string> MapFiles(string directory)
{
var map = new Dictionary<string, string>(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;
}
/// <summary>按上述算法计算目录指纹。</summary>
public static string DirectoryHash(string directory)
=> DirectoryHash(MapFiles(directory));
public static string DirectoryHash(IReadOnlyDictionary<string, string> 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()));
}
/// <summary>目录指纹;目录不存在时返回空串(区别于空目录的哈希)。</summary>
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;
}
}
+44
View File
@@ -0,0 +1,44 @@
using System;
using System.Text.Json;
namespace GC.Services;
/// <summary>
/// 把「远端拿到的清单文本」变成 <see cref="RepoVersion"/>,同时带上验签结论。
///
/// 设计上把「验签」和「允不允许用」分开:
/// · 本方法只负责**如实报告**信任状态;
/// · 允不允许安装由 <c>UpdateService</c> / <c>LauncherUpdater</c> 按策略决定。
/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。
/// </summary>
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<RepoVersion>(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;
}
}
+172
View File
@@ -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;
/// <summary>清单可信度。</summary>
public enum ManifestTrust
{
/// <summary>签名有效,且密钥在受信任列表里。</summary>
Verified,
/// <summary>本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。</summary>
Skipped,
/// <summary>清单没有签名,但客户端要求签名。</summary>
Unsigned,
/// <summary>有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。</summary>
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);
}
/// <summary>
/// 版本清单签名(ECDSA P-256 / SHA-256)。
///
/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。
/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥,
/// 才能把「篡改清单」这条路堵死。
///
/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带
/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。
///
/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip
/// → 校验解压出的模型文件 → 加载 dll。
/// </summary>
public static class ManifestSignature
{
public const string Algorithm = "ECDSA-P256-SHA256";
private static readonly JsonSerializerOptions WriteOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
// ------------------------------------------------------------------ 验签
/// <summary>
/// 校验清单文本的签名。<paramref name="requireSignature"/> 为 true 时,
/// 无签名视为失败;为 false 时无签名只返回 <see cref="ManifestTrust.Unsigned"/>,
/// 由调用方决定是否放行(开发态用)。
/// </summary>
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<string>() ?? "";
var value = signature["value"]?.GetValue<string>() ?? "";
var alg = signature["alg"]?.GetValue<string>() ?? 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);
}
}
// ------------------------------------------------------------------ 签名
/// <summary>用私钥给清单签名,返回写入了 <c>signature</c> 字段的新清单文本。</summary>
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";
}
/// <summary>从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。</summary>
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;
}
}
/// <summary>导出公钥(SPKI / Base64),用于写入客户端受信任列表。</summary>
public static string ExportPublicKeyBase64(ECDsa key)
=> Convert.ToBase64String(key.ExportSubjectPublicKeyInfo());
/// <summary>公钥指纹,便于人工核对两边的公钥是否一致。</summary>
public static string PublicKeyFingerprint(string publicKeyBase64)
=> Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64)))
.ToLowerInvariant()[..16];
}
+111
View File
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace GC.Services;
/// <summary>模型安装后落盘的完整性记录。</summary>
public sealed class ModelIntegrityFile
{
public int Schema { get; set; } = 1;
public string Id { get; set; } = "";
public string Version { get; set; } = "";
/// <summary>模型清单文件的 sha256。</summary>
public string ManifestSha256 { get; set; } = "";
/// <summary>&lt;id&gt;.model 目录的目录指纹。</summary>
public string FilesSha256 { get; set; } = "";
/// <summary>关键文件(dll / json)逐文件哈希,用于加载前快速校验。</summary>
public Dictionary<string, string> Files { get; set; } = new();
public string InstalledAt { get; set; } = "";
/// <summary>来源(远端源名 / 本地目录),便于排查。</summary>
public string Source { get; set; } = "";
}
public sealed record IntegrityResult(bool Ok, bool Present, string Message)
{
public static readonly IntegrityResult Missing =
new(true, false, "没有完整性记录(本地/开发模型),跳过校验");
}
/// <summary>
/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。
///
/// 威胁模型:模型 dll 会被 <c>AssemblyLoadContext</c> 直接执行,等于任意代码。
/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。
/// 因此:
/// 1. version.json(已签名)里带 manifestSha256 / filesSha256;
/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装;
/// 3. 安装成功后写 <c>&lt;id&gt;.integrity.json</c>;
/// 4. 每次加载 dll 前抽查 dll / json 的哈希。
/// </summary>
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<ModelIntegrityFile>(IntegrityPath(modelDirectory, id));
public static void Write(string modelDirectory, string id, ModelIntegrityFile data)
=> Json.Write(IntegrityPath(modelDirectory, id), data);
/// <summary>
/// 计算某个模型包(清单 + 数据目录)的哈希。
/// <paramref name="packageDirectory"/> 是包含 <c>&lt;id&gt;.json</c> 与
/// <c>&lt;id&gt;.model/</c> 的那一层。
/// </summary>
public static (string ManifestSha256, string FilesSha256, Dictionary<string, string> 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<string, string>(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);
}
/// <summary>加载前校验:只查会被执行 / 解析的文件,保证 <c>OpenModel</c> 不被明显拖慢。</summary>
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);
}
}
+143
View File
@@ -0,0 +1,143 @@
using System;
using System.IO;
using System.IO.Compression;
namespace GC.Services;
/// <summary>
/// 安全解压:更新包来自网络,必须当成不可信输入处理。
///
/// 拦截:
/// · zip slip(<c>../</c>、绝对路径、盘符、UNC)
/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件)
/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常)
/// 逐条校验通过后**自己写文件**,不使用 <see cref="ZipFile.ExtractToDirectory(string,string)"/>,
/// 避免框架在写入阶段才发现问题、留下半成品。
/// </summary>
public static class SafeArchive
{
/// <summary>单个包最多条目数。</summary>
public const int MaxEntries = 20000;
/// <summary>解压后总体积上限(2 GiB)。</summary>
public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024;
/// <summary>单个条目解压上限(1 GiB)。</summary>
public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024;
/// <summary>压缩比上限:超过视为 zip 炸弹。</summary>
public const int MaxCompressionRatio = 200;
public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes)
{
public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes;
}
/// <summary>只检查不解压:条目数、体积、路径、链接。发现问题抛异常。</summary>
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);
}
}
/// <summary>校验条目名,拒绝一切能逃出目标目录的写法。</summary>
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}");
}
/// <summary>Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。</summary>
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 { /* 权限位设置失败不影响文件内容 */ }
}
}
+95
View File
@@ -0,0 +1,95 @@
using System;
namespace GC.Services;
/// <summary>
/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 <c>.GC/update/</c> 下,全部相对路径)。
///
/// 流程:
/// <code>
/// launcher 下载并校验更新包
/// -> 解压到 update/payload/
/// -> 写 apply-request.json + 已验签的 version.json 副本
/// -> 启动 GC-SAVEDOG apply --wait-pid &lt;自己&gt;
/// -> 自己退出
///
/// GC-SAVEDOG
/// -> 等父进程退出
/// -> 重验签名 + 包 sha256 + 解压安全性
/// -> 把 payload 移到安装目录(绝不覆盖已有版本)
/// -> 启动新版,等 update/health.json
/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版
/// -> 写 state.json(applied / rolledback / failed)
/// </code>
/// </summary>
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";
/// <summary>SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。</summary>
public static string ExecutableName =>
OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG";
}
/// <summary>启动器写入的更新申请。</summary>
public sealed class SavedogRequest
{
public int Schema { get; set; } = 1;
/// <summary>新版本号,如 1.0.8。</summary>
public string Version { get; set; } = "";
public string Rid { get; set; } = "";
/// <summary>文件名里的平台标签,如 mac-arm64。</summary>
public string PlatformLabel { get; set; } = "";
/// <summary>payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。</summary>
public string PackageName { get; set; } = "";
/// <summary>payload 目录(相对 update 目录)。</summary>
public string PayloadDir { get; set; } = "payload";
/// <summary>已验签清单的副本(相对 update 目录),用于二次验签。</summary>
public string ManifestPath { get; set; } = "version.json";
/// <summary>更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。</summary>
public string PackageZip { get; set; } = "package.zip";
/// <summary>更新包 sha256(来自已验签清单)。</summary>
public string? PackageSha256 { get; set; }
public long PackageSize { get; set; }
/// <summary>是否强制要求清单签名。</summary>
public bool RequireSignature { get; set; } = true;
/// <summary>安装目录(相对 update 目录),由启动器按实际路径算出。</summary>
public string InstallRelative { get; set; } = "../..";
public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
/// <summary>SAVEDOG 的执行结果,写入 state.json 供界面显示。</summary>
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; }
}
/// <summary>上次成功启动的版本信息,回滚时用。</summary>
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");
}
+79
View File
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
namespace GC.Services;
/// <summary>
/// 受信任的签名公钥。
///
/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库**
/// (放在仓库根 <c>.signing/</c>,已在 .gitignore 中)。
///
/// 轮换密钥:用 <c>GC-SAVEDOG keygen</c> 生成新的一对,把新公钥追加到这里,
/// 旧公钥保留一个版本周期,避免老客户端直接失效。
/// 也可用环境变量临时注入(测试 / 私有构建):
/// <c>GC_TRUSTED_KEYS="id1:base64;id2:base64"</c>
/// </summary>
public static class SignatureKeyring
{
public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null);
private static readonly List<KeyEntry> KeysInternal = new()
{
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
new KeyEntry(
"gc-2026-11",
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
"GC 主发布密钥")
};
static SignatureKeyring() => LoadFromEnvironment();
public static IReadOnlyList<KeyEntry> Keys => KeysInternal;
/// <summary>是否配置了受信任密钥(配置了就必须验签)。</summary>
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;
}
/// <summary>测试 / 私有分发用:追加一个受信任公钥。</summary>
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);
}
/// <summary>测试用:替换整个密钥环。</summary>
public static void ReplaceAll(IEnumerable<KeyEntry> 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"));
}
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.IO;
namespace GC.Services;
/// <summary>
/// 启动成功的健康标记。
///
/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现,
/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。
/// </summary>
public static class StartupHealth
{
public const string FileName = "health.json";
public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName);
/// <summary>主窗口显示后调用:证明本次启动真的跑起来了。</summary>
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<HealthRecord>(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; }
}
}
@@ -1,24 +1,27 @@
using System; using System;
using System.Threading.Tasks;
using System.IO; using System.IO;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 运行目录约定(可执行文件旁边,不内置任何模型): /// 运行目录约定(可执行文件旁边,不内置任何模型):
/// <code> /// <code>
/// &lt;安装目录&gt;/ /// &lt;安装目录&gt;/
/// EarthModelStudio(.exe | .app/...) /// GC(.exe | .app/...)
/// .GC/ /// .GC/
/// settings.json 设置与已安装版本记录 /// settings.json 设置与已安装版本记录
/// model/ 模型(启动时下载;model 目录也在 .GC 里) /// model/ 模型(启动时下载)
/// cache/ 下载缓存 / 原子替换暂存 /// cache/ 下载缓存 / 原子替换暂存
/// update/ 待下次启动应用的启动器更新包 /// update/ 待下次启动应用的启动器更新包
/// </code> /// </code>
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。 /// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。 /// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
/// </summary> /// </summary>
public sealed class AppPaths public sealed class AppPaths
{ {
private Task _developmentModelsSync = Task.CompletedTask;
/// <summary>安装目录(开发态为仓库根)。</summary> /// <summary>安装目录(开发态为仓库根)。</summary>
public string AppRoot { get; private init; } = ""; public string AppRoot { get; private init; } = "";
@@ -28,7 +31,7 @@ public sealed class AppPaths
/// <summary>.GC 目录。</summary> /// <summary>.GC 目录。</summary>
public string HomeRoot { get; private init; } = ""; public string HomeRoot { get; private init; } = "";
/// <summary>模型库,恒为 &lt;HomeRoot&gt;/model。</summary> /// <summary>模型库。</summary>
public string ModelRoot { get; private init; } = ""; public string ModelRoot { get; private init; } = "";
/// <summary>兼容旧代码:数据目录即 .GC。</summary> /// <summary>兼容旧代码:数据目录即 .GC。</summary>
@@ -36,7 +39,11 @@ public sealed class AppPaths
public string CacheRoot => Path.Combine(HomeRoot, "cache"); public string CacheRoot => Path.Combine(HomeRoot, "cache");
public string UpdateRoot => Path.Combine(HomeRoot, "update"); public string UpdateRoot => Path.Combine(HomeRoot, "update");
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
public string ConfigRoot => Path.Combine(HomeRoot, "config");
public string SettingsFile => Path.Combine(ConfigRoot, "settings.json");
public bool IsDevelopment { get; private init; } public bool IsDevelopment { get; private init; }
public bool IsPortableModelRoot { get; private init; } public bool IsPortableModelRoot { get; private init; }
@@ -47,22 +54,27 @@ public sealed class AppPaths
// 判定「当前目录」:程序实际所在的位置。 // 判定「当前目录」:程序实际所在的位置。
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录) // · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
// · 源码版:仓库根(含 EarthModelStudio.sln 的目录) // · 源码版:仓库根(含 GC.sln 的目录)
// //
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主, // 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。 // 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME"); var explicitHome = Environment.GetEnvironmentVariable("EMS_HOME");
var repoRoot = explicitHome;
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot)) if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir); repoRoot = FindRepoRoot(baseDir);
var isDev = !string.IsNullOrEmpty(repoRoot) && var isDev = !string.IsNullOrEmpty(repoRoot) &&
File.Exists(Path.Combine(repoRoot!, "EarthModelStudio.sln")); File.Exists(Path.Combine(repoRoot!, "GC.sln"));
string installDir; string installDir;
if (isDev) if (isDev)
{ {
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里 // 源码版:安装目录 = 仓库根
installDir = repoRoot!; installDir = repoRoot!;
} }
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
{
installDir = explicitHome;
}
else else
{ {
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。 // 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
@@ -111,13 +123,13 @@ public sealed class AppPaths
home = CanWrite(portableHome) home = CanWrite(portableHome)
? portableHome ? portableHome
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio", ".GC"); "GC", ".GC");
} }
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS"); var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
var modelRoot = !string.IsNullOrWhiteSpace(envModels) var modelRoot = !string.IsNullOrWhiteSpace(envModels)
? envModels! ? envModels!
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里 : Path.Combine(home, "model");
return new AppPaths return new AppPaths
{ {
@@ -137,7 +149,6 @@ public sealed class AppPaths
Directory.CreateDirectory(dir); Directory.CreateDirectory(dir);
var probe = Path.Combine(dir, ".write-test"); var probe = Path.Combine(dir, ".write-test");
File.WriteAllText(probe, "ok"); File.WriteAllText(probe, "ok");
File.Delete(probe);
return true; return true;
} }
catch catch
@@ -147,7 +158,7 @@ public sealed class AppPaths
} }
/// <summary> /// <summary>
/// 从程序所在位置向上找仓库根(含 EarthModelStudio.sln 的目录)。 /// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
/// ///
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。 /// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln, /// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
@@ -165,7 +176,7 @@ public sealed class AppPaths
var name = dir.Name; var name = dir.Name;
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null; if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
{ {
// 再确认不是从「发布输出目录」里往上找来的 // 再确认不是从「发布输出目录」里往上找来的
if (IsUnderPublishOutput(start, dir.FullName)) return null; if (IsUnderPublishOutput(start, dir.FullName)) return null;
@@ -240,20 +251,51 @@ public sealed class AppPaths
public void EnsureCreated() public void EnsureCreated()
{ {
Directory.CreateDirectory(HomeRoot); Directory.CreateDirectory(HomeRoot);
Directory.CreateDirectory(ConfigRoot);
Directory.CreateDirectory(CacheRoot); Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot); Directory.CreateDirectory(ModelRoot);
Directory.CreateDirectory(UpdateRoot); Directory.CreateDirectory(UpdateRoot);
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码) MigrateLegacySettings();
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS"))) if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
SyncDevelopmentModels(); {
var modelRoot = ModelRoot;
var source = Path.Combine(AppRoot, "model");
if (Directory.Exists(source))
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
}
} }
private void SyncDevelopmentModels() public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
/// <summary>
/// 老版本把设置放在 .GC/settings.json。现在设置归到 .GC/config/,
/// 与 cache/ 分开(清缓存不会连带清掉语言、内存预算、离线源等配置)。
/// 迁移只做一次:新位置不存在时才搬旧的。
/// </summary>
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 try
{ {
var source = Path.Combine(AppRoot, "model");
if (!Directory.Exists(source)) return; if (!Directory.Exists(source)) return;
foreach (var dir in Directory.GetDirectories(source)) foreach (var dir in Directory.GetDirectories(source))
{ {
@@ -262,7 +304,7 @@ public sealed class AppPaths
var manifest = Path.Combine(dir, id + ".json"); var manifest = Path.Combine(dir, id + ".json");
var data = Path.Combine(dir, id + ".model"); var data = Path.Combine(dir, id + ".model");
if (!File.Exists(manifest) || !Directory.Exists(data)) continue; if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
var dest = Path.Combine(ModelRoot, id); var dest = Path.Combine(modelRoot, id);
Directory.CreateDirectory(dest); Directory.CreateDirectory(dest);
File.Copy(manifest, Path.Combine(dest, id + ".json"), true); File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
CopyTree(data, Path.Combine(dest, id + ".model")); CopyTree(data, Path.Combine(dest, id + ".model"));
@@ -1,6 +1,6 @@
using System; using System;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary>组合根:一处初始化所有服务。</summary> /// <summary>组合根:一处初始化所有服务。</summary>
public sealed class AppServices public sealed class AppServices
@@ -10,15 +10,17 @@ public sealed class AppServices
public AppPaths Paths { get; } public AppPaths Paths { get; }
public SettingsService Settings { get; } public SettingsService Settings { get; }
public ModelRepository Models { get; } public ModelRepository Models { get; }
public DownloadCenter Downloads { get; } public IDownloadCenter Downloads { get; }
public MemoryBudget Memory { get; } public MemoryBudget Memory { get; }
public ModelSourceClient Sources { get; } public IModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary> /// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; } public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary> /// <summary>启动时检查模型 / 启动器更新。</summary>
public UpdateService Updates { get; } public IUpdateService Updates { get; }
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary> /// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
public SourceSelector Selector { get; } public ISourceSelector Selector { get; }
public ILauncherUpdateService LauncherUpdates { get; }
public IDownloadModule DownloadModule { get; }
private AppServices(AppPaths paths) private AppServices(AppPaths paths)
{ {
@@ -26,12 +28,16 @@ public sealed class AppServices
Settings = new SettingsService(paths); Settings = new SettingsService(paths);
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源 Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
Models = new ModelRepository(paths); Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths); var factory = DownloadModuleHost.Factory
Downloads = new DownloadCenter(paths, Models); ?? throw new InvalidOperationException("GC-DOWNLOAD 模块尚未注册");
DownloadModule = factory.Create(paths, Settings, Models);
Sources = DownloadModule.Sources;
Downloads = DownloadModule.Downloads;
Memory = new MemoryBudget(); Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory); ModelHost = new ModelHost(paths, Settings, Memory);
Selector = new SourceSelector(); Selector = DownloadModule.Selector;
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current)); Updates = DownloadModule.Updates;
LauncherUpdates = DownloadModule.LauncherUpdates;
} }
public static AppServices Create() public static AppServices Create()
@@ -5,7 +5,7 @@ using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary>GitCode 仓库的一位贡献者。</summary> /// <summary>GitCode 仓库的一位贡献者。</summary>
public sealed class Contributor public sealed class Contributor
@@ -21,7 +21,7 @@ public sealed class Contributor
/// </summary> /// </summary>
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase) private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
{ {
["2509_92447106"] = "Morris" ["Morris_1"] = "Morris"
}; };
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary> /// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
@@ -54,7 +54,7 @@ public static class ContributorsService
private static HttpClient CreateHttp() private static HttpClient CreateHttp()
{ {
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0"); c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json"); c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c; return c;
} }
@@ -63,13 +63,13 @@ public static class ContributorsService
public static string BuildUrl(string repository) public static string BuildUrl(string repository)
{ {
var raw = string.IsNullOrWhiteSpace(repository) var raw = string.IsNullOrWhiteSpace(repository)
? GitCodeRemote.DefaultRepository : repository.Trim(); ? SourcePreset.GitCode.HomeUrl : repository.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri)) if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors"; return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries); var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) if (parts.Length < 2)
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors"; return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase) var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1]; ? parts[1][..^4] : parts[1];
+157
View File
@@ -0,0 +1,157 @@
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
namespace GC.Services;
public enum DownloadState
{
Queued,
Running,
Completed,
Failed,
Canceled
}
public interface IDownloadJob : INotifyPropertyChanged
{
RemoteModel Model { get; }
string Id { get; }
string Name { get; }
string Version { get; }
CancellationTokenSource Cts { get; }
DownloadState State { get; set; }
double Progress { get; set; }
string StatusText { get; }
string DetailText { get; }
string? Error { get; set; }
bool IsActive { get; }
bool CanRetry { get; }
bool IsDone { get; }
void RefreshText();
}
public interface IDownloadCenter
{
ObservableCollection<IDownloadJob> Jobs { get; }
event Action? Installed;
IDownloadJob Enqueue(RemoteModel model);
void Cancel(IDownloadJob job);
void Retry(IDownloadJob job);
void Remove(IDownloadJob job);
void ClearFinished();
int ActiveCount { get; }
}
public interface IModelSourceClient
{
Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct);
}
public interface IUpdateService
{
IModelRemote Remote { get; }
void UseRemote(IModelRemote remote);
Task<UpdateResult> RunAsync(bool force, IProgress<UpdateProgress>? progress, CancellationToken ct = default);
}
public interface ISourceSelector
{
SourcePreset? Current { get; }
System.Collections.Generic.IReadOnlyDictionary<string, long> LastLatency { get; }
Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default);
}
public interface ILauncherUpdateService
{
Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default);
Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default);
bool ScheduleApply(AppPaths paths, string packageName);
bool TryApplyPending(AppPaths paths);
}
public enum UpdateRunState { UpToDate, Ready, Failed }
public sealed class UpdateProgressInfo
{
public double Value { get; init; }
public string Stage { get; init; } = "";
}
public sealed class UpdateRunResult
{
public UpdateRunState State { get; init; }
public string Version { get; init; } = "";
public string Message { get; init; } = "";
public string? PackageName { get; init; }
public string? NewAppPath { get; init; }
}
public interface IDownloadModule
{
IDownloadCenter Downloads { get; }
IModelSourceClient Sources { get; }
IUpdateService Updates { get; }
ISourceSelector Selector { get; }
ILauncherUpdateService LauncherUpdates { get; }
IModelRemote CreateRemote(SourcePreset preset);
}
public interface IDownloadModuleFactory
{
IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models);
bool TryApplyPending(AppPaths paths);
}
public static class DownloadModuleHost
{
public static IDownloadModuleFactory? Factory { get; set; }
}
public static class LauncherRuntimeInfo
{
private static string? _versionOverride;
public static string CurrentLauncherVersion
{
get
{
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
var assembly = typeof(AppServices).Assembly;
var version = assembly.GetName().Version;
if (version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0))
{
var info = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<
System.Reflection.AssemblyInformationalVersionAttribute>(assembly)?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(info) && Version.TryParse(info.Split('+')[0].Trim(), out var parsed))
version = parsed;
}
return version == null
? "0.0.0"
: $"{Math.Max(0, version.Major)}.{Math.Max(0, version.Minor)}.{Math.Max(0, version.Build)}";
}
}
public static string CurrentRid
{
get
{
var architecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
System.Runtime.InteropServices.Architecture.X86 => "x86",
_ => "x64"
};
if (OperatingSystem.IsWindows()) return "win-" + architecture;
if (OperatingSystem.IsMacOS()) return "osx-" + architecture;
if (OperatingSystem.IsLinux()) return "linux-" + architecture;
return System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
}
}
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
}
+64
View File
@@ -0,0 +1,64 @@
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;
public static class Json
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
/// <summary>
/// 源生成类型信息的提供者(可选)。
///
/// 启动器本身不做裁剪,走默认的反射序列化即可;GC-SAVEDOG 会被 PublishTrimmed
/// 裁掉无参构造,反射序列化在运行时直接抛 <c>NotSupportedException</c>。
/// 因此守护进程在启动时把本钩子指向 <c>JsonSerializerContext</c>,
/// 让所有读写都走编译期生成的 <see cref="JsonTypeInfo{T}"/>。
/// 这样「安全模块只有一份实现」的前提没有被破坏,只是换了元数据来源。
/// </summary>
public static Func<Type, JsonTypeInfo?>? TypeInfoProvider { get; set; }
public static T? Read<T>(string path)
{
if (!System.IO.File.Exists(path)) return default;
return Deserialize<T>(System.IO.File.ReadAllText(path));
}
public static void Write<T>(string path, T value)
{
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, Serialize(value));
System.IO.File.Move(tmp, path, true);
}
public static T? Deserialize<T>(string text)
{
if (string.IsNullOrWhiteSpace(text)) return default;
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
return info != null
? JsonSerializer.Deserialize(text, info)
: JsonSerializer.Deserialize<T>(text, Options);
}
public static string Serialize<T>(T value)
{
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
return info != null
? JsonSerializer.Serialize(value, info)
: JsonSerializer.Serialize(value, Options);
}
}
@@ -6,9 +6,9 @@ using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading; using Avalonia.Threading;
using EarthModelStudio.Views; using GC.Views;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用): /// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
@@ -52,7 +52,7 @@ public static class LauncherUpdateFlow
var progress = new Progress<UpdateProgressInfo>(p => var progress = new Progress<UpdateProgressInfo>(p =>
progressWindow.Report(p.Value, p.Stage)); progressWindow.Report(p.Value, p.Stage));
var result = await LauncherUpdater.DownloadAsync( var result = await services.LauncherUpdates.DownloadAsync(
services.Paths, services.Updates.Remote, progress); services.Paths, services.Updates.Remote, progress);
if (result.State == UpdateRunState.Failed) if (result.State == UpdateRunState.Failed)
@@ -68,7 +68,7 @@ public static class LauncherUpdateFlow
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…"); progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
// 4. 安排替换(下次启动生效 / 脚本接管重启) // 4. 安排替换(下次启动生效 / 脚本接管重启)
var scheduled = LauncherUpdater.ScheduleApply( var scheduled = services.LauncherUpdates.ScheduleApply(
services.Paths, result.PackageName ?? ""); services.Paths, result.PackageName ?? "");
if (!scheduled) if (!scheduled)
@@ -8,7 +8,7 @@ using Avalonia.Markup.Xaml;
using Avalonia.Data; using Avalonia.Data;
using Avalonia.Platform; using Avalonia.Platform;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary> /// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
public sealed class L : INotifyPropertyChanged public sealed class L : INotifyPropertyChanged
@@ -75,7 +75,7 @@ public sealed class L : INotifyPropertyChanged
{ {
try try
{ {
var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json"); var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
using var stream = AssetLoader.Open(uri); using var stream = AssetLoader.Open(uri);
using var reader = new StreamReader(stream); using var reader = new StreamReader(stream);
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(), return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
@@ -1,6 +1,6 @@
using System; using System;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 启动时运行内存分配(类似启动器的 -Xmx)。 /// 启动时运行内存分配(类似启动器的 -Xmx)。
@@ -11,7 +11,7 @@ public sealed class MemoryBudget
{ {
public int BudgetMb { get; private set; } = 2048; public int BudgetMb { get; private set; } = 2048;
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L; public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
public long ManagedBytes => GC.GetTotalMemory(false); public long ManagedBytes => System.GC.GetTotalMemory(false);
public event Action? Changed; public event Action? Changed;
@@ -29,7 +29,7 @@ public sealed class MemoryBudget
{ {
try try
{ {
var info = GC.GetGCMemoryInfo(); var info = System.GC.GetGCMemoryInfo();
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0); var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
if (totalMb > 0) if (totalMb > 0)
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192); return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
@@ -5,10 +5,10 @@ using System.Reflection;
using System.Runtime.Loader; using System.Runtime.Loader;
using System.Threading.Tasks; using System.Threading.Tasks;
using Avalonia.Controls; using Avalonia.Controls;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.ModelSdk; using GC.ModelSdk;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。 /// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
@@ -71,6 +71,40 @@ public sealed class ModelHost
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress) private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? 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; var assemblyPath = package.AssemblyPath;
if (!File.Exists(assemblyPath)) if (!File.Exists(assemblyPath))
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath); throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
@@ -89,7 +123,8 @@ public sealed class ModelHost
if (factory.ApiVersion != SupportedApiVersion) if (factory.ApiVersion != SupportedApiVersion)
throw new InvalidOperationException( throw new InvalidOperationException(
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致"); $"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
"请更新到匹配的版本");
var runtime = factory.Create(); var runtime = factory.Create();
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress); var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
@@ -118,6 +153,34 @@ public sealed class ModelHost
return null; return null;
} }
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
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 sealed class Session : IDisposable
{ {
private readonly ModelLoadContext _context; private readonly ModelLoadContext _context;
@@ -176,7 +239,7 @@ public sealed class ModelLoadContext : AssemblyLoadContext
{ {
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase) private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
{ {
"EarthModelStudio.ModelSdk", "GC.ModelSdk",
"Avalonia", "Avalonia",
"Avalonia.Base", "Avalonia.Base",
"Avalonia.Controls", "Avalonia.Controls",
@@ -2,9 +2,9 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 —— /// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
@@ -20,6 +20,7 @@ public sealed class ModelRepository
public IReadOnlyList<ModelPackage> Scan() public IReadOnlyList<ModelPackage> Scan()
{ {
_paths.WaitForDevelopmentModels();
var result = new List<ModelPackage>(); var result = new List<ModelPackage>();
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot)) foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
{ {
@@ -1,9 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
public static class ModelScanner public static class ModelScanner
{ {
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。 /// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。
@@ -2,9 +2,9 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using EarthModelStudio.Models; using GC.Models;
namespace EarthModelStudio.Services; namespace GC.Services;
public sealed class SettingsService public sealed class SettingsService
{ {
@@ -18,6 +18,12 @@ public sealed class SettingsService
public void Load() public void Load()
{ {
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings(); Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.UpdateRepository.Contains("gitcode.com/2509_92447106/GC", StringComparison.OrdinalIgnoreCase))
{
Current.UpdateRepository = Current.UpdateRepository.Replace(
"2509_92447106", "Morris_1", StringComparison.OrdinalIgnoreCase);
Save();
}
SeedDefaultSource(); SeedDefaultSource();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048; if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
} }
@@ -28,7 +34,7 @@ public sealed class SettingsService
/// 老配置里的自定义源会被清理掉。 /// 老配置里的自定义源会被清理掉。
/// </summary> /// </summary>
public const string DefaultSourceId = "gitcode"; public const string DefaultSourceId = "gitcode";
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC"; public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
private void SeedDefaultSource() private void SeedDefaultSource()
{ {
@@ -2,7 +2,7 @@ using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
namespace EarthModelStudio.Services; namespace GC.Services;
public static class Shell public static class Shell
{ {
@@ -2,7 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary> /// <summary>
/// 内置下载源。只允许这两个,不再支持用户自定义源。 /// 内置下载源。只允许这两个,不再支持用户自定义源。
@@ -53,12 +53,12 @@ public sealed class SourcePreset
{ {
Id = "gitcode", Id = "gitcode",
Name = "GitCode", Name = "GitCode",
HomeUrl = "https://gitcode.com/2509_92447106/GC", HomeUrl = "https://gitcode.com/Morris_1/GC",
ApiBase = "https://api.gitcode.com/api/v5", ApiBase = "https://api.gitcode.com/api/v5",
RawBase = "https://gitcode.com", RawBase = "https://gitcode.com",
Kind = "gitcode", Kind = "gitcode",
RawStyle = "plain", RawStyle = "plain",
Owner = "2509_92447106", Owner = "Morris_1",
Repo = "GC", Repo = "GC",
Branch = "main" Branch = "main"
}; };
@@ -1,9 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json.Serialization;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace EarthModelStudio.Services; namespace GC.Services;
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary> /// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
public sealed class RepoVersion public sealed class RepoVersion
@@ -15,6 +16,20 @@ public sealed class RepoVersion
public string ModelDir { get; set; } = "model"; public string ModelDir { get; set; } = "model";
public RepoLauncher Launcher { get; set; } = new(); public RepoLauncher Launcher { get; set; } = new();
public List<RepoModel> Models { get; set; } = new(); public List<RepoModel> Models { get; set; } = new();
// ---- 验签结论(解析时填入,不参与序列化) ----------------------------
/// <summary>Verified / Skipped / Unsigned / Invalid。</summary>
[JsonIgnore] public string SignatureTrust { get; set; } = "";
[JsonIgnore] public string? SignatureKeyId { get; set; }
[JsonIgnore] public string? SignatureError { get; set; }
/// <summary>清单是否可用:签名有效,或本机没有配置公钥(兼容期)。</summary>
[JsonIgnore]
public bool IsTrusted =>
SignatureTrust is nameof(ManifestTrust.Verified) or nameof(ManifestTrust.Skipped);
} }
public sealed class RepoLauncher public sealed class RepoLauncher
@@ -34,6 +49,19 @@ public sealed class RepoPackage
public long Size { get; set; } public long Size { get; set; }
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary> /// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
public string? AssetName { get; set; } public string? AssetName { get; set; }
/// <summary>
/// 仓库里的平台产物目录,如 <c>dist/mac-arm64</c>。
/// 不发 Release、只把编译产物提交进仓库时,更新包就在这里找。
/// 清单没写时由 <see cref="Rid"/> 推导。
/// </summary>
public string? Dir { get; set; }
/// <summary>包文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>;清单没写时按版本与平台标签拼。</summary>
public string? Name { get; set; }
/// <summary>所属平台键(win-x64 / win-arm64 / osx-arm64 …),解析清单时按字典键填入。</summary>
[JsonIgnore] public string Rid { get; set; } = "";
} }
public sealed class RepoModel public sealed class RepoModel
@@ -42,6 +70,20 @@ public sealed class RepoModel
public string Version { get; set; } = ""; public string Version { get; set; } = "";
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary> /// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
public string Dir { get; set; } = ""; public string Dir { get; set; } = "";
// ---- 完整性(由 VersionStamp 计算,签名覆盖这几个字段) ----------------
/// <summary>内容指纹(构建溯源,不参与版本比较)。</summary>
public string? Build { get; set; }
/// <summary>模型清单 &lt;id&gt;.json 的 sha256。</summary>
public string? ManifestSha256 { get; set; }
/// <summary>&lt;id&gt;.model 目录的目录指纹(算法见 ContentHash)。</summary>
public string? FilesSha256 { get; set; }
/// <summary>参与分发的文件数。</summary>
public int Files { get; set; }
} }
/// <summary>远端目录树里的一个条目。</summary> /// <summary>远端目录树里的一个条目。</summary>
@@ -71,6 +113,12 @@ public interface IModelRemote
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct); Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct); Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct); Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
/// <summary>
/// 最近一次读到的清单**原始文本**(含 signature 字段),供 SAVEDOG 二次验签。
/// 默认返回 null,表示该源不支持(调用方会退化为单次验签)。
/// </summary>
Task<string?> GetRawVersionTextAsync(CancellationToken ct) => Task.FromResult<string?>(null);
} }
public sealed class UpdateProgress public sealed class UpdateProgress
@@ -4,9 +4,9 @@ using System.Collections.ObjectModel;
using System.Threading.Tasks; using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.ViewModels; namespace GC.ViewModels;
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary> /// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
public partial class AboutViewModel : ObservableObject public partial class AboutViewModel : ObservableObject
@@ -29,10 +29,10 @@ public partial class AboutViewModel : ObservableObject
public string AppName => "Morris GC"; public string AppName => "Morris GC";
/// <summary>启动器版本号,如 v1.0.2。</summary> /// <summary>启动器版本号,如 v1.0.2。</summary>
public string VersionText => "v" + UpdateService.CurrentLauncherVersion; public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary> /// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
public string PlatformText => UpdateService.CurrentRid; public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public string RepositoryText => _services.Settings.Current.UpdateRepository; public string RepositoryText => _services.Settings.Current.UpdateRepository;
@@ -9,10 +9,10 @@ using System.Threading.Tasks;
using System.Windows.Input; using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.ViewModels; namespace GC.ViewModels;
public partial class DownloadViewModel : ObservableObject public partial class DownloadViewModel : ObservableObject
{ {
@@ -25,7 +25,7 @@ public partial class DownloadViewModel : ObservableObject
public ObservableCollection<SourceItemViewModel> Sources { get; } = new(); public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new(); public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
public ObservableCollection<DownloadJob> Jobs => _services.Downloads.Jobs; public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
[ObservableProperty] private SourceItemViewModel? _selectedSource; [ObservableProperty] private SourceItemViewModel? _selectedSource;
[ObservableProperty] private string _importUrl = ""; [ObservableProperty] private string _importUrl = "";
@@ -264,19 +264,19 @@ public partial class DownloadViewModel : ObservableObject
} }
[RelayCommand] [RelayCommand]
private void CancelJob(DownloadJob? job) private void CancelJob(IDownloadJob? job)
{ {
if (job != null) _services.Downloads.Cancel(job); if (job != null) _services.Downloads.Cancel(job);
} }
[RelayCommand] [RelayCommand]
private void RetryJob(DownloadJob? job) private void RetryJob(IDownloadJob? job)
{ {
if (job != null) _services.Downloads.Retry(job); if (job != null) _services.Downloads.Retry(job);
} }
[RelayCommand] [RelayCommand]
private void RemoveJob(DownloadJob? job) private void RemoveJob(IDownloadJob? job)
{ {
if (job != null) _services.Downloads.Remove(job); if (job != null) _services.Downloads.Remove(job);
} }
@@ -291,17 +291,17 @@ public partial class DownloadViewModel : ObservableObject
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e) private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{ {
if (e.NewItems != null) if (e.NewItems != null)
foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged; foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
if (e.OldItems != null) if (e.OldItems != null)
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged; foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
UpdateJobState(); UpdateJobState();
} }
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e) private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
{ {
if (e.PropertyName == nameof(DownloadJob.State)) if (e.PropertyName == nameof(IDownloadJob.State))
{ {
if (sender is DownloadJob { State: DownloadState.Completed }) if (sender is IDownloadJob { State: DownloadState.Completed })
_services.Models.NotifyChanged(); _services.Models.NotifyChanged();
} }
UpdateJobState(); UpdateJobState();
@@ -6,11 +6,11 @@ using System.Threading.Tasks;
using System.Windows.Input; using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models; using GC.Models;
using Avalonia.Media.Imaging; using Avalonia.Media.Imaging;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.ViewModels; namespace GC.ViewModels;
public partial class HomeViewModel : ObservableObject public partial class HomeViewModel : ObservableObject
{ {
@@ -3,10 +3,10 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.ViewModels; namespace GC.ViewModels;
public partial class MainViewModel : ObservableObject public partial class MainViewModel : ObservableObject
{ {
@@ -46,8 +46,8 @@ public partial class MainViewModel : ObservableObject
public event Action<ModelPackage>? PlayerRequested; public event Action<ModelPackage>? PlayerRequested;
public string VersionText => "v" + UpdateService.CurrentLauncherVersion; public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
public string PlatformText => UpdateService.CurrentRid; public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public MainViewModel(AppServices services) public MainViewModel(AppServices services)
{ {
@@ -143,7 +143,7 @@ public partial class MainViewModel : ObservableObject
{ {
var fastest = await _services.Selector.PickFastestAsync( var fastest = await _services.Selector.PickFastestAsync(
force, default); force, default);
_services.Updates.UseRemote(SourceSelector.CreateRemote(fastest)); _services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
var lat = _services.Selector.LastLatency; var lat = _services.Selector.LastLatency;
UpdateDetail = "源:" + fastest.Name + UpdateDetail = "源:" + fastest.Name +
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv => (lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
@@ -155,7 +155,7 @@ public partial class MainViewModel : ObservableObject
} }
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问 // 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
var latest = await LauncherUpdater.CheckAsync(_services.Updates.Remote); var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
if (latest != null) if (latest != null)
{ {
var agreed = LauncherUpdateHandler != null && var agreed = LauncherUpdateHandler != null &&
@@ -181,6 +181,15 @@ public partial class MainViewModel : ObservableObject
UpdateDetail = result.Error ?? ""; UpdateDetail = result.Error ?? "";
LauncherNotice = result.LauncherMessage ?? ""; LauncherNotice = result.LauncherMessage ?? "";
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
{
UpdateStatus = "暂时连不上模型源,模型库为空";
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
return;
}
// 模型下载完成后本次启动就刷新列表,立刻可用 // 模型下载完成后本次启动就刷新列表,立刻可用
if (result.UpdatedModels > 0) Home.Refresh(); if (result.UpdatedModels > 0) Home.Refresh();
@@ -5,10 +5,10 @@ using System.Runtime.InteropServices;
using System.Windows.Input; using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.ViewModels; namespace GC.ViewModels;
public sealed class LanguageOption public sealed class LanguageOption
{ {
@@ -156,8 +156,8 @@ public partial class SettingsViewModel : ObservableObject
private void ClearCache() private void ClearCache()
{ {
// 模型数据由模型自己管理;这里只回收启动器侧托管内存 // 模型数据由模型自己管理;这里只回收启动器侧托管内存
GC.Collect(); System.GC.Collect();
GC.WaitForPendingFinalizers(); System.GC.WaitForPendingFinalizers();
_services.Memory.Refresh(); _services.Memory.Refresh();
StatusMessage = L.I["set.cacheCleared"]; StatusMessage = L.I["set.cacheCleared"];
OnPropertyChanged(nameof(UsageText)); OnPropertyChanged(nameof(UsageText));
@@ -1,8 +1,8 @@
<UserControl xmlns="https://github.com/avaloniaui" <UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
xmlns:vm="using:EarthModelStudio.ViewModels" xmlns:vm="using:GC.ViewModels"
x:Class="EarthModelStudio.Views.AboutView" x:Class="GC.Views.AboutView"
x:DataType="vm:AboutViewModel"> x:DataType="vm:AboutViewModel">
<ScrollViewer> <ScrollViewer>
@@ -1,7 +1,7 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class AboutView : UserControl public partial class AboutView : UserControl
{ {
@@ -1,7 +1,7 @@
<Window xmlns="https://github.com/avaloniaui" <Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
x:Class="EarthModelStudio.Views.ConfirmWindow" x:Class="GC.Views.ConfirmWindow"
Title="{loc:Loc app.name}" Title="{loc:Loc app.name}"
Width="440" SizeToContent="Height" Width="440" SizeToContent="Height"
CanResize="False" ShowInTaskbar="False" CanResize="False" ShowInTaskbar="False"
@@ -4,7 +4,7 @@ using Avalonia.Interactivity;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Media; using Avalonia.Media;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class ConfirmWindow : Window public partial class ConfirmWindow : Window
{ {
@@ -1,7 +1,7 @@
<UserControl xmlns="https://github.com/avaloniaui" <UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
x:Class="EarthModelStudio.Views.DownloadView"> x:Class="GC.Views.DownloadView">
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24"> <Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
@@ -1,7 +1,7 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class DownloadView : UserControl public partial class DownloadView : UserControl
{ {
@@ -1,8 +1,8 @@
<UserControl xmlns="https://github.com/avaloniaui" <UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
xmlns:controls="using:EarthModelStudio.Controls" xmlns:controls="using:GC.Controls"
x:Class="EarthModelStudio.Views.HomeView"> x:Class="GC.Views.HomeView">
<ScrollViewer VerticalScrollBarVisibility="Auto"> <ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="26,24,26,28" Spacing="18"> <StackPanel Margin="26,24,26,28" Spacing="18">
@@ -1,7 +1,7 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class HomeView : UserControl public partial class HomeView : UserControl
{ {
@@ -8,7 +8,7 @@ using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Threading; using Avalonia.Threading;
namespace EarthModelStudio.Views; namespace GC.Views;
/// <summary> /// <summary>
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。 /// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
@@ -1,7 +1,7 @@
<Window xmlns="https://github.com/avaloniaui" <Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
x:Class="EarthModelStudio.Views.MainWindow" x:Class="GC.Views.MainWindow"
Title="{loc:Loc app.name}" Title="{loc:Loc app.name}"
Width="1220" Height="800" Width="1220" Height="800"
MinWidth="1040" MinHeight="700" MinWidth="1040" MinHeight="700"
@@ -10,11 +10,11 @@ using System.Linq;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using EarthModelStudio.Models; using GC.Models;
using EarthModelStudio.Services; using GC.Services;
using EarthModelStudio.ViewModels; using GC.ViewModels;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
@@ -1,7 +1,7 @@
<UserControl xmlns="https://github.com/avaloniaui" <UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services" xmlns:loc="using:GC.Services"
x:Class="EarthModelStudio.Views.SettingsView"> x:Class="GC.Views.SettingsView">
<ScrollViewer VerticalScrollBarVisibility="Auto"> <ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left"> <StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
@@ -1,7 +1,7 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views; namespace GC.Views;
public partial class SettingsView : UserControl public partial class SettingsView : UserControl
{ {
@@ -4,9 +4,9 @@ using Avalonia.Controls;
using Avalonia.Layout; using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Threading; using Avalonia.Threading;
using EarthModelStudio.Services; using GC.Services;
namespace EarthModelStudio.Views; namespace GC.Views;
/// <summary> /// <summary>
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。 /// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
@@ -4,8 +4,8 @@
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>EarthModelStudio.Tests</RootNamespace> <RootNamespace>GC.Tests</RootNamespace>
<AssemblyName>EarthModelStudio.Tests</AssemblyName> <AssemblyName>GC.Tests</AssemblyName>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,7 +14,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="../../../main/dotnet/EarthModelStudio/EarthModelStudio.csproj" /> <ProjectReference Include="../../../GC.Core.csproj" />
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -2,25 +2,29 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using EarthModelStudio.Models; using System.Security.Cryptography;
using System.Text.Json;
using GC.Models;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Headless; using Avalonia.Headless;
using Avalonia.Threading; using Avalonia.Threading;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using EarthModelStudio; using GC;
using EarthModelStudio.Services; using GC.Download;
using EarthModelStudio.ViewModels; using GC.Services;
using EarthModelStudio.Views; using GC.ViewModels;
using GC.Views;
namespace EarthModelStudio.Tests; namespace GC.Tests;
/// <summary> /// <summary>
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。 /// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
/// 用法:dotnet run --project src/test/dotnet/EarthModelStudio.Tests -- build/screenshots /// 用法:dotnet run --project GC/src/test/dotnet/GC.Tests -- build/screenshots
/// </summary> /// </summary>
internal static class Program internal static class Program
{ {
@@ -29,6 +33,7 @@ internal static class Program
[STAThread] [STAThread]
public static int Main(string[] args) public static int Main(string[] args)
{ {
DownloadModuleHost.Factory = new DownloadModuleFactory();
if (args.Length > 0 && args[0] == "--update-test") if (args.Length > 0 && args[0] == "--update-test")
return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot()); return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot());
@@ -76,7 +81,9 @@ internal static class Program
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/ // 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
Directory.CreateDirectory(Path.Combine(remote, "model")); Directory.CreateDirectory(Path.Combine(remote, "model"));
File.Copy(versionFile, Path.Combine(remote, "version.json"), true); var fixtureVersion = Json.Read<RepoVersion>(versionFile)!;
fixtureVersion.Models.RemoveAll(model =>
model.Id is not "earth-rotation" and not "earth-revolution");
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model"))) foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
{ {
var id = Path.GetFileName(dir); var id = Path.GetFileName(dir);
@@ -90,10 +97,32 @@ internal static class Program
CopyTree(data, Path.Combine(dest, id + ".model")); 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 布局 // EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
Environment.SetEnvironmentVariable("EMS_HOME", tmp); Environment.SetEnvironmentVariable("EMS_HOME", tmp);
Environment.SetEnvironmentVariable("EMS_DATA", home); Environment.SetEnvironmentVariable("EMS_DATA", home);
Environment.SetEnvironmentVariable("EMS_MODELS", modelRoot); Environment.SetEnvironmentVariable("EMS_MODELS", null);
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1"); Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
var paths = AppPaths.Discover(); var paths = AppPaths.Discover();
@@ -111,11 +140,13 @@ internal static class Program
Console.WriteLine($"运行目录: {paths.HomeRoot}"); Console.WriteLine($"运行目录: {paths.HomeRoot}");
Console.WriteLine($"模型库: {paths.ModelRoot}"); Console.WriteLine($"模型库: {paths.ModelRoot}");
Check(paths.ModelRoot == modelRoot, ".GC/model 是下载目标"); Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model");
Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建"); 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/config/settings.json 已创建");
// 1) 首次启动:模型全部下载并立即落地 // 1) 首次启动:模型全部下载并立即落地
var r1 = updater.RunAsync(true, null).GetAwaiter().GetResult(); var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}"); Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}");
Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型"); Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型");
foreach (var id in new[] { "earth-rotation", "earth-revolution" }) foreach (var id in new[] { "earth-rotation", "earth-revolution" })
@@ -128,12 +159,12 @@ internal static class Program
} }
// 2) 版本没变:不重复下载 // 2) 版本没变:不重复下载
var r2 = updater.RunAsync(true, null).GetAwaiter().GetResult(); var r2 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}"); Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}");
Check(r2.UpdatedModels == 0, "版本未变时不重复下载"); Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效 // 3) 远端模型改版:只更新这一个,并且本次启动立即生效
var rv = Json.Read<RepoVersion>(Path.Combine(remote, "version.json"))!; var rv = Json.Read<RepoVersion>(remoteManifest)!;
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version), Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
"version.json 里模型版本由构建自动生成"); "version.json 里模型版本由构建自动生成");
var changed = rv.Models[0]; var changed = rv.Models[0];
@@ -141,16 +172,25 @@ internal static class Program
var stampName = "_version-stamp.txt"; var stampName = "_version-stamp.txt";
File.WriteAllText(Path.Combine(remote, "model", changed.Id, File.WriteAllText(Path.Combine(remote, "model", changed.Id,
changed.Id + ".model", stampName), "new content"); changed.Id + ".model", stampName), "new content");
Json.Write(Path.Combine(remote, "version.json"), rv);
var r3 = updater.RunAsync(true, null).GetAwaiter().GetResult(); // 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
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}"); Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型"); 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 + ".model", stampName)),
"新版本本次启动立即生效"); "新版本本次启动立即生效");
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")),
"安装后写入完整性记录");
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列) // 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
var rid = UpdateService.CurrentRid; var rid = LauncherRuntimeInfo.CurrentRid;
Console.WriteLine($"当前平台: {rid},启动器版本: {UpdateService.CurrentLauncherVersion}"); Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
var stage = Path.Combine(tmp, "launcher-stage"); var stage = Path.Combine(tmp, "launcher-stage");
Directory.CreateDirectory(stage); Directory.CreateDirectory(stage);
File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"), File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"),
@@ -158,19 +198,29 @@ internal static class Program
var zip = Path.Combine(tmp, "GC-" + rid + ".zip"); var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
ZipFile.CreateFromDirectory(stage, zip); ZipFile.CreateFromDirectory(stage, zip);
rv.Launcher.Version = "9.9.9"; rv.Launcher.Version = "9.9.9";
rv.Launcher.Packages[rid] = new RepoPackage { Url = zip }; rv.Launcher.Packages[rid] = new RepoPackage
Json.Write(Path.Combine(remote, "version.json"), rv); {
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"; var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher"); File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
var dl = LauncherUpdater.DownloadAsync(paths, updater.Remote, null).GetAwaiter().GetResult(); var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
.GetAwaiter().GetResult();
Console.WriteLine($"启动器下载: {dl.Message}"); Console.WriteLine($"启动器下载: {dl.Message}");
Check(dl.State == UpdateRunState.Ready, "启动器下载成功"); Check(dl.State == UpdateRunState.Ready, "启动器下载成功");
Check(!string.IsNullOrWhiteSpace(dl.PackageName), "得到新版包名"); Check(!string.IsNullOrWhiteSpace(dl.PackageName), "得到新版包名");
Check(File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")), Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")) ||
"新版已存到当前目录"); Directory.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")),
"新版暂存于 .GC/update/payload");
Check(!File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")) &&
!Directory.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")),
"下载阶段不会把新版写入安装目录");
Check(File.Exists(Path.Combine(paths.InstallDirectory, oldName)), Check(File.Exists(Path.Combine(paths.InstallDirectory, oldName)),
"旧版仍在(删除由替换脚本在重启后做)"); "旧版仍在(删除由替换脚本在重启后做)");
@@ -188,10 +238,63 @@ internal static class Program
Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除"); 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 offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
var beforeCount = settings.Current.InstalledModelVersions.Count; var beforeCount = settings.Current.InstalledModelVersions.Count;
var r5 = offline.RunAsync(true, null).GetAwaiter().GetResult(); var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult();
Check(r5.Outcome == UpdateOutcome.Unavailable && Check(r5.Outcome == UpdateOutcome.Unavailable &&
settings.Current.InstalledModelVersions.Count == beforeCount && settings.Current.InstalledModelVersions.Count == beforeCount &&
Directory.Exists(Path.Combine(modelRoot, "earth-rotation")), Directory.Exists(Path.Combine(modelRoot, "earth-rotation")),
@@ -204,6 +307,13 @@ internal static class Program
return failures == 0 ? 0 : 1; return failures == 0 ? 0 : 1;
} }
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
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) private static void CopyTree(string src, string dst)
{ {
Directory.CreateDirectory(dst); Directory.CreateDirectory(dst);
@@ -221,7 +331,7 @@ internal static class Program
var dir = new DirectoryInfo(AppContext.BaseDirectory); var dir = new DirectoryInfo(AppContext.BaseDirectory);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent) for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{ {
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName; if (File.Exists(Path.Combine(dir.FullName, "GC.sln"))) return dir.FullName;
} }
return Directory.GetCurrentDirectory(); return Directory.GetCurrentDirectory();
} }
+190 -75
View File
@@ -1,110 +1,216 @@
# Earth Model Studio # GC
天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。 天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。
> **分层约定(重要)** > **分层约定(重要)**
> - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。 > - `GC/` = 启动器:扫描、下载、开窗口、显示加载进度。**不渲染、不含任何模型内容、发布包不内置模型**。
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。 > - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
> - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。 > - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。 > - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,启动器一行都不用改,客户端启动自动更新。
> - `GC-SAVEDOG/` = 更新守护进程:验签、原子替换、启动后健康检查、失败回滚。
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台 - UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载 - 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译 - 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵)
- 更新仓库:<https://gitcode.com/2509_92447106/GC>,模型目录 <https://gitcode.com/2509_92447106/GC/tree/main/model> - 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
## 快速开始
```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`。
## 运行目录(发布包里就长这样) ## 运行目录(发布包里就长这样)
``` ```
<安装目录>/ <安装目录>/
EarthModelStudio.exe | EarthModelStudio.app/ GC.exe | GC.app/
GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内)
.GC/ .GC/
settings.json 设置 + 已安装版本记录 config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置)
model/ 启动时下载的模型 model/ 启动时下载的模型
cache/ 下载暂存 / 原子替换 cache/ 下载暂存 / 原子替换
update/ 待下次启动应用的启动器更新 update/ 待应用的启动器更新(apply-request.json + package.zip)
``` ```
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示; **发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。 安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载;
`.GC/config/settings.json` 删掉等于恢复出厂设置。
## 自动更新 ## 自动更新
| 检查项 | 不是最新版时 | 生效时机 | | 检查项 | 不是最新版时 | 生效时机 |
| --- | --- | --- | | --- | --- | --- |
| 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) | | 模型 | 按文件清单下载到 `cache/`,校验哈希后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) | | 启动器 | 下载对应平台 zip 到 `.GC/update/`,交给 `GC-SAVEDOG` | **下次启动时应用**(重启后自动替换) |
- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`: 启动器更新的完整流程:
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**, ```
所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。 启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出
- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。 GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
- 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。 -> 移入安装目录(绝不覆盖已有版本)
- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。 -> 启动新版,等 .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`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填 - 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
`updateLocalRoot` 指向它,即可完全离线更新。 `updateLocalRoot` 指向它,即可完全离线更新(同样会验签)
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。 ## 安全模型
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
威胁模型很直接:**模型 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` 的 `<Version>`;`./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<fileHash>\n" )
```
相对路径统一 `/` 分隔,跳过 `.` 开头的文件、`bin/`、`obj/`、`*.user`;
不含时间戳、权限位、文件顺序。实现见 `GC/src/Security/ContentHash.cs`,构建端由
`VersionStamp` 直接链接同一份源码,不会出现两套算法。
## 目录结构 ## 目录结构
``` ```
EarthModelStudio/ Repository/
├── EarthModelStudio.sln ├── GC.sln
├── Directory.Build.props # 公共构建属性 ├── Directory.Build.props # 公共构建属性(版本号在这里)
├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效) ├── version.json # ★ 自动生成并签名的版本清单(推送到仓库后才生效)
├── build.sh / build.ps1 # 构建脚本 ├── build.sh / build.ps1 # 构建脚本(实际实现在 buildsh/ 与 buildps1/)
├── src/ # ★ 启动器(没有渲染逻辑) ├── GC/ # 启动器
│ └── main/dotnet/EarthModelStudio/ │ └── src/
│ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新 │ ├── GC.Core.csproj
│ │ # UpdateService · GitCodeRemote · DirectoryRemote · LauncherUpdate │ ├── Security/ # ★ 验签、哈希、安全解压、完整性、健康标记
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳、启动更新状态条 │ ├── Models/ Services/
│ └── Assets/i18n/ # 启动器界面语言包 │ ├── ViewModels/ Views/
├── src/test/dotnet/…Tests/ # 离屏校验 + --update-test 离线更新链路验证 │ ├── Assets/i18n/ # 界面语言包
│ └── test/dotnet/GC.Tests/ # 离屏校验 + --update-test 离线更新链路验证
├── GC-BOOT/ # 轻量启动入口
├── GC-DOWNLOAD/ # 源仓库 / 模型 / 启动器下载更新
├── GC-DRAW/PlayerWindow.cs # 模型窗口宿主;绘制由模型提供
├── GC-SAVEDOG/ # ★ 更新守护进程(apply / verify / keygen / sign / status)
├── model/ # ★ 模型的一切 ├── model/ # ★ 模型的一切
│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取) │ ├── version.json # 与根 version.json 完全相同(同一份签名)
│ ├── _sdk/EarthModelStudio.ModelSdk/ │ ├── _sdk/GC.ModelSdk/
│ ├── _engine/ │ ├── _engine/{src,PreviewGen,VersionStamp}/
│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView … │ ├── earth-rotation/{earth-rotation.json,src/,earth-rotation.model/}
│ │ ├── PreviewGen/ # 用模型渲染器生成封面
│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json
│ ├── earth-rotation/
│ │ ├── earth-rotation.json
│ │ ├── src/ # 本模型源码
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
│ └── earth-revolution/ │ └── earth-revolution/
└── dist/ # 发布产物(只有启动器 + .GC 骨架) ├── dist/ # 发布产物(.gitignore,只通过 Release 分发)
└── .signing/ # 签名私钥(.gitignore,绝不入库)
``` ```
模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。 模型库位置:`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 ```bash
./build.sh build # 编译整个解决方案 ./build.sh build # 三平台完整发布:启动器 + SAVEDOG + 运行骨架 + 更新包 ZIP
./build.sh models # 编译模型 dll + 生成封面 + 自动打版本 ./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查
./build.sh stamp # 只重新生成 version.json 与模型版本 ./build.sh models # 编译模型 dll、生成封面、更新并签名版本清单
./build.sh run # 运行 ./build.sh stamp # 只重新生成 + 签名 version.json
./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图 ./build.sh run # Debug 运行启动器
./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序) ./build.sh test # 离屏校验,截图写入 build/screenshots/
./build.sh publish # 三平台发布(不内置模型)+ 建 .GC 骨架 + 生成更新包 ./build.sh update-test # 离线验证自动更新链路(验签 / 立即生效 / 篡改拒绝 / 断网兜底)
./build.sh pack-models # 单独打包模型 -> dist/models-<version>.zip ./build.sh pack-models # 编译模型并打包 dist/models-<版本>.zip
./build.sh pack-launcher # 生成三个平台的启动器更新包 zip ./build.sh pack-launcher # 把已有平台发布目录打成启动器更新 ZIP
./build.sh clean ./build.sh doctor # dotnet 环境信息
./build.sh dist # 列出 dist/ 产物
./build.sh clean # 清理 build/ 与 dist/
``` ```
Windows 用 `.\build.ps1`(参数相同)。
| 产物 | 平台 | | 产物 | 平台 |
| --- | --- | | --- | --- |
| `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon | | `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) |
| `dist/win-x64/EarthModelStudio.exe` | Windows x64 | | `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` |
| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM | | `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 |
均为自包含单文件启动器,**发布包内不含模型**。改完模型: 平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe`
`./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。 会被挪到 `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`。
两种都能被客户端识别,客户端下次启动就会看到更新。
## 模型契约 ## 模型契约
@@ -134,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)。 详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。
@@ -143,7 +266,7 @@ public interface IModelContext
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口 - 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集 - 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
- 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义 - 所有由启动器打开的窗口(模型窗、加载窗、确认框、更新窗)都是 16px 圆角
## 地球模型(model/_engine + model/<id>/src) ## 地球模型(model/_engine + model/<id>/src)
@@ -155,20 +278,12 @@ public interface IModelContext
**没有节气定位**(节气属于公转) **没有节气定位**(节气属于公转)
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期) - **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期)
- **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮; - **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮;
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**, 所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**
俯视角只由「俯视」按钮显式切换
- **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明; - **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明;
右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位; 右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位;
快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角 快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角
- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数
## 模型源(手动导入)
除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库:
**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档,
失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`。
## 启动时运行内存分配 ## 启动时运行内存分配
设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb` 设置页的「启动时运行内存分配」类似启动器的 `-Xmx`:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。 交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。
+6 -73
View File
@@ -1,75 +1,8 @@
# --------------------------------------------------------------------------- try {
# Earth Model Studio 构建入口(Windows PowerShell,薄封装) & (Join-Path $PSScriptRoot 'buildps1/build.ps1') @args
# 实际代码在 buildsh/ 里。Windows 上若无 sh,则走内置的最小实现。 exit 0
# .\build.ps1 build | check | models | stamp | run | test | clean | doctor
# ---------------------------------------------------------------------------
param(
[Parameter(Position = 0)]
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
'run','test','update-test','clean','doctor','dist')]
[string]$Task = 'build'
)
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
Set-Location $Root
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
$StampProj= 'model/_engine/VersionStamp/VersionStamp.csproj'
$Sln = 'EarthModelStudio.sln'
$Version = ([regex]::Match((Get-Content Directory.Build.props -Raw), '<Version>(.*?)</Version>')).Groups[1].Value
if (-not $Version) { $Version = '1.0.0' }
New-Item -ItemType Directory -Force -Path "$Root/build/logs" | Out-Null
# 优先复用 buildsh 的 shell 实现(Git Bash / WSL / sh 可用时)
$sh = Get-Command sh -ErrorAction SilentlyContinue
if ($sh) {
& $sh.Source "$Root/build.sh" $Task
exit $LASTEXITCODE
} }
catch {
function Stamp { dotnet run --project $StampProj -c Release -- $Root $Version } [Console]::Error.WriteLine($_)
function Build-Models { exit 1
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
$id = $_.Name
$src = Join-Path $_.FullName 'src'
if (-not (Test-Path $src)) { return }
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
if (-not $proj) { return }
dotnet build $proj.FullName -c Release
}
Stamp
}
switch ($Task) {
'build' {
Write-Host '==> 编译三平台(进度见 buildsh/lib/progress.sh,建议用 Git Bash 运行 ./build.sh build)'
Remove-Item -Recurse -Force "$Root/dist" -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Stamp
foreach ($rid in @('osx-arm64','win-x64','win-arm64')) {
dotnet publish $AppProj -c Release -r $rid --self-contained true `
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false `
-o "$Root/dist/$rid"
}
Write-Host '==> 完成(详细打包请用 ./build.sh build)'
}
'check' {
dotnet build $Sln -c Debug
$env:EMS_SELFTEST = '1'; dotnet run --project $AppProj -c Debug --no-build; Remove-Item Env:\EMS_SELFTEST
dotnet run --project $TestProj -c Debug --no-build -- "$Root/build/screenshots"
}
'models' { Build-Models }
'stamp' { Stamp }
'pack-models' { Build-Models }
'pack-launcher' { Write-Host '请用 ./build.sh pack-launcher' }
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
'clean' { Remove-Item -Recurse -Force "$Root/build","$Root/dist" -ErrorAction SilentlyContinue; Write-Host '==> 已清理' }
'doctor' { dotnet --info | Select-Object -First 20 }
'dist' { Get-ChildItem "$Root/dist" -ErrorAction SilentlyContinue }
} }
+5 -4
View File
@@ -1,6 +1,6 @@
#!/bin/sh #!/bin/sh
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Earth Model Studio 构建入口(薄封装) # GC 构建入口(薄封装)
# #
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条 # ./build.sh build 完整发布(原 publish),带 apt 风格进度条
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物 # ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
@@ -21,11 +21,12 @@ export AVALONIA_TELEMETRY_OPTOUT=1
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR" cd "$ROOT_DIR"
APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj" APP_PROJ="GC-BOOT/GC-BOOT.csproj"
SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj"
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj" PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj" STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj" TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj"
SLN="EarthModelStudio.sln" SLN="GC.sln"
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1) VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION="1.0.0" [ -n "$VERSION" ] || VERSION="1.0.0"
+45
View File
@@ -0,0 +1,45 @@
function Invoke-BuildCheck {
Initialize-BuildProgress @('编译检查', '模型自检', '离屏渲染', '产物检查')
$failures = [System.Collections.Generic.List[string]]::new()
try {
Start-BuildStep '编译检查'
try { Invoke-LoggedDotNet -Name 'check-build' -Arguments @('build', $script:Solution, '-c', 'Debug', '-v', 'quiet') }
catch { $failures.Add('编译失败,见 build/logs/check-build.log'); Write-Host "!! $($failures[-1])" }
Complete-BuildStep
Start-BuildStep '模型自检'
$previousSelfTest = $env:EMS_SELFTEST
try {
$env:EMS_SELFTEST = '1'
Invoke-LoggedDotNet -Name 'check-selftest' -Arguments @('run', '--project', $script:AppProject, '-c', 'Debug', '--no-build')
if (Select-String -Path 'build/logs/check-selftest.log' -Pattern 'FAIL' -Quiet) {
$failures.Add('模型自检有失败项')
Write-Host "!! $($failures[-1])"
}
}
catch { $failures.Add('模型自检异常'); Write-Host "!! $($failures[-1])" }
finally { $env:EMS_SELFTEST = $previousSelfTest }
Complete-BuildStep
Start-BuildStep '离屏渲染'
try {
New-Item -ItemType Directory -Force -Path 'build/screenshots' | Out-Null
Invoke-LoggedDotNet -Name 'check-render' -Arguments @('run', '--project', $script:TestProject, '-c', 'Debug', '--no-build', '--', (Join-Path $script:BuildRoot 'build/screenshots'))
}
catch { $failures.Add('离屏渲染失败,见 build/logs/check-render.log'); Write-Host "!! $($failures[-1])" }
Complete-BuildStep
Start-BuildStep '产物检查'
$packageCount = @(Get-ChildItem 'dist' -Filter "GC-$script:BuildVersion-*.zip" -ErrorAction SilentlyContinue).Count
if ($packageCount -lt 3) {
$failures.Add("产物不足 3 个(当前 $packageCount)")
Write-Host "!! $($failures[-1])"
}
Complete-BuildStep
}
finally { Complete-BuildProgress }
if ($failures.Count -eq 0) { Write-Host '==> 全部通过'; return }
Write-Host '==> 有失败项'
throw ($failures -join "`n")
}
+28
View File
@@ -0,0 +1,28 @@
function Invoke-BuildTool {
param([Parameter(Mandatory)][string]$Name)
switch ($Name) {
'models' { Build-Models }
'stamp' { Invoke-VersionStamp }
'pack-models' { Build-Models; Pack-Models }
'pack-launcher'{ Pack-Launcher }
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
'clean' {
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
foreach ($projectRoot in @('GC', 'GC-BOOT', 'GC-DRAW', 'model')) {
$path = Join-Path $script:BuildRoot $projectRoot
if (Test-Path $path) {
Get-ChildItem $path -Directory -Recurse -Force | Where-Object Name -in @('bin', 'obj') | Sort-Object FullName -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
}
Write-Host '==> 已清理'
}
'doctor' { & dotnet --info | Select-Object -First 20; if ($LASTEXITCODE -ne 0) { throw "dotnet --info 失败,退出码 $LASTEXITCODE" } }
'dist' {
Write-Host '==> dist 产物:'
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -ErrorAction SilentlyContinue | Select-Object Name, Length
}
default { throw "未知任务:$Name" }
}
}
+47
View File
@@ -0,0 +1,47 @@
param(
[Parameter(Position = 0)]
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
'run','test','update-test','clean','doctor','dist')]
[string]$Task = 'build',
[string]$Version = ''
)
$ErrorActionPreference = 'Stop'
$script:BuildRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
$script:AppProject = 'GC-BOOT/GC-BOOT.csproj'
$script:PreviewProject = 'model/_engine/PreviewGen/PreviewGen.csproj'
$script:StampProject = 'model/_engine/VersionStamp/VersionStamp.csproj'
$script:TestProject = 'GC/src/test/dotnet/GC.Tests/GC.Tests.csproj'
$script:Solution = 'GC.sln'
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
Push-Location $script:BuildRoot
try {
$props = [xml](Get-Content 'Directory.Build.props' -Raw)
$versionNode = $props.SelectSingleNode('/Project/PropertyGroup/Version')
if (-not $Version) { $Version = $versionNode.InnerText }
if (-not $Version) { $Version = '1.0.0' }
$script:BuildVersion = $Version
if ($PSBoundParameters.ContainsKey('Version')) {
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
$versionNode.InnerText = $Version
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
Write-Host "==> 版本号设为 $Version"
}
New-Item -ItemType Directory -Force -Path 'build/logs' | Out-Null
. (Join-Path $PSScriptRoot 'lib/Progress.ps1')
. (Join-Path $PSScriptRoot 'lib/Build-Funcs.ps1')
. (Join-Path $PSScriptRoot 'Build-Check.ps1')
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
switch ($Task) {
'build' { Invoke-FullBuild }
'check' { Invoke-BuildCheck }
default { Invoke-BuildTool $Task }
}
}
finally {
Pop-Location
}
+343
View File
@@ -0,0 +1,343 @@
function Invoke-LoggedDotNet {
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][string[]]$Arguments
)
$logPath = Join-Path $script:BuildRoot "build/logs/$Name.log"
& dotnet @Arguments *> $logPath
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
Get-Content $logPath | Write-Host
throw "dotnet $($Arguments -join ' ') 失败,退出码 $exitCode;日志:$logPath"
}
}
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 {
Write-Host '==> 编译模型功能程序集(源码位于各模型目录的 src/)'
Get-ChildItem (Join-Path $script:BuildRoot 'model') -Directory | ForEach-Object {
$modelId = $_.Name
$sourceDir = Join-Path $_.FullName 'src'
if (-not (Test-Path $sourceDir)) { return }
$project = Get-ChildItem $sourceDir -Filter '*.csproj' | Select-Object -First 1
if ($null -eq $project) { return }
Invoke-LoggedDotNet -Name "model-$modelId" -Arguments @('build', $project.FullName, '-c', 'Release')
$packageDir = Join-Path $_.FullName "$modelId.model"
$outputDir = Join-Path $sourceDir 'bin/Release/net8.0'
if (Test-Path $packageDir) {
Get-ChildItem $outputDir -Filter '*.dll' -ErrorAction SilentlyContinue | Where-Object Name -ne 'GC.ModelSdk.dll' | ForEach-Object {
Copy-Item $_.FullName (Join-Path $packageDir $_.Name) -Force
Write-Host " -> model/$modelId/$modelId.model/$($_.Name)"
}
}
}
Write-Host '==> 用模型自己的渲染器生成封面'
Invoke-LoggedDotNet -Name 'preview' -Arguments @('run', '--project', $script:PreviewProject, '-c', 'Release', '--', $script:BuildRoot)
Invoke-VersionStamp
}
function Prepare-RuntimeLayout {
param([Parameter(Mandatory)][string]$RelativePath)
$destination = Join-Path $script:BuildRoot $RelativePath
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'), (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,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
'@
$settingsPath = Join-Path $destination '.GC/config/settings.json'
if (-not (Test-Path $settingsPath)) {
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"requireSignedManifest": true,
"updateRepository": "https://gitcode.com/Morris_1/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
}
'@
}
Write-Host " 运行目录 -> $RelativePath/.GC"
}
function Publish-Rid {
param(
[Parameter(Mandatory)][string]$Rid,
[Parameter(Mandatory)][string]$Output,
[bool]$SingleFile = $true
)
$outputPath = Join-Path $script:BuildRoot $Output
Remove-Item $outputPath -Recurse -Force -ErrorAction SilentlyContinue
$singleValue = $SingleFile.ToString().ToLowerInvariant()
Write-Host "==> 编译 $Rid (single-file=$singleValue) -> $Output"
Invoke-LoggedDotNet -Name "publish-$($Rid -replace '-', '')" -Arguments @(
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
"-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
}
function Pack-Models {
$zipPath = Join-Path $script:BuildRoot "dist/models-$script:BuildVersion.zip"
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
Write-Host "==> 打包模型数据 -> dist/models-$script:BuildVersion.zip"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$modelRoot = Join-Path $script:BuildRoot 'model'
$archive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
try {
Get-ChildItem $modelRoot -File -Recurse | Where-Object {
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
$_.Name -ne '.DS_Store' -and
$_.Extension -ne '.user' -and
$relativePath -notmatch '(^|/)(bin|obj)/'
} | ForEach-Object {
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
$archive, $_.FullName, "model/$relativePath", [System.IO.Compression.CompressionLevel]::Optimal
) | Out-Null
}
}
finally { $archive.Dispose() }
Get-Item $zipPath | Select-Object Name, Length
}
function Pack-Launcher {
$dist = Join-Path $script:BuildRoot 'dist'
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
# 产物落点 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 }
# 注意排除守护进程: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 }
$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'
if (Test-Path $macApp) {
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
Move-Item $macApp $finalApp
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
$plist = Join-Path $finalApp 'Contents/Info.plist'
if ((Test-Path $plist) -and (Test-Path '/usr/libexec/PlistBuddy')) {
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
}
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
}
# 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
}
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
}
else {
Compress-Archive -Path $_.FullName -DestinationPath $zipPath -CompressionLevel Optimal
}
Write-Host " -> dist/$label/$($_.BaseName).zip"
}
# 原始产物(.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 -LauncherOnly
Write-Host '==> dist 可发布 zip:'
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
function Remove-IntermediateDirectories {
# 平台目录里只留最终 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
}
function New-MacAppBundle {
$dist = Join-Path $script:BuildRoot 'dist/mac-arm64'
$app = Join-Path $dist 'GC.app'
Remove-Item $app -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $app 'Contents/MacOS'), (Join-Path $app 'Contents/Resources') | Out-Null
$plist = @"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleName</key><string>GC</string>
<key>CFBundleDisplayName</key><string>GC</string>
<key>CFBundleIdentifier</key><string>cn.neorf.GC</string>
<key>CFBundleVersion</key><string>$script:BuildVersion</string>
<key>CFBundleShortVersionString</key><string>$script:BuildVersion</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>GC</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
"@
Set-Content -Path (Join-Path $app 'Contents/Info.plist') -Encoding UTF8 -Value $plist
Get-ChildItem $dist -Force | Where-Object Name -notin @('GC.app', '.DS_Store') | Move-Item -Destination (Join-Path $app 'Contents/MacOS')
Remove-Item (Join-Path $app 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
$binary = Join-Path $app 'Contents/MacOS/GC'
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
$iconSource = Join-Path $script:BuildRoot 'GC/src/Assets/icon-1024.png'
if ((Test-Path $iconSource) -and (Get-Command iconutil -ErrorAction SilentlyContinue) -and (Get-Command sips -ErrorAction SilentlyContinue)) {
$iconset = Join-Path $dist 'AppIcon.iconset'
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $iconset | Out-Null
foreach ($size in @(16, 32, 64, 128, 256, 512)) {
& sips -z $size $size $iconSource --out (Join-Path $iconset "icon_${size}x${size}.png") *> $null
$doubleSize = $size * 2
& sips -z $doubleSize $doubleSize $iconSource --out (Join-Path $iconset "icon_${size}x${size}@2x.png") *> $null
}
$iconFile = Join-Path $app 'Contents/Resources/AppIcon.icns'
& iconutil -c icns $iconset -o $iconFile
if ($LASTEXITCODE -eq 0) {
$infoPlist = Join-Path $app 'Contents/Info.plist'
if (Test-Path '/usr/libexec/PlistBuddy') {
& /usr/libexec/PlistBuddy -c 'Add :CFBundleIconFile string AppIcon' $infoPlist 2>$null
}
}
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host "==> 已打包 $app"
}
function Invoke-FullBuild {
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
try {
Start-BuildStep '清理旧产物'
Remove-Item (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
Complete-BuildStep
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-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-amd64'
Prepare-RuntimeLayout 'dist/win-arm64'
Prepare-RuntimeLayout 'dist/mac-arm64/GC.app/Contents/MacOS'
Complete-BuildStep
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
Start-BuildStep '收尾'; Complete-BuildStep
Write-Host '==> 完成,产物:'
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
finally { Complete-BuildProgress }
}
+27
View File
@@ -0,0 +1,27 @@
$script:ProgressSteps = @()
$script:ProgressIndex = 0
$script:ProgressActivity = 'GC 构建'
function Initialize-BuildProgress {
param([string[]]$Steps)
$script:ProgressSteps = $Steps
$script:ProgressIndex = 0
Write-Progress -Activity $script:ProgressActivity -Status '准备' -PercentComplete 0
}
function Start-BuildStep {
param([string]$Name)
$script:ProgressIndex++
$percent = [math]::Min(99, [int](($script:ProgressIndex - 1) * 100 / [math]::Max(1, $script:ProgressSteps.Count)))
Write-Progress -Activity $script:ProgressActivity -Status $Name -PercentComplete $percent
Write-Host "==> $Name"
}
function Complete-BuildStep {
$percent = [int]($script:ProgressIndex * 100 / [math]::Max(1, $script:ProgressSteps.Count))
Write-Progress -Activity $script:ProgressActivity -Status '进行中' -PercentComplete $percent
}
function Complete-BuildProgress {
Write-Progress -Activity $script:ProgressActivity -Completed
}
+9 -4
View File
@@ -11,6 +11,11 @@ bs_build() {
progress_step "清理旧产物"; progress_tick 100 progress_step "清理旧产物"; progress_tick 100
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist" 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 progress_step "版本戳"; progress_tick 100
stamp_versions stamp_versions
@@ -36,16 +41,16 @@ bs_build() {
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1 _run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
progress_step "编译 Win-x64" 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" progress_step "编译 Win-arm64"
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1 _run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
progress_step "运行骨架"; progress_tick 100 progress_step "运行骨架"; progress_tick 100
package_mac_app 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/win-arm64"
prepare_runtime_layout "dist/mac-arm64/EarthModelStudio.app/Contents/MacOS" prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
progress_step "打包 zip"; progress_tick 100 progress_step "打包 zip"; progress_tick 100
pack_launcher pack_launcher
@@ -53,5 +58,5 @@ bs_build() {
progress_step "收尾"; progress_tick 100 progress_step "收尾"; progress_tick 100
progress_done progress_done
echo "==> 完成,产物:" 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
} }
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more