添加GC-SAVEDOG项目,降低隐患

This commit is contained in:
2509_92447106 committed 2026-11-14 19:42:02 +08:00
1 parent 791db4fe12
commit 2f3a8682c9
54 files changed
+3642 -320

No files matched your search

+29 -1
View File
@@ -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
View File
@@ -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);
}
}
+64 -1
View File
@@ -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;
+48
View File
@@ -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>模型清单 &lt;id&gt;.json 的 sha256。</summary>
public string? ManifestSha256 { get; set; }
/// <summary>&lt;id&gt;.model 目录的目录指纹(算法见 ContentHash)。</summary>
public string? FilesSha256 { get; set; }
/// <summary>参与分发的文件数。</summary>
public int Files { get; set; }
}
/// <summary>远端目录树里的一个条目。</summary>
@@ -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