添加GC-SAVEDOG项目,降低隐患
This commit is contained in:
1 parent
791db4fe12
commit
2f3a8682c9
54 files changed
+3642
-320
No files matched your search
@@ -0,0 +1,552 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
internal sealed class ApplyOptions
|
||||
{
|
||||
public string UpdateDir { get; set; } = "";
|
||||
public string? InstallDir { get; set; }
|
||||
public int WaitPid { get; set; }
|
||||
public int TimeoutSeconds { get; set; } = 45;
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
public bool DryRun { get; set; }
|
||||
public bool Force { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
|
||||
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
|
||||
/// </summary>
|
||||
internal sealed class Applier
|
||||
{
|
||||
private static readonly Regex ArtifactPattern = new(
|
||||
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(app|exe)$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly ApplyOptions _options;
|
||||
private readonly Log _log;
|
||||
|
||||
public Applier(ApplyOptions options, Log log)
|
||||
{
|
||||
_options = options;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public int Run()
|
||||
{
|
||||
var updateDir = Path.GetFullPath(_options.UpdateDir);
|
||||
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
||||
|
||||
if (!File.Exists(requestPath))
|
||||
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3);
|
||||
|
||||
var request = Json.Read<SavedogRequest>(requestPath);
|
||||
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
||||
return Fail(updateDir, "更新申请内容不完整", 3);
|
||||
|
||||
if (!ValidName(request.PackageName))
|
||||
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3);
|
||||
|
||||
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})");
|
||||
|
||||
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
||||
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
||||
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试");
|
||||
|
||||
// 2. 安装目录定位与安全检查
|
||||
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
||||
? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative))
|
||||
: Path.GetFullPath(_options.InstallDir!);
|
||||
|
||||
if (!Directory.Exists(installDir))
|
||||
return Fail(updateDir, "安装目录不存在: " + installDir, 4);
|
||||
|
||||
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
||||
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4);
|
||||
|
||||
// 3. 二次验签:不信任「启动器说它验过了」
|
||||
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
||||
var manifestPath = Path.Combine(updateDir, request.ManifestPath);
|
||||
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||
var verification = ManifestSignature.Verify(manifestText, require);
|
||||
|
||||
if (verification.IsRejected)
|
||||
{
|
||||
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}");
|
||||
return Refuse(updateDir, request, verification);
|
||||
}
|
||||
_log.Info($"清单可信度:{verification.Trust}" +
|
||||
(verification.KeyId != null ? $"({verification.KeyId})" : ""));
|
||||
|
||||
// 4. 校验更新包
|
||||
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
||||
if (!File.Exists(zipPath))
|
||||
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5);
|
||||
|
||||
var zipInfo = new FileInfo(zipPath);
|
||||
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
||||
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5);
|
||||
|
||||
var actualSha = ContentHash.Sha256File(zipPath);
|
||||
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
||||
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
||||
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验");
|
||||
|
||||
SafeArchive.Inspection inspection;
|
||||
try
|
||||
{
|
||||
inspection = SafeArchive.Inspect(zipPath);
|
||||
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5);
|
||||
}
|
||||
|
||||
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
||||
var stage = Path.Combine(updateDir, "stage");
|
||||
ClearDirectory(stage);
|
||||
try
|
||||
{
|
||||
SafeArchive.ExtractToDirectory(zipPath, stage);
|
||||
FlattenSingleDirectory(stage);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "解压失败: " + ex.Message, 6);
|
||||
}
|
||||
|
||||
var artifact = FindArtifact(stage, request.PackageName);
|
||||
if (artifact == null)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
|
||||
}
|
||||
|
||||
var target = Path.Combine(installDir, Path.GetFileName(artifact));
|
||||
var alreadyInstalled = File.Exists(target) || Directory.Exists(target);
|
||||
|
||||
if (_options.DryRun)
|
||||
{
|
||||
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
|
||||
ClearDirectory(stage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (alreadyInstalled)
|
||||
{
|
||||
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
||||
_log.Info("目标版本已存在,视为已安装");
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PackageName = Path.GetFileName(artifact),
|
||||
Verified = true,
|
||||
Message = "目标版本已存在,无需替换"
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 6. 移入安装目录(不覆盖任何已有文件)
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(installDir);
|
||||
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
|
||||
else File.Move(artifact, target);
|
||||
_log.Info("新版已就位: " + Path.GetFileName(target));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
|
||||
}
|
||||
|
||||
// 7. 启动并看护
|
||||
var previous = ReadLastGood(updateDir);
|
||||
StartupHealth.Clear(updateDir);
|
||||
|
||||
Process? child;
|
||||
try
|
||||
{
|
||||
child = Launch(target);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
child = null;
|
||||
_log.Error("启动新版失败: " + ex.Message);
|
||||
}
|
||||
|
||||
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
||||
TimeSpan.FromSeconds(_options.TimeoutSeconds));
|
||||
|
||||
if (healthy)
|
||||
{
|
||||
_log.Info($"v{request.Version} 启动正常,更新完成");
|
||||
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
|
||||
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = "更新已应用"
|
||||
});
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 8. 回滚
|
||||
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
|
||||
TryKill(child);
|
||||
var removed = RemoveNewVersion(target);
|
||||
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
|
||||
|
||||
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "rolledback",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = restored
|
||||
? "新版本未通过启动检查,已回滚到上一个版本"
|
||||
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
||||
});
|
||||
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 8;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 校验辅助
|
||||
|
||||
private static bool ValidName(string name)
|
||||
=> name.Length > 0 && name.Length < 200 &&
|
||||
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
|
||||
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static bool WaitForExit(int pid, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(pid);
|
||||
if (process.HasExited) return true;
|
||||
}
|
||||
catch (ArgumentException) { return true; } // 进程已不存在
|
||||
catch { return true; }
|
||||
Thread.Sleep(200);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void FlattenSingleDirectory(string stage)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(stage);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var temp = stage + "-flat";
|
||||
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||
Directory.Move(inner, temp);
|
||||
Directory.Delete(stage, true);
|
||||
Directory.Move(temp, stage);
|
||||
}
|
||||
|
||||
private static string? FindArtifact(string stage, string packageName)
|
||||
{
|
||||
var direct = Path.Combine(stage, packageName);
|
||||
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
|
||||
return entry;
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
|
||||
return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 启动与看护
|
||||
|
||||
private Process? Launch(string target)
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
// .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护
|
||||
var macOs = Path.Combine(target, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
var exe = Directory.GetFiles(macOs)
|
||||
.OrderByDescending(f => Path.GetFileName(f) == "GC")
|
||||
.FirstOrDefault();
|
||||
if (exe != null)
|
||||
{
|
||||
MakeExecutable(exe);
|
||||
return StartProcess(exe, Path.GetDirectoryName(exe)!);
|
||||
}
|
||||
}
|
||||
MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC"));
|
||||
var psi = new ProcessStartInfo("open") { UseShellExecute = false };
|
||||
psi.ArgumentList.Add("-n");
|
||||
psi.ArgumentList.Add(target);
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) MakeExecutable(target);
|
||||
return StartProcess(target, Path.GetDirectoryName(target)!);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Process? StartProcess(string exe, string workingDirectory)
|
||||
{
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = workingDirectory
|
||||
};
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
private static void MakeExecutable(string path)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return;
|
||||
var mode = File.GetUnixFileMode(path);
|
||||
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||
UnixFileMode.GroupExecute |
|
||||
UnixFileMode.OtherExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
if (health != null && health.Ok && SameVersion(health.Version, version))
|
||||
{
|
||||
_log.Info($"收到健康标记(pid {health.Pid})");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (child.HasExited)
|
||||
{
|
||||
_log.Error($"新版进程已退出(退出码 {child.ExitCode})");
|
||||
return false;
|
||||
}
|
||||
Thread.Sleep(250);
|
||||
}
|
||||
|
||||
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
||||
if (!child.HasExited)
|
||||
{
|
||||
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool SameVersion(string a, string b)
|
||||
=> string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Normalize(string version)
|
||||
{
|
||||
var trimmed = version.Trim().TrimStart('v', 'V');
|
||||
var parts = trimmed.Split('.');
|
||||
var numbers = new List<string>();
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (!int.TryParse(part, out var n)) break;
|
||||
numbers.Add(n.ToString());
|
||||
}
|
||||
while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1);
|
||||
return numbers.Count == 0 ? trimmed : string.Join('.', numbers);
|
||||
}
|
||||
|
||||
private static void TryKill(Process? process)
|
||||
{
|
||||
if (process == null) return;
|
||||
try
|
||||
{
|
||||
if (!process.HasExited) process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 清理 / 回滚
|
||||
|
||||
private void CleanupOldVersions(string installDir, string keepName, string platformLabel)
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
|
||||
var platform = match.Groups["plat"].Value;
|
||||
if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_log.Info($"保留其它平台版本: {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(entry)) Directory.Delete(entry, true);
|
||||
else File.Delete(entry);
|
||||
_log.Info("清理旧版本: " + name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"清理旧版本失败 {name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoveNewVersion(string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
||||
else if (File.Exists(target)) File.Delete(target);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("移除新版失败: " + ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
||||
string platformLabel)
|
||||
{
|
||||
// 优先用上次成功的版本;否则挑一个同平台的其它版本
|
||||
var candidates = new List<string>();
|
||||
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
||||
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
candidates.Add(entry);
|
||||
}
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
||||
try
|
||||
{
|
||||
Launch(candidate);
|
||||
_log.Info("已回滚启动: " + Path.GetFileName(candidate));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 状态文件
|
||||
|
||||
private void WriteState(string updateDir, SavedogState state)
|
||||
{
|
||||
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
||||
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); }
|
||||
}
|
||||
|
||||
private int Fail(string updateDir, string message, int code)
|
||||
{
|
||||
_log.Error(message);
|
||||
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
||||
return code;
|
||||
}
|
||||
|
||||
private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification)
|
||||
{
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "refused",
|
||||
Version = request.Version,
|
||||
PackageName = request.PackageName,
|
||||
Verified = false,
|
||||
Message = $"清单验签失败:{verification.Error}"
|
||||
});
|
||||
return 2;
|
||||
}
|
||||
|
||||
private static LastGoodVersion? ReadLastGood(string updateDir)
|
||||
=> Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
|
||||
private static void WriteLastGood(string updateDir, string version, string packageName)
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion
|
||||
{
|
||||
Version = version,
|
||||
PackageName = packageName
|
||||
});
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void ClearDirectory(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try { if (File.Exists(path)) File.Delete(path); } catch { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
GC-SAVEDOG —— 启动器更新守护进程。
|
||||
|
||||
为什么不把替换逻辑留在启动器里:
|
||||
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
|
||||
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
|
||||
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
|
||||
|
||||
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
|
||||
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
|
||||
安全原语,保证「校验逻辑与启动器完全同一份实现」。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Savedog</RootNamespace>
|
||||
<AssemblyName>GC-SAVEDOG</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
|
||||
<!--
|
||||
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
|
||||
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
|
||||
|
||||
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
|
||||
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
|
||||
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
|
||||
会覆盖到。
|
||||
-->
|
||||
<PublishTrimmed>true</PublishTrimmed>
|
||||
<TrimMode>full</TrimMode>
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
|
||||
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
||||
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
|
||||
internal sealed class Log
|
||||
{
|
||||
private readonly string? _path;
|
||||
private readonly object _gate = new();
|
||||
|
||||
public Log(string? path) => _path = path;
|
||||
|
||||
public void Info(string message) => Write("INFO ", message);
|
||||
public void Warn(string message) => Write("WARN ", message);
|
||||
public void Error(string message) => Write("ERROR", message);
|
||||
|
||||
private void Write(string level, string message)
|
||||
{
|
||||
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
|
||||
Console.WriteLine(line);
|
||||
if (string.IsNullOrWhiteSpace(_path)) return;
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(_path!);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.AppendAllText(_path!, line + "\n");
|
||||
}
|
||||
}
|
||||
catch { /* 日志失败不能影响更新 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 命令行。
|
||||
///
|
||||
/// GC-SAVEDOG apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
/// [--timeout 45] [--dry-run] [--json]
|
||||
/// GC-SAVEDOG verify --manifest <version.json> [--require 1] [--json]
|
||||
/// GC-SAVEDOG verify-model --dir <model/<id>> --id <id> [--json]
|
||||
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
|
||||
/// GC-SAVEDOG sign --manifest <version.json> [--key .signing/gc-signing.pem]
|
||||
/// [--key-id ...] [--out <file>]
|
||||
/// GC-SAVEDOG status --update <.GC/update> [--json]
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private const string DefaultKeyId = "gc-2026-11";
|
||||
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
try { Console.OutputEncoding = Encoding.UTF8; } catch { }
|
||||
|
||||
// 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需)
|
||||
SavedogJson.Initialize();
|
||||
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
{
|
||||
Help();
|
||||
return 0;
|
||||
}
|
||||
|
||||
var command = args[0].ToLowerInvariant();
|
||||
var rest = args.Skip(1).ToArray();
|
||||
var options = Parse(rest);
|
||||
|
||||
return command switch
|
||||
{
|
||||
"apply" => Apply(options),
|
||||
"verify" => Verify(options),
|
||||
"verify-model" => VerifyModel(options),
|
||||
"keygen" => Keygen(options),
|
||||
"sign" => Sign(options),
|
||||
"status" => Status(options),
|
||||
"version" or "--version" => PrintVersion(),
|
||||
_ => Unknown(command)
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ apply
|
||||
|
||||
private static int Apply(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Option(options, "update", "");
|
||||
if (string.IsNullOrWhiteSpace(updateDir))
|
||||
{
|
||||
Console.Error.WriteLine("apply 需要 --update <.GC/update>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log));
|
||||
var applyOptions = new ApplyOptions
|
||||
{
|
||||
UpdateDir = updateDir,
|
||||
InstallDir = Option(options, "install", null),
|
||||
WaitPid = Int(options, "wait-pid", 0),
|
||||
TimeoutSeconds = Int(options, "timeout", 45),
|
||||
DryRun = Flag(options, "dry-run"),
|
||||
Force = Flag(options, "force"),
|
||||
RequireSignature = Int(options, "require-signature", 1) != 0
|
||||
};
|
||||
|
||||
var applier = new Applier(applyOptions, log);
|
||||
var code = applier.Run();
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
if (applyOptions.DryRun)
|
||||
{
|
||||
// dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方
|
||||
var request = Json.Read<SavedogRequest>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest));
|
||||
Console.WriteLine(Json.Serialize(new SavedogState
|
||||
{
|
||||
Status = code == 0 ? "checked" : "failed",
|
||||
Version = request?.Version ?? "",
|
||||
PackageName = request?.PackageName ?? "",
|
||||
Verified = code == 0,
|
||||
Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)"
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
var state = Json.Read<SavedogState>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
|
||||
Console.WriteLine(Json.Serialize(state));
|
||||
}
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ verify
|
||||
|
||||
private static int Verify(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var require = Int(options, "require", 1) != 0;
|
||||
var text = File.ReadAllText(manifest);
|
||||
var result = ManifestSignature.Verify(text, require);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
var report = new VerifyReport
|
||||
{
|
||||
Trust = result.Trust.ToString(),
|
||||
KeyId = result.KeyId,
|
||||
Error = result.Error
|
||||
};
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
report.TrustedKeys.Add(new TrustedKey
|
||||
{
|
||||
KeyId = key.KeyId,
|
||||
Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)
|
||||
});
|
||||
Console.WriteLine(Json.Serialize(report));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"信任状态: {result.Trust}");
|
||||
if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}");
|
||||
if (result.Error != null) Console.WriteLine($"说明: {result.Error}");
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})");
|
||||
}
|
||||
|
||||
return result.IsTrusted ? 0 : 2;
|
||||
}
|
||||
|
||||
private static int VerifyModel(Dictionary<string, string> options)
|
||||
{
|
||||
var dir = Option(options, "dir", "");
|
||||
var id = Option(options, "id", "");
|
||||
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --id <模型 id>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id);
|
||||
if (Flag(options, "json"))
|
||||
Console.WriteLine(Json.Serialize(new VerifyModelReport
|
||||
{
|
||||
Ok = result.Ok,
|
||||
Present = result.Present,
|
||||
Message = result.Message
|
||||
}));
|
||||
else
|
||||
Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}");
|
||||
|
||||
return result.Ok ? 0 : 2;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ keygen / sign
|
||||
|
||||
private static int Keygen(Dictionary<string, string> options)
|
||||
{
|
||||
var outDir = Option(options, "out", ".signing")!;
|
||||
var keyId = Option(options, "key-id", DefaultKeyId)!;
|
||||
Directory.CreateDirectory(outDir);
|
||||
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var privatePath = Path.Combine(outDir, "gc-signing.pem");
|
||||
var publicPath = Path.Combine(outDir, "gc-signing.pub");
|
||||
|
||||
File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem());
|
||||
var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key);
|
||||
File.WriteAllText(publicPath, publicBase64 + "\n");
|
||||
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
catch { }
|
||||
|
||||
Console.WriteLine("已生成 ECDSA P-256 密钥对:");
|
||||
Console.WriteLine(" 私钥(绝不要提交): " + privatePath);
|
||||
Console.WriteLine(" 公钥(写进源码) : " + publicPath);
|
||||
Console.WriteLine(" keyId : " + keyId);
|
||||
Console.WriteLine(" 公钥 Base64 : " + publicBase64);
|
||||
Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:");
|
||||
Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Sign(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
var keyPath = Option(options, "key", DefaultKeyPath)!;
|
||||
var keyId = Option(options, "key-id",
|
||||
Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("sign 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
using var key = ManifestSignature.TryLoadPrivateKey(keyPath);
|
||||
if (key == null)
|
||||
{
|
||||
Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}");
|
||||
return 4;
|
||||
}
|
||||
|
||||
var text = File.ReadAllText(manifest);
|
||||
var signed = ManifestSignature.SignDocument(text, key, keyId);
|
||||
var output = Option(options, "out", manifest)!;
|
||||
File.WriteAllText(output, signed);
|
||||
|
||||
var check = ManifestSignature.Verify(signed, requireSignature: true);
|
||||
Console.WriteLine($"已签名: {output}({check.Trust})");
|
||||
return check.Trust == ManifestTrust.Verified ? 0 : 5;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
|
||||
private static int Status(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
|
||||
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
|
||||
var lastGood = Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
Console.WriteLine(Json.Serialize(new StatusReport
|
||||
{
|
||||
State = state,
|
||||
LastGood = lastGood,
|
||||
Health = health
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
|
||||
Console.WriteLine(state == null
|
||||
? "没有更新记录"
|
||||
: $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})");
|
||||
Console.WriteLine(lastGood == null
|
||||
? "上次成功版本: 未知"
|
||||
: $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})");
|
||||
Console.WriteLine(health == null
|
||||
? "健康标记: 无"
|
||||
: $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int PrintVersion()
|
||||
{
|
||||
Console.WriteLine("GC-SAVEDOG 1.0.0");
|
||||
Console.WriteLine("签名算法: " + ManifestSignature.Algorithm);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Unknown(string command)
|
||||
{
|
||||
Console.Error.WriteLine($"未知命令: {command}");
|
||||
Help();
|
||||
return 3;
|
||||
}
|
||||
|
||||
private static void Help()
|
||||
{
|
||||
Console.WriteLine("""
|
||||
GC-SAVEDOG —— 启动器更新守护进程
|
||||
|
||||
apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
[--timeout 45] [--dry-run] [--force] [--json]
|
||||
verify --manifest <version.json> [--require 1] [--json]
|
||||
verify-model --dir <model/ID> --id <ID> [--json]
|
||||
keygen [--out .signing] [--key-id gc-2026-11]
|
||||
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
|
||||
status --update <.GC/update> [--json]
|
||||
|
||||
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
|
||||
""");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 参数
|
||||
|
||||
private static Dictionary<string, string> Parse(string[] args)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
if (!arg.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[arg] = "1";
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = arg[2..];
|
||||
var eq = name.IndexOf('=');
|
||||
if (eq > 0)
|
||||
{
|
||||
map[name[..eq]] = name[(eq + 1)..];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[name] = args[++i];
|
||||
continue;
|
||||
}
|
||||
map[name] = "1";
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static string? Option(Dictionary<string, string> options, string name, string? fallback)
|
||||
=> options.TryGetValue(name, out var value) ? value : fallback;
|
||||
|
||||
private static int Int(Dictionary<string, string> options, string name, int fallback)
|
||||
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
|
||||
? parsed : fallback;
|
||||
|
||||
private static bool Flag(Dictionary<string, string> options, string name)
|
||||
=> options.TryGetValue(name, out var value) &&
|
||||
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
|
||||
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
|
||||
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
|
||||
/// 编译期生成类型信息,运行时零反射。
|
||||
///
|
||||
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
|
||||
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip)]
|
||||
[JsonSerializable(typeof(SavedogRequest))]
|
||||
[JsonSerializable(typeof(SavedogState))]
|
||||
[JsonSerializable(typeof(LastGoodVersion))]
|
||||
[JsonSerializable(typeof(StartupHealth.HealthRecord))]
|
||||
[JsonSerializable(typeof(ModelIntegrityFile))]
|
||||
[JsonSerializable(typeof(VerifyReport))]
|
||||
[JsonSerializable(typeof(StatusReport))]
|
||||
[JsonSerializable(typeof(VerifyModelReport))]
|
||||
internal partial class SavedogJsonContext : JsonSerializerContext
|
||||
{
|
||||
// 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项,
|
||||
// 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。
|
||||
}
|
||||
|
||||
/// <summary><c>verify --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyReport
|
||||
{
|
||||
public string Trust { get; set; } = "";
|
||||
public string? KeyId { get; set; }
|
||||
public string? Error { get; set; }
|
||||
public List<TrustedKey> TrustedKeys { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class TrustedKey
|
||||
{
|
||||
public string KeyId { get; set; } = "";
|
||||
public string Fingerprint { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary><c>status --json</c> 的输出。</summary>
|
||||
internal sealed class StatusReport
|
||||
{
|
||||
public SavedogState? State { get; set; }
|
||||
public LastGoodVersion? LastGood { get; set; }
|
||||
public StartupHealth.HealthRecord? Health { get; set; }
|
||||
}
|
||||
|
||||
/// <summary><c>verify-model --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyModelReport
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
public bool Present { get; set; }
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
|
||||
internal static class SavedogJson
|
||||
{
|
||||
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user