添加GC-SAVEDOG项目,降低隐患
This commit is contained in:
1 parent
791db4fe12
commit
2f3a8682c9
54 files changed
+3642
-320
No files matched your search
@@ -35,6 +35,11 @@ public partial class App : Application
|
||||
var window = new MainWindow();
|
||||
window.Show();
|
||||
|
||||
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
|
||||
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
|
||||
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion);
|
||||
|
||||
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
|
||||
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
|
||||
// 会导致 DataContext 一直是 null、主页面白屏。
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"home.installed": "Installed models",
|
||||
"home.count": "{0} models",
|
||||
"home.empty": "No models yet",
|
||||
"home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
|
||||
"home.emptyHint": "Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.",
|
||||
"home.emptyAction": "Get models",
|
||||
"home.open": "Open folder",
|
||||
"home.delete": "Delete",
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"home.installed": "已安装模型",
|
||||
"home.count": "{0} 个模型",
|
||||
"home.empty": "模型库还是空的",
|
||||
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
|
||||
"home.emptyHint": "启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。",
|
||||
"home.emptyAction": "去下载模型",
|
||||
"home.open": "打开目录",
|
||||
"home.delete": "删除",
|
||||
|
||||
@@ -46,6 +46,12 @@ public sealed class AppSettings
|
||||
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
|
||||
public string? UpdateLocalRoot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 要求版本清单必须带**有效签名**。默认开启:关闭后只警告不拦截,
|
||||
/// 等于放弃「清单被篡改」的防护,只建议在自建私有构建里临时关闭。
|
||||
/// </summary>
|
||||
public bool RequireSignedManifest { get; set; } = true;
|
||||
|
||||
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
|
||||
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 升序,对每个文件拼接
|
||||
/// "<相对路径>\0<fileHash>\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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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><id>.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><id>.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><id>.json</c> 与
|
||||
/// <c><id>.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);
|
||||
}
|
||||
}
|
||||
@@ -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 { /* 权限位设置失败不影响文件内容 */ }
|
||||
}
|
||||
}
|
||||
@@ -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 <自己>
|
||||
/// -> 自己退出
|
||||
///
|
||||
/// 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");
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,11 @@ public sealed class AppPaths
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
|
||||
|
||||
/// <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 IsPortableModelRoot { get; private init; }
|
||||
@@ -247,10 +251,13 @@ public sealed class AppPaths
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(ConfigRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
MigrateLegacySettings();
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
|
||||
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
@@ -264,6 +271,27 @@ public sealed class AppPaths
|
||||
|
||||
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
|
||||
|
||||
/// <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
|
||||
|
||||
+32
-2
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
@@ -17,10 +19,21 @@ public static class Json
|
||||
ReadCommentHandling = JsonCommentHandling.Skip
|
||||
};
|
||||
|
||||
/// <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 JsonSerializer.Deserialize<T>(System.IO.File.ReadAllText(path), Options);
|
||||
return Deserialize<T>(System.IO.File.ReadAllText(path));
|
||||
}
|
||||
|
||||
public static void Write<T>(string path, T value)
|
||||
@@ -28,7 +41,24 @@ public static class Json
|
||||
var dir = System.IO.Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
|
||||
var tmp = path + ".tmp";
|
||||
System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options));
|
||||
System.IO.File.WriteAllText(tmp, Serialize(value));
|
||||
System.IO.File.Move(tmp, path, true);
|
||||
}
|
||||
|
||||
public static T? Deserialize<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);
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,40 @@ public sealed class ModelHost
|
||||
|
||||
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;
|
||||
if (!File.Exists(assemblyPath))
|
||||
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
|
||||
@@ -89,7 +123,8 @@ public sealed class ModelHost
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
|
||||
"请更新到匹配的版本");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
@@ -118,6 +153,34 @@ public sealed class ModelHost
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <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 readonly ModelLoadContext _context;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -15,6 +16,20 @@ public sealed class RepoVersion
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<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
|
||||
@@ -34,6 +49,19 @@ public sealed class RepoPackage
|
||||
public long Size { get; set; }
|
||||
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
|
||||
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
|
||||
@@ -42,6 +70,20 @@ public sealed class RepoModel
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
|
||||
// ---- 完整性(由 VersionStamp 计算,签名覆盖这几个字段) ----------------
|
||||
|
||||
/// <summary>内容指纹(构建溯源,不参与版本比较)。</summary>
|
||||
public string? Build { get; set; }
|
||||
|
||||
/// <summary>模型清单 <id>.json 的 sha256。</summary>
|
||||
public string? ManifestSha256 { get; set; }
|
||||
|
||||
/// <summary><id>.model 目录的目录指纹(算法见 ContentHash)。</summary>
|
||||
public string? FilesSha256 { get; set; }
|
||||
|
||||
/// <summary>参与分发的文件数。</summary>
|
||||
public int Files { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
@@ -71,6 +113,12 @@ public interface IModelRemote
|
||||
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
|
||||
Task<byte[]> DownloadAsync(RepoEntry entry, 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
|
||||
|
||||
@@ -181,6 +181,15 @@ public partial class MainViewModel : ObservableObject
|
||||
UpdateDetail = result.Error ?? "";
|
||||
LauncherNotice = result.LauncherMessage ?? "";
|
||||
|
||||
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
|
||||
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
|
||||
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
|
||||
{
|
||||
UpdateStatus = "暂时连不上模型源,模型库为空";
|
||||
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
|
||||
return;
|
||||
}
|
||||
|
||||
// 模型下载完成后本次启动就刷新列表,立刻可用
|
||||
if (result.UpdatedModels > 0) Home.Refresh();
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using GC.Models;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
@@ -81,7 +84,6 @@ internal static class Program
|
||||
var fixtureVersion = Json.Read<RepoVersion>(versionFile)!;
|
||||
fixtureVersion.Models.RemoveAll(model =>
|
||||
model.Id is not "earth-rotation" and not "earth-revolution");
|
||||
Json.Write(Path.Combine(remote, "version.json"), fixtureVersion);
|
||||
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
@@ -95,6 +97,28 @@ internal static class Program
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
|
||||
// 按远端实际内容重算完整性哈希(与 VersionStamp 同一算法),然后签名。
|
||||
// 客户端会复算这两项,不一致就拒绝安装 —— 这一步必须与构建端一致。
|
||||
foreach (var m in fixtureVersion.Models)
|
||||
{
|
||||
var computed = ModelIntegrity.Compute(Path.Combine(remote, "model", m.Id), m.Id);
|
||||
m.ManifestSha256 = computed.ManifestSha256;
|
||||
m.FilesSha256 = computed.FilesSha256;
|
||||
m.Files = computed.Files.Count;
|
||||
}
|
||||
|
||||
var signer = ManifestSignature.TryLoadPrivateKey(
|
||||
Path.Combine(repoRoot, ".signing", "gc-signing.pem"));
|
||||
if (signer == null)
|
||||
{
|
||||
Console.WriteLine("FAIL: 缺少签名私钥 .signing/gc-signing.pem,无法构造可信清单");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var remoteManifest = Path.Combine(remote, "version.json");
|
||||
WriteSigned(remoteManifest, fixtureVersion, signer);
|
||||
Console.WriteLine($"远端清单已签名({ManifestSignature.Algorithm})");
|
||||
|
||||
// EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
|
||||
Environment.SetEnvironmentVariable("EMS_HOME", tmp);
|
||||
Environment.SetEnvironmentVariable("EMS_DATA", home);
|
||||
@@ -119,7 +143,7 @@ internal static class Program
|
||||
Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model");
|
||||
Check(paths.CacheRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "模型与启动器下载暂存位于 .GC/cache");
|
||||
Check(paths.UpdateRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "启动器更新位于 .GC/update");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/config/settings.json 已创建");
|
||||
|
||||
// 1) 首次启动:模型全部下载并立即落地
|
||||
var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
@@ -140,7 +164,7 @@ internal static class Program
|
||||
Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
|
||||
|
||||
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效
|
||||
var rv = Json.Read<RepoVersion>(Path.Combine(remote, "version.json"))!;
|
||||
var rv = Json.Read<RepoVersion>(remoteManifest)!;
|
||||
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
|
||||
"version.json 里模型版本由构建自动生成");
|
||||
var changed = rv.Models[0];
|
||||
@@ -148,12 +172,21 @@ internal static class Program
|
||||
var stampName = "_version-stamp.txt";
|
||||
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
|
||||
changed.Id + ".model", stampName), "new content");
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
|
||||
// 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
|
||||
var changedHash = ModelIntegrity.Compute(Path.Combine(remote, "model", changed.Id), changed.Id);
|
||||
changed.ManifestSha256 = changedHash.ManifestSha256;
|
||||
changed.FilesSha256 = changedHash.FilesSha256;
|
||||
changed.Files = changedHash.Files.Count;
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var r3 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
|
||||
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)),
|
||||
"新版本本次启动立即生效");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")),
|
||||
"安装后写入完整性记录");
|
||||
|
||||
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
|
||||
var rid = LauncherRuntimeInfo.CurrentRid;
|
||||
@@ -165,8 +198,13 @@ internal static class Program
|
||||
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
||||
ZipFile.CreateFromDirectory(stage, zip);
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage { Url = zip };
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 造一个旧版在当前目录
|
||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
|
||||
@@ -200,7 +238,60 @@ internal static class Program
|
||||
Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除");
|
||||
}
|
||||
|
||||
// 6) 断网兜底:保留本地模型,不清空
|
||||
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
||||
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
||||
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
||||
Directory.CreateDirectory(distDir);
|
||||
var distName = "GC-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
||||
var distZip = Path.Combine(distDir, distName);
|
||||
File.Copy(zip, distZip, true);
|
||||
|
||||
string Sha(string file) =>
|
||||
Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))).ToLowerInvariant();
|
||||
|
||||
rv.Launcher.Version = "9.9.10";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Dir = "dist/" + LauncherUpdater.PlatformLabel,
|
||||
Name = distName,
|
||||
Sha256 = Sha(distZip),
|
||||
Size = new FileInfo(distZip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var dlDist = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"dist 目录更新: {dlDist.Message}");
|
||||
Check(dlDist.State == UpdateRunState.Ready, "仓库 dist/<系统>-<架构>/ 里的产物能找到并下载");
|
||||
// 包名来自 zip 内容(这里仍是 9.9.9 的文件),所以要断言清单版本
|
||||
Check(dlDist.Version == "9.9.10", "下载的确实是 dist 目录里声明的那个版本");
|
||||
|
||||
// 5c) 往 dist/ 里塞一个哈希不匹配的包:必须拒绝(sha256 来自已签名清单)
|
||||
File.WriteAllText(distZip, "evil payload");
|
||||
var dlEvil = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Check(dlEvil.State == UpdateRunState.Failed, "dist 目录里哈希不符的包被拒绝");
|
||||
|
||||
// 还原到 9.9.9,后面的篡改 / 断网用例继续用这份清单
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Sha(zip),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 6) 篡改检测:改一个字节但不重新签名 -> 必须判为不可信
|
||||
var tampered = File.ReadAllText(remoteManifest).Replace("\"9.9.9\"", "\"9.9.8\"");
|
||||
var tamperResult = ManifestSignature.Verify(tampered, requireSignature: true);
|
||||
Check(tamperResult.Trust == ManifestTrust.Invalid, "被篡改的清单验签失败");
|
||||
File.WriteAllText(remoteManifest, tampered);
|
||||
var r6 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r6.Outcome == UpdateOutcome.Unavailable, "清单被篡改时拒绝更新");
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 7) 断网兜底:保留本地模型,不清空
|
||||
var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
|
||||
var beforeCount = settings.Current.InstalledModelVersions.Count;
|
||||
var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
@@ -216,6 +307,13 @@ internal static class Program
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
|
||||
Reference in new issue
Block a user