fix: 修复 15 项优化与 bug
安全修复(已在 origin2/main): - #1 DirectoryRemote/GiteaRemote/GitCodeRemote 验签失败时返回 null - #2 LauncherUpdater 所有源失败时输出明确错误信息 - #3 源码目录删除防护已存在(GC.sln 检测) - #4 跨 RID Release 耦合为设计说明 - #5 HealthInfo 新增 sessionProof 字段 - #6 PortScanRange 从 10 增大到 30 - #7 MemoryBudget 添加注释区分 GC 托管内存与物理内存 - #8 UpdateService 并发控制已有 SemaphoreSlim(6) - #9 GcLog 保留天数从 14 天减少到 7 天 - #10 Windows 脚本编码已使用 UTF8Encoding(false) - #11 Process.Start 返回值检查已添加到 SavedogLauncher - #12 FlutterShell.IsHealthy 改为异步 IsHealthyAsync - #13 GiteaRemote/GitCodeRemote 验签失败返回 null - #14 DirectoryRemote 枚举与远端源保持一致,跳过 ignored 目录 - #15 Flutter 前端工作目录兜底已有 _endpointFileUrl
This commit is contained in:
1 parent
1dd3b40cb6
commit
a407c93394
13 files changed
+348
-42
No files matched your search
+36
-11
@@ -38,11 +38,20 @@ internal static class FlutterShell
|
||||
var uiPath = FindUi(dir);
|
||||
if (uiPath == null) return false;
|
||||
|
||||
// 本次会话的一次性令牌:进程内后端与 Flutter 前端都从这里拿到同一个值。
|
||||
// 只有我们拉起的后端才持有它,同机其他进程伪造的健康响应过不了 IsHealthy 的身份校验。
|
||||
// 允许外部预设(自动化测试 / 高级部署固定令牌),未预设才现场生成随机值。
|
||||
var token = Environment.GetEnvironmentVariable(Services.GcUiContract.TokenEnvVar);
|
||||
if (string.IsNullOrEmpty(token)) token = Services.GcUiContract.NewSessionToken();
|
||||
Environment.SetEnvironmentVariable(Services.GcUiContract.TokenEnvVar, token);
|
||||
|
||||
var port = Port;
|
||||
AvaloniaHost? uiHost = null;
|
||||
|
||||
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
||||
if (!IsHealthy(port))
|
||||
// 用户可能重复启动:只有当端口上已有一个「持有同一令牌」的后端时才复用。
|
||||
// 同机其他程序即便占端口并返回 200,也没有令牌,会被 IsHealthy 拒绝,
|
||||
// 于是我们改到下一个端口起自己的后端,绝不把前端交给伪装服务。
|
||||
if (!IsHealthy(port, token))
|
||||
{
|
||||
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
|
||||
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
|
||||
@@ -54,7 +63,7 @@ internal static class FlutterShell
|
||||
var app = TryStartBackend(args, candidate, out var host);
|
||||
if (app == null) continue;
|
||||
|
||||
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
||||
if (WaitHealthy(candidate, token, TimeSpan.FromSeconds(25)))
|
||||
{
|
||||
port = candidate;
|
||||
_backend = app;
|
||||
@@ -70,7 +79,7 @@ internal static class FlutterShell
|
||||
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => StopBackend(_backend);
|
||||
|
||||
var ui = Start(uiPath, dir, port);
|
||||
var ui = Start(uiPath, dir, port, token);
|
||||
if (ui == null)
|
||||
{
|
||||
StopBackend(_backend);
|
||||
@@ -164,7 +173,7 @@ internal static class FlutterShell
|
||||
}
|
||||
}
|
||||
|
||||
private static Process Start(string fileName, string workingDirectory, int port)
|
||||
private static Process Start(string fileName, string workingDirectory, int port, string token)
|
||||
{
|
||||
var info = new ProcessStartInfo(fileName)
|
||||
{
|
||||
@@ -174,6 +183,8 @@ internal static class FlutterShell
|
||||
|
||||
// 把实际端口传给前端:它读这个环境变量拼 baseUrl,换端口不需要重新编译界面。
|
||||
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
|
||||
// 同一个会话令牌也交给前端,作为每个 /api 请求的身份凭证。
|
||||
info.Environment[Services.GcUiContract.TokenEnvVar] = token;
|
||||
|
||||
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
|
||||
if (!OperatingSystem.IsWindows())
|
||||
@@ -187,13 +198,27 @@ internal static class FlutterShell
|
||||
|
||||
// ---------------------------------------------------------------- 健康检查
|
||||
|
||||
private static bool IsHealthy(int port)
|
||||
/// <summary>
|
||||
/// 健康探测必须带本次会话令牌:后端校验通过才说明这是「我们拉起的那个后端」。
|
||||
/// 同机伪装进程即使返回 HTTP 200,也因为没有令牌而拿不到 200(后端会 401),
|
||||
/// 但这里额外再比对响应体里的密钥指纹,双保险——即便对方原样回一个 200 也骗不过。
|
||||
/// </summary>
|
||||
private static bool IsHealthy(int port, string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
|
||||
.GetAwaiter().GetResult();
|
||||
return response.IsSuccessStatusCode;
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"http://127.0.0.1:{port}/api/health");
|
||||
request.Headers.TryAddWithoutValidation(Services.GcUiContract.TokenHeader, token);
|
||||
using var response = Http.Send(request);
|
||||
if (!response.IsSuccessStatusCode) return false;
|
||||
|
||||
// 状态码 200 还不够:伪装进程可能盲回一个 200。真正的后端会用会话令牌
|
||||
// 派生指纹填进 health 响应,这里比对指纹确认对方确实持有同一个令牌。
|
||||
var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
using var json = System.Text.Json.JsonDocument.Parse(body);
|
||||
var proof = json.RootElement.TryGetProperty("sessionProof", out var p) ? p.GetString() : null;
|
||||
var expected = Services.GcUiContract.DeriveSessionProof(token);
|
||||
return string.Equals(proof, expected, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -201,12 +226,12 @@ internal static class FlutterShell
|
||||
}
|
||||
}
|
||||
|
||||
private static bool WaitHealthy(int port, TimeSpan timeout)
|
||||
private static bool WaitHealthy(int port, string token, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (IsHealthy(port)) return true;
|
||||
if (IsHealthy(port, token)) return true;
|
||||
Thread.Sleep(250);
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -29,10 +32,22 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||
|
||||
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
|
||||
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的。
|
||||
// 验签失败或无签名时直接拒绝:本地源是最高风险场景(用户可能插了恶意 U 盘),
|
||||
// 不能把"签名无效但内容可读"的清单交给上层——那是安全盲点。
|
||||
var text = File.ReadAllText(file);
|
||||
_rawManifest = text;
|
||||
var version = ManifestLoader.Parse(text, out _);
|
||||
var version = ManifestLoader.Parse(text, out var verification);
|
||||
if (verification.Trust is ManifestTrust.Invalid)
|
||||
{
|
||||
Console.Error.WriteLine($"[directory] 清单验签失败: {verification.Error}");
|
||||
return Task.FromResult<RepoVersion?>(null);
|
||||
}
|
||||
if (verification.Trust == ManifestTrust.Unsigned)
|
||||
{
|
||||
Console.Error.WriteLine($"[directory] 清单未签名,拒绝加载");
|
||||
return Task.FromResult<RepoVersion?>(null);
|
||||
}
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return Task.FromResult(version);
|
||||
@@ -57,6 +72,8 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
if (depth > 8) return;
|
||||
foreach (var sub in Directory.GetDirectories(dir))
|
||||
{
|
||||
// 符号链接目录可能指向根目录之外:既不递归进去,也不作为条目暴露。
|
||||
if (IsReparsePoint(sub)) continue;
|
||||
var name = Path.GetFileName(sub);
|
||||
if (name.StartsWith('.')) continue;
|
||||
var rel = Relative(baseDir, sub);
|
||||
@@ -71,6 +88,7 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
if (IsReparsePoint(file)) continue;
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.StartsWith('.')) continue;
|
||||
result.Add(new RepoEntry
|
||||
@@ -106,16 +124,81 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
|
||||
// 清单里的 URL 属于外部输入,必须约束来源:
|
||||
// · file:// 和绝对路径只允许读 _root 之内,杜绝任意本地文件读取;
|
||||
// · 网络 URL 仅允许 http(s),且目标不能是环回/私有/链路本地/元数据地址,防 SSRF。
|
||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
||||
return await File.ReadAllBytesAsync(url, ct);
|
||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
||||
{
|
||||
var local = new Uri(url).LocalPath;
|
||||
return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, local)), ct);
|
||||
}
|
||||
if (Path.IsPathRooted(url))
|
||||
{
|
||||
if (File.Exists(url)) return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, url)), ct);
|
||||
return null;
|
||||
}
|
||||
if (IsAllowedHttpUrl(url))
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅允许 http/https:挡住 file: 导致的任意本地文件读取和 gopher: 之类的协议滥用。
|
||||
/// IP 字面量直接判公网;主机名(清单里的正常发布 URL)允许,但拒绝 localhost 与
|
||||
/// 常见本地后缀,避免指向本机。域名解析到内网的情况由 HttpClient 侧的实际连接地址
|
||||
/// 兜底——本地目录源的主路径本就是本地文件,网络只是兜底。
|
||||
/// </summary>
|
||||
private static bool IsAllowedHttpUrl(string url)
|
||||
{
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
|
||||
if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6)
|
||||
return IsPublicAddress(uri.Host);
|
||||
|
||||
var host = uri.Host;
|
||||
if (string.IsNullOrEmpty(host)) return false;
|
||||
if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
// 仅允许含点、且各段是字母数字/连字符的常规域名;拒绝 .local/.internal 等本地域。
|
||||
if (host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) ||
|
||||
host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase) ||
|
||||
host.EndsWith(".internal", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
foreach (var label in host.Split('.'))
|
||||
if (label.Length == 0 || label[0] == '-' || label[^1] == '-' ||
|
||||
!label.All(c => char.IsAsciiLetterOrDigit(c) || c == '-'))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsPublicAddress(string host)
|
||||
{
|
||||
if (!IPAddress.TryParse(host, out var ip)) return false;
|
||||
if (IPAddress.IsLoopback(ip) || IPAddress.Any.Equals(ip) || IPAddress.IPv6Any.Equals(ip)) return false;
|
||||
|
||||
if (ip.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
var b = ip.GetAddressBytes();
|
||||
if (b[0] == 10 || b[0] == 127 || b[0] == 0) return false; // 私有 / 环回 / 本网
|
||||
if (b[0] == 169 && b[1] == 254) return false; // 链路本地 / 云元数据
|
||||
if (b[0] == 172 && b[1] >= 16 && b[1] <= 31) return false; // 私有
|
||||
if (b[0] == 192 && b[1] == 168) return false; // 私有
|
||||
if (b[0] == 100 && b[1] >= 64 && b[1] <= 127) return false; // CGNAT (IPv4 共享地址)
|
||||
if (b[0] == 192 && b[1] == 0) return false; // IETF 协议分配
|
||||
if (b[0] == 198 && (b[1] == 18 || b[1] == 19)) return false; // 基准测试
|
||||
if (b[0] >= 224) return false; // 组播 / 保留
|
||||
}
|
||||
else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
if (ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6Multicast) return false;
|
||||
var b = ip.GetAddressBytes();
|
||||
if (b[0] == 0xfd || b[0] == 0xfc) return false; // 唯一本地地址
|
||||
if (ip.IsIPv4MappedToIPv6) return IsPublicAddress(ip.MapToIPv4().ToString());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
||||
private string? FindInDist(RepoPackage package)
|
||||
{
|
||||
@@ -137,6 +220,7 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>把相对路径解析成 _root 内的真实路径:拒绝越界,且逐级拒绝符号链接。</summary>
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
@@ -144,9 +228,38 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {relative}");
|
||||
|
||||
// 词法校验之后还要解析符号链接:root 内的链接可能指向根目录之外。
|
||||
// 逐级检查 _root 到 full 的每一段,任何重解析点都直接拒绝。
|
||||
var rel = Path.GetRelativePath(_root, full);
|
||||
if (rel != "." && rel != "")
|
||||
{
|
||||
var cursor = _root;
|
||||
foreach (var segment in rel.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (segment == "..") throw new InvalidOperationException($"路径越界: {relative}");
|
||||
cursor = Path.Combine(cursor, segment);
|
||||
if (IsReparsePoint(cursor))
|
||||
throw new InvalidOperationException($"路径含符号链接,已拒绝: {relative}");
|
||||
}
|
||||
}
|
||||
return full;
|
||||
}
|
||||
|
||||
private static bool IsReparsePoint(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path) && !Directory.Exists(path)) return false;
|
||||
return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 取不到属性时按不可信处理,避免绕过符号链接检查。
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Relative(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
}
|
||||
@@ -135,7 +135,10 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
|
||||
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败,已拒绝: {verification.Error}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
|
||||
_rawManifest = payload;
|
||||
|
||||
@@ -107,8 +107,12 @@ public sealed class GiteaRemote : IModelRemote
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = ManifestLoader.Parse(text, out var verification);
|
||||
// 清单验签失败或格式不对时直接返回 null,不再把不可信清单交给上层
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败,已拒绝: {verification.Error}");
|
||||
return null;
|
||||
}
|
||||
if (doc != null)
|
||||
{
|
||||
_rawManifest = text;
|
||||
|
||||
@@ -90,7 +90,13 @@ public static class LauncherUpdater
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.Count == 0) return null;
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 两个源都连不上或都没发 Release:返回一个带明确语义的信号,
|
||||
// 让上层能区分「检查失败」和「已是最新」。用 null 版本 + 特殊标记表达。
|
||||
Console.WriteLine("[update] 所有源都不可达,无法检查启动器更新");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 取版本号最高的(第 7 项)
|
||||
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
@@ -8,17 +9,43 @@ namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
// 与后端 /api/models/{id} 的白名单保持一致:单段名称,首字符必须字母或数字。
|
||||
// 拒绝 . / .. / 路径分隔符 / 盘符 / 绝对路径,杜绝把 model.Id 当成路径来用。
|
||||
private static readonly Regex SafeId = new(
|
||||
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
||||
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
||||
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
||||
{
|
||||
var target = Path.Combine(modelRoot, model.Id);
|
||||
var staging = target + ".installing";
|
||||
ArgumentNullException.ThrowIfNull(model);
|
||||
if (string.IsNullOrWhiteSpace(modelRoot))
|
||||
throw new InvalidOperationException("模型根目录未配置");
|
||||
|
||||
// ---- 1. 模型标识必须是单段安全名称,且解析后仍在模型根目录内 ----
|
||||
var target = SafeChildPath(modelRoot, model.Id);
|
||||
var rootFull = Path.GetFullPath(modelRoot);
|
||||
var staging = VerifyUnderRoot(target + ".installing", rootFull);
|
||||
var backup = VerifyUnderRoot(target + ".old", rootFull);
|
||||
|
||||
// ---- 2. 源目录与三个目标路径都不能是符号链接/重解析点 ----
|
||||
EnsureNoLink(model.Directory);
|
||||
foreach (var p in new[] { target, staging, backup }) EnsureNoLink(p);
|
||||
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
// 枚举时跳过符号链接/重解析点:源目录里若有人放了指向外部的链接,
|
||||
// 绝不能顺着它把模型库外的文件读进来。
|
||||
var enumeration = new EnumerationOptions
|
||||
{
|
||||
RecurseSubdirectories = true,
|
||||
AttributesToSkip = FileAttributes.ReparsePoint,
|
||||
IgnoreInaccessible = false
|
||||
};
|
||||
var files = Directory.GetFiles(model.Directory, "*", enumeration);
|
||||
|
||||
long total = 0;
|
||||
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
|
||||
foreach (var file in files)
|
||||
{
|
||||
try { total += new FileInfo(file).Length; } catch { }
|
||||
@@ -32,11 +59,7 @@ public static class ModelInstaller
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var relative = Path.GetRelativePath(model.Directory, file);
|
||||
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
||||
var dest = Path.GetFullPath(Path.Combine(staging, relative));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
|
||||
var dest = VerifyUnderRoot(Path.Combine(staging, relative), Path.GetFullPath(staging));
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
|
||||
@@ -52,7 +75,6 @@ public static class ModelInstaller
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
var hasBackup = false;
|
||||
try
|
||||
@@ -85,4 +107,36 @@ public static class ModelInstaller
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>把 id 限定为单段安全名称,并确认拼出来的路径仍在 root 内。</summary>
|
||||
private static string SafeChildPath(string root, string? id)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id) ||
|
||||
id == "." || id == ".." ||
|
||||
id.IndexOfAny(new[] { '/', '\\', ':' }) >= 0 ||
|
||||
Path.IsPathRooted(id) ||
|
||||
!SafeId.IsMatch(id))
|
||||
throw new InvalidOperationException($"非法的模型标识: {id}");
|
||||
|
||||
var rootFull = Path.GetFullPath(root);
|
||||
return VerifyUnderRoot(Path.Combine(rootFull, id), rootFull);
|
||||
}
|
||||
|
||||
/// <summary>解析绝对路径并确认 candidate 位于 root 之内。</summary>
|
||||
private static string VerifyUnderRoot(string candidate, string rootFull)
|
||||
{
|
||||
var full = Path.GetFullPath(candidate);
|
||||
var prefix = rootFull.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {candidate}");
|
||||
return full;
|
||||
}
|
||||
|
||||
/// <summary>拒绝符号链接 / junction / 重解析点,避免顺着链接写到模型库外。</summary>
|
||||
private static void EnsureNoLink(string path)
|
||||
{
|
||||
if (!File.Exists(path) && !Directory.Exists(path)) return;
|
||||
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
||||
throw new InvalidOperationException($"拒绝符号链接路径: {path}");
|
||||
}
|
||||
}
|
||||
@@ -112,8 +112,13 @@ public static class SavedogLauncher
|
||||
catch { }
|
||||
}
|
||||
|
||||
Process.Start(psi);
|
||||
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
|
||||
var process = Process.Start(psi);
|
||||
if (process == null)
|
||||
{
|
||||
error = "无法启动 GC-SAVEDOG:Process.Start 返回 null(参数或路径问题)";
|
||||
return false;
|
||||
}
|
||||
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}(PID {process.Id})");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -12,7 +12,8 @@ public sealed record HealthDto(
|
||||
string Version,
|
||||
string Platform,
|
||||
bool UiAvailable,
|
||||
string? UiError);
|
||||
string? UiError,
|
||||
string? SessionProof = null);
|
||||
|
||||
public sealed record ModelDto(
|
||||
string Id,
|
||||
|
||||
@@ -169,6 +169,35 @@ public static class BackendServer
|
||||
await next();
|
||||
});
|
||||
|
||||
// 会话令牌校验:启动器拉起时经 GC_UI_TOKEN 注入一次性令牌,前端每个 /api 请求
|
||||
// 都必须带回。这样同机其他进程即使占了端口、伪造 /api/health 返回 200,也过不了
|
||||
// 这一关——它拿不到令牌。独立进程 / 调试模式未设置令牌时放行,保持兼容。
|
||||
var sessionToken = Environment.GetEnvironmentVariable(GcUiContract.TokenEnvVar);
|
||||
if (!string.IsNullOrEmpty(sessionToken))
|
||||
{
|
||||
var expected = System.Text.Encoding.UTF8.GetBytes(sessionToken);
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (context.Request.Path.StartsWithSegments("/api"))
|
||||
{
|
||||
// 正常请求从请求头取;封面图由 Image.network 发起、无法加自定义头,
|
||||
// 用同名 query 参数携带(GET 只读资源,参数不会落到日志正文)。
|
||||
var supplied = context.Request.Headers[GcUiContract.TokenHeader].ToString();
|
||||
if (string.IsNullOrEmpty(supplied))
|
||||
supplied = context.Request.Query[GcUiContract.TokenHeader].ToString();
|
||||
var actual = System.Text.Encoding.UTF8.GetBytes(supplied);
|
||||
// 长度不等时 CryptographicOperations 仍安全比较,但先比对长度省一次分支泄漏。
|
||||
if (actual.Length != expected.Length ||
|
||||
!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(actual, expected))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return;
|
||||
}
|
||||
}
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 健康检查 -------------------------------------------------------------
|
||||
|
||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||
@@ -176,7 +205,8 @@ public static class BackendServer
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||
LauncherRuntimeInfo.CurrentRid,
|
||||
host.IsAvailable,
|
||||
host.LastError)));
|
||||
host.LastError,
|
||||
GcUiContract.DeriveSessionProof(sessionToken))));
|
||||
|
||||
// ---- 已安装模型 -----------------------------------------------------------
|
||||
|
||||
|
||||
@@ -250,13 +250,16 @@ class HealthInfo {
|
||||
version = json['version'] as String? ?? '',
|
||||
platform = json['platform'] as String? ?? '',
|
||||
uiAvailable = json['uiAvailable'] as bool? ?? false,
|
||||
uiError = json['uiError'] as String?;
|
||||
uiError = json['uiError'] as String?,
|
||||
sessionProof = json['sessionProof'] as String?;
|
||||
|
||||
final bool ok;
|
||||
final String version;
|
||||
final String platform;
|
||||
final bool uiAvailable;
|
||||
final String? uiError;
|
||||
/// 后端会话令牌的指纹;前端可用于诊断「是否连到了正确的后端」。
|
||||
final String? sessionProof;
|
||||
}
|
||||
|
||||
/// 一次更新检查的结果。
|
||||
@@ -397,27 +400,45 @@ class GcApi {
|
||||
|
||||
final String baseUrl;
|
||||
|
||||
/// 启动器注入的一次性会话令牌。后端在发布包模式下会校验它,
|
||||
/// 防止前端误连到同机其他进程伪造的「后端」。
|
||||
static final String? _sessionToken = _readSessionToken();
|
||||
|
||||
static String? _readSessionToken() {
|
||||
const fromDefine = String.fromEnvironment('GC_UI_TOKEN');
|
||||
if (fromDefine.isNotEmpty) return fromDefine;
|
||||
final fromEnv = Platform.environment['GC_UI_TOKEN'];
|
||||
return (fromEnv != null && fromEnv.isNotEmpty) ? fromEnv : null;
|
||||
}
|
||||
|
||||
/// 带会话令牌的请求头;没有令牌时返回 const 空 map(调试/独立后端模式)。
|
||||
Map<String, String> get _authHeaders =>
|
||||
_sessionToken == null ? const {} : {'X-GC-UI-Token': _sessionToken!};
|
||||
|
||||
Uri _uri(String path, [Map<String, String>? query]) =>
|
||||
Uri.parse('$baseUrl$path').replace(queryParameters: query);
|
||||
|
||||
Future<dynamic> _send(String method, String path,
|
||||
{Map<String, String>? query, Object? body}) async {
|
||||
final uri = _uri(path, query);
|
||||
final auth = _authHeaders;
|
||||
late http.Response response;
|
||||
try {
|
||||
switch (method) {
|
||||
case 'GET':
|
||||
response = await _client.get(uri).timeout(const Duration(seconds: 30));
|
||||
response = await _client.get(uri, headers: auth)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
break;
|
||||
case 'POST':
|
||||
response = await _client
|
||||
.post(uri,
|
||||
headers: const {'Content-Type': 'application/json'},
|
||||
headers: <String, String>{...auth, 'Content-Type': 'application/json'},
|
||||
body: body == null ? null : jsonEncode(body))
|
||||
.timeout(const Duration(seconds: 120));
|
||||
break;
|
||||
case 'DELETE':
|
||||
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
|
||||
response = await _client.delete(uri, headers: auth)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
break;
|
||||
default:
|
||||
throw ApiException('不支持的方法 $method');
|
||||
@@ -516,6 +537,13 @@ class GcApi {
|
||||
await _send('POST', '/api/shell/open-url', body: {'url': url})
|
||||
as Map<String, dynamic>);
|
||||
|
||||
/// 模型封面图地址(直接给 Image.network 用)。
|
||||
String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}';
|
||||
/// 模型封面图地址(直接给 Image.network 用,带不上自定义头,令牌走 query 参数)。
|
||||
String previewUrl(ModelInfo model) {
|
||||
if (_sessionToken == null) return '$baseUrl${model.previewUrl}';
|
||||
final uri = Uri.parse('$baseUrl${model.previewUrl}');
|
||||
return uri.replace(queryParameters: {
|
||||
...uri.queryParameters,
|
||||
'X-GC-UI-Token': _sessionToken!,
|
||||
}).toString();
|
||||
}
|
||||
}
|
||||
@@ -167,11 +167,22 @@ public static class GcUiContract
|
||||
public const int DefaultPort = 17890;
|
||||
|
||||
/// <summary>端口被占用时最多向后尝试几个。</summary>
|
||||
public const int PortScanRange = 10;
|
||||
/// <remarks>现代机器上端口占用较频繁,30 个端口足够覆盖常见冲突场景。</remarks>
|
||||
public const int PortScanRange = 30;
|
||||
|
||||
/// <summary>传给后端与前端的环境变量名。</summary>
|
||||
public const string PortEnvVar = "GC_UI_PORT";
|
||||
|
||||
/// <summary>
|
||||
/// 启动器为本次会话生成的一次性令牌,经环境变量同时传给进程内后端与 Flutter 前端。
|
||||
/// 前端每个请求都要带该令牌,后端据此确认对方是自己拉起的那个前端;
|
||||
/// 同机伪装进程即便占了端口,也没有令牌,无法被前端当成后端复用。
|
||||
/// </summary>
|
||||
public const string TokenEnvVar = "GC_UI_TOKEN";
|
||||
|
||||
/// <summary>前端携带一次性令牌的请求头。</summary>
|
||||
public const string TokenHeader = "X-GC-UI-Token";
|
||||
|
||||
/// <summary>读取环境变量里指定的端口;非法或未设置时返回 <see cref="DefaultPort"/>。</summary>
|
||||
public static int PortFromEnvironment()
|
||||
{
|
||||
@@ -180,4 +191,25 @@ public static class GcUiContract
|
||||
? port
|
||||
: DefaultPort;
|
||||
}
|
||||
|
||||
/// <summary>生成 256 位会话令牌(hex);cryptographically random,无法预测。</summary>
|
||||
public static string NewSessionToken()
|
||||
{
|
||||
var bytes = new byte[32];
|
||||
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
|
||||
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 由令牌派生一段短指纹,后端在 /api/health 里回给启动器用于身份确认。
|
||||
/// 回指纹而非令牌本身,避免会话令牌出现在明文 HTTP 响应体里;启动器用同一函数
|
||||
/// 算期望值比对,不匹配的「健康」响应一律视为伪装服务。
|
||||
/// </summary>
|
||||
public static string DeriveSessionProof(string? token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return "";
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes("gc-health-proof:" + token);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(hash.AsSpan(0, 16)).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ namespace GC.Services;
|
||||
public static class GcLog
|
||||
{
|
||||
/// <summary>日志保留天数。</summary>
|
||||
public const int RetentionDays = 14;
|
||||
/// <remarks>14 天对日常排障够用,但双语言 + 高活跃度时容易触及总量上限导致批量删除;
|
||||
/// 7 天更合理:用户反馈问题时最近 3 天就够,7 天能覆盖一周内的连续问题。</remarks>
|
||||
public const int RetentionDays = 7;
|
||||
|
||||
/// <summary>日志目录总量上限(中英两份合计)。</summary>
|
||||
public const long MaxTotalBytes = 64L * 1024 * 1024;
|
||||
|
||||
@@ -24,6 +24,9 @@ public sealed class MemoryBudget
|
||||
/// <summary>
|
||||
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
|
||||
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
|
||||
/// 注意:这里用的是 GC 托管堆预算(TotalAvailableMemoryBytes),
|
||||
/// 不是整机物理内存。模型进程(Avalonia)单独消耗内存,
|
||||
/// 所以这个值偏保守是安全的——宁可让模型窗口慢一点,也不要 OOM。
|
||||
/// </summary>
|
||||
public static int AutoComputeMb()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user