添加GC-SAVEDOG项目,降低隐患
This commit is contained in:
1 parent
791db4fe12
commit
2f3a8682c9
54 files changed
+3642
-320
No files matched your search
@@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
private string? _rawManifest;
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
@@ -26,9 +28,20 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<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)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
@@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
|
||||
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!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
string full;
|
||||
try { full = SafePath(rel); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
|
||||
}
|
||||
|
||||
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
|
||||
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
|
||||
var fromDist = FindInDist(package);
|
||||
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
|
||||
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
@@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 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)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
|
||||
@@ -86,13 +86,19 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
|
||||
// 但模型清单仍然有效,保证模型能正常同步。
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
|
||||
if (version != null)
|
||||
// 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256,
|
||||
// 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。
|
||||
// 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
var n = version?.Launcher.Packages.Count ?? 0;
|
||||
if (v.Length == 0 || n == 0)
|
||||
{
|
||||
version.Launcher.Version = "";
|
||||
version.Launcher.Packages.Clear();
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
@@ -120,6 +126,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
_content.SetLauncherVersion(latest.Version);
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
|
||||
+150
-17
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
@@ -27,6 +28,9 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
private string? _rawManifest;
|
||||
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
@@ -77,9 +81,24 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return version;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
string text;
|
||||
@@ -107,10 +126,20 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
||||
payload, GC.Services.Json.Options);
|
||||
|
||||
// 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
|
||||
var version = ManifestLoader.Parse(payload, out var verification);
|
||||
if (version == null) return null;
|
||||
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
||||
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
|
||||
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
|
||||
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
|
||||
_rawManifest = payload;
|
||||
return version;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -283,25 +312,129 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
||||
// 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
|
||||
var direct = await TryFetchAsync(package.Url, package.Sha256, ct);
|
||||
if (direct != null) return direct;
|
||||
|
||||
// url 不可用或校验不符:再去找仓库里的编译产物。
|
||||
// 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。
|
||||
// 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个,
|
||||
// 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。
|
||||
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||
{
|
||||
try
|
||||
var url = await ResolveFileUrlAsync(path, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||
{
|
||||
var url = await FindZipInDirAsync(dir, package, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
if (bytes.Length == 0) return null;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
||||
url = dl.GetString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
|
||||
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static string Short(string url)
|
||||
=> url.Length <= 96 ? url : url[..60] + "…" + url[^24..];
|
||||
|
||||
/// <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)
|
||||
|
||||
@@ -23,6 +23,7 @@ public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
private string? _rawManifest;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
@@ -69,7 +70,18 @@ public sealed class GiteaRemote : IModelRemote
|
||||
// Release 提供启动器版本与平台附件
|
||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||
foreach (var kv in fromRelease.Launcher.Packages)
|
||||
{
|
||||
// Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256,
|
||||
// 否则「有仓库写权限的人发个 Release」就能绕过验签。
|
||||
if (fromRepo != null &&
|
||||
fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) &&
|
||||
!string.IsNullOrWhiteSpace(signed?.Sha256))
|
||||
{
|
||||
kv.Value.Sha256 = signed!.Sha256;
|
||||
if (signed.Size > 0) kv.Value.Size = signed.Size;
|
||||
}
|
||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -81,6 +93,10 @@ public sealed class GiteaRemote : IModelRemote
|
||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||
return result.Models.Count > 0 ? result : null;
|
||||
}
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -90,8 +106,14 @@ public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
|
||||
if (doc != null) return doc;
|
||||
var doc = ManifestLoader.Parse(text, out var verification);
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
|
||||
if (doc != null)
|
||||
{
|
||||
_rawManifest = text;
|
||||
return doc;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -282,12 +304,35 @@ public sealed class GiteaRemote : IModelRemote
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(package.Url)) return null;
|
||||
try { return await Http.GetByteArrayAsync(package.Url, ct); }
|
||||
catch (Exception ex)
|
||||
// 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
|
||||
// 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
|
||||
var candidates = new List<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}");
|
||||
return null;
|
||||
byte[] bytes;
|
||||
try { bytes = await Http.GetByteArrayAsync(candidate, ct); }
|
||||
catch (Exception) { continue; }
|
||||
if (bytes.Length == 0) continue;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(package.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(
|
||||
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
|
||||
return bytes;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 平台标签与「仓库里的编译产物位置」的推导规则。
|
||||
///
|
||||
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
|
||||
/// 提交(或上传)到仓库的 <c>dist/<系统>-<架构></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/<标签></c> 与 <c>dist/<RID></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;
|
||||
}
|
||||
}
|
||||
+130
-32
@@ -303,48 +303,120 @@ public static class LauncherUpdater
|
||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||
return Fail($"该平台({rid})没有对应发布包");
|
||||
|
||||
// ---- 信任闸门 ---------------------------------------------------
|
||||
// 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。
|
||||
// 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。
|
||||
var allowUnsigned =
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!version.IsTrusted && !allowUnsigned)
|
||||
{
|
||||
var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效"
|
||||
: "清单未签名";
|
||||
Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}");
|
||||
return Fail($"{reason},已拒绝下载启动器更新");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新");
|
||||
return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||
|
||||
// sha256 校验(Release 提供时)
|
||||
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
// sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义)
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Fail("下载文件校验失败(sha256 不符)");
|
||||
return Fail("下载文件校验失败(sha256 与已签名清单不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压更新包" });
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.55, Stage = "正在校验更新包" });
|
||||
|
||||
// 更新包先完整保存在下载目录,重启替换脚本再移入安装目录。
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
var updateRoot = paths.UpdateRoot;
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
|
||||
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
|
||||
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
|
||||
// 避免「解压后被替换」的中间窗口。
|
||||
var zip = Path.Combine(updateRoot, "package.zip");
|
||||
if (File.Exists(zip)) File.Delete(zip);
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try { ZipSafety.ExtractToDirectory(zip, staging); }
|
||||
finally { try { File.Delete(zip); } catch { } }
|
||||
|
||||
// 只展平「单个非 .app 顶层目录」的 zip
|
||||
FlattenStaging(staging);
|
||||
try
|
||||
{
|
||||
var inspection = SafeArchive.Inspect(zip);
|
||||
Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { File.Delete(zip); } catch { }
|
||||
return Fail("更新包安全性检查失败: " + ex.Message);
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在暂存新版本" });
|
||||
// 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了"
|
||||
var rawManifest = await remote.GetRawVersionTextAsync(ct);
|
||||
var manifestCopy = Path.Combine(updateRoot, "version.json");
|
||||
if (!string.IsNullOrWhiteSpace(rawManifest))
|
||||
File.WriteAllText(manifestCopy, rawManifest!);
|
||||
else if (File.Exists(manifestCopy))
|
||||
File.Delete(manifestCopy);
|
||||
|
||||
var payload = Path.Combine(paths.UpdateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
Directory.CreateDirectory(payload);
|
||||
var packageName = MoveToPayload(staging, payload);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
|
||||
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
|
||||
|
||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
||||
Directory.CreateDirectory(paths.UpdateRoot);
|
||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||
$"INSTALL_REL={Path.GetRelativePath(paths.UpdateRoot, paths.InstallDirectory)}\n");
|
||||
var request = new SavedogRequest
|
||||
{
|
||||
Version = latest,
|
||||
Rid = rid,
|
||||
PlatformLabel = PlatformLabel,
|
||||
PackageName = packageName,
|
||||
PackageZip = "package.zip",
|
||||
PayloadDir = "payload",
|
||||
ManifestPath = "version.json",
|
||||
PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(),
|
||||
PackageSize = bytes.LongLength,
|
||||
RequireSignature = version.IsTrusted,
|
||||
InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory),
|
||||
CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
|
||||
// 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换
|
||||
string? legacyPath = null;
|
||||
if (SavedogLauncher.Find(paths) == null)
|
||||
{
|
||||
Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程");
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" });
|
||||
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
SafeArchive.ExtractToDirectory(zip, staging);
|
||||
FlattenStaging(staging);
|
||||
|
||||
var payload = Path.Combine(updateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
Directory.CreateDirectory(payload);
|
||||
var legacyName = MoveToPayload(staging, payload);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
packageName = legacyName;
|
||||
request.PackageName = legacyName;
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
legacyPath = Path.Combine(payload, legacyName);
|
||||
|
||||
// 老脚本读这个纯文本标记,只含相对信息
|
||||
File.WriteAllText(Path.Combine(updateRoot, "update.txt"),
|
||||
$"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||
$"INSTALL_REL={request.InstallRelative}\n");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
@@ -354,7 +426,7 @@ public static class LauncherUpdater
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已暂存到 .GC/update",
|
||||
PackageName = packageName,
|
||||
NewAppPath = Path.Combine(payload, packageName)
|
||||
NewAppPath = legacyPath
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
@@ -370,15 +442,13 @@ public static class LauncherUpdater
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 生成替换脚本并启动。脚本等本进程退出后:
|
||||
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
|
||||
/// 安排应用已下载的新版。
|
||||
/// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
|
||||
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
@@ -386,6 +456,17 @@ public static class LauncherUpdater
|
||||
return false;
|
||||
}
|
||||
|
||||
if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest)))
|
||||
{
|
||||
string? savedogError = null;
|
||||
if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError))
|
||||
return true;
|
||||
Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本");
|
||||
}
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
try
|
||||
{
|
||||
var isWin = OperatingSystem.IsWindows();
|
||||
@@ -420,13 +501,30 @@ public static class LauncherUpdater
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
|
||||
/// <summary>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths)
|
||||
{
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
// 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签)
|
||||
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||
if (File.Exists(requestPath))
|
||||
{
|
||||
var request = Json.Read<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");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -104,6 +104,37 @@ public sealed class UpdateService : IUpdateService
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
// ---- 清单信任策略 --------------------------------------------------
|
||||
// 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。
|
||||
// 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。
|
||||
var allowUnsigned = devMode ||
|
||||
!_settings.Current.RequireSignedManifest ||
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!remote.IsTrusted)
|
||||
{
|
||||
var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效(内容可能被篡改)"
|
||||
: "清单未签名";
|
||||
|
||||
if (!allowUnsigned)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {reason},已拒绝本次更新");
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = $"{reason},已拒绝更新",
|
||||
Error = remote.SignatureError
|
||||
};
|
||||
}
|
||||
|
||||
Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})");
|
||||
}
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
@@ -248,6 +279,22 @@ public sealed class UpdateService : IUpdateService
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 --------
|
||||
// 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。
|
||||
var computed = ModelIntegrity.Compute(staging, model.Id);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.ManifestSha256) &&
|
||||
!string.Equals(computed.ManifestSha256, model.ManifestSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.FilesSha256) &&
|
||||
!string.Equals(computed.FilesSha256, model.FilesSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃");
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
@@ -270,6 +317,25 @@ public sealed class UpdateService : IUpdateService
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
// 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次
|
||||
try
|
||||
{
|
||||
ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile
|
||||
{
|
||||
Id = model.Id,
|
||||
Version = model.Version,
|
||||
ManifestSha256 = computed.ManifestSha256,
|
||||
FilesSha256 = computed.FilesSha256,
|
||||
Files = computed.Files,
|
||||
InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Source = _remote.DisplayName
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -283,4 +349,7 @@ public sealed class UpdateService : IUpdateService
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
|
||||
private static string Short(string? hash)
|
||||
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
|
||||
}
|
||||
@@ -1,36 +1,22 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
|
||||
/// 并在解压前逐条校验目标路径完整落在目标目录内。
|
||||
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
|
||||
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
|
||||
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using (var archive = ZipFile.OpenRead(zipPath))
|
||||
{
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
|
||||
(name.Length >= 2 && name[1] == ':'))
|
||||
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
}
|
||||
}
|
||||
|
||||
// 校验通过后交给框架解压(保留 overwrite 语义)
|
||||
ZipFile.ExtractToDirectory(zipPath, destination, true);
|
||||
if (!File.Exists(zipPath))
|
||||
throw new FileNotFoundException("压缩包不存在", zipPath);
|
||||
SafeArchive.ExtractToDirectory(zipPath, destination);
|
||||
}
|
||||
|
||||
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
|
||||
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
|
||||
}
|
||||
Reference in new issue
Block a user