packServer/desktop/Services/ExtensionInstaller.cs
liufumingren 11ebb33966 feat(extension): 插件配置集中管理 + 桌面端策略安装 + 跨网下载修复
- 后端:sys_config 存插件配置(识别前缀/生效站点/模板),平台管理员 GET/PUT /api/web/admin/extension;
  插件读取 GET /api/web/extension/config(Redis 缓存 1 小时,保存即失效)
- 前端:平台管理 → 插件配置页(只维护前缀,单号正则由服务端生成)
- 插件:改为只拉取执行(每 5 分钟 + 手动同步),移除规则编辑/试跑/导入导出;安装包地址自动取最新发布
- 桌面端:工具 → 安装/卸载谷歌插件(生成 .reg + reg import 写 HKLM 策略,读注册表验证);
  跨网下载改走云端中转;局域网探测补排障日志;自动更新按包类型取 md5Exe/sizeExe
- 发布:npm run extension:publish(crx + updates.xml)、extension:zip(商店上传包),
  nginx 对 /download/extension/updates.xml 关缓存

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 03:16:26 +08:00

394 lines
15 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.Win32;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 「工具 → 安装谷歌插件」:用**企业策略**把 Chrome / Edge 的扩展装上
///
/// 为什么不能像以前那样「复制解压目录 + 加载已解压」:
/// - 那只在开发者模式生效,每台机器要人手动点,Chrome 每次启动还会提示「请停用以开发者模式运行的扩展程序」;
/// - 策略安装(<c>ExtensionInstallForcelist</c>)只认 `<扩展ID>;<update_url>`,update_url 必须是
/// 一个可访问的 XML(我们自己的 `/download/extension/updates.xml`),**不认本地目录**。
///
/// 实现方式(**不依赖进程间回传结果**):
/// 1. 去后端拉 `updates.xml` 读出扩展 ID;
/// 2. 生成一个 `.reg` 文件(写 HKLM 策略);
/// 3. runas 执行 `reg.exe import`(一次 UAC);
/// 4. **直接读注册表**确认写没写进去 —— 成功与否以注册表为准,不看子进程输出。
///
/// ⚠️ 早期版本用「runas 起自己 + 临时文件回传结果」,现场出现过
/// 「提权进程退出码 0 但结果文件没写」→ 装不上。reg import 只有一步动作、没有 IPC,稳得多。
/// </summary>
public static class ExtensionInstaller
{
/// <summary>更新清单路径(相对后端地址)</summary>
private const string UpdatePath = "/download/extension/updates.xml";
/// <summary>允许安装来源的匹配串(非商店 CRX 必须放行,否则 Chrome 直接拒绝)</summary>
private const string SourcesSuffix = "/download/extension/*";
/// <summary>我们写的策略以后都带这个特征,卸载时按它精确匹配,不误删别人的策略</summary>
private const string OurMarker = "/download/extension/";
/// <summary>Chrome / Edge 的策略根(都支持 ExtensionInstallForcelist + ExtensionInstallSources)</summary>
private static readonly string[] BrowserPolicyRoots =
{
@"SOFTWARE\Policies\Google\Chrome",
@"SOFTWARE\Policies\Microsoft\Edge",
};
/// <summary>用户点了 UAC 的「否」</summary>
private const int ErrorCancelled = 1223;
public sealed class HelperResult
{
public bool Ok { get; set; }
public string? Error { get; set; }
public string? Id { get; set; }
public string? UpdateUrl { get; set; }
public List<string> Targets { get; set; } = new();
}
/// <summary>
/// 装插件(**会弹一次 UAC**)
/// </summary>
/// <exception cref="OperationCanceledException">用户取消了 UAC 授权</exception>
/// <exception cref="InvalidOperationException">拉不到更新清单 / 策略没写进去</exception>
public static async Task<HelperResult> InstallAsync(string serverBaseUrl, CancellationToken ct = default)
{
var baseUrl = NormalizeBase(serverBaseUrl);
var id = await FetchExtensionIdAsync(baseUrl, ct).ConfigureAwait(false);
return await ApplyAsync(baseUrl, id, install: true, ct).ConfigureAwait(false);
}
/// <summary>卸插件(**会弹一次 UAC**):只删带我们 URL 特征的那几条策略</summary>
public static Task<HelperResult> UninstallAsync(string serverBaseUrl, CancellationToken ct = default)
=> ApplyAsync(NormalizeBase(serverBaseUrl), string.Empty, install: false, ct);
/// <summary>更新清单地址(失败提示里要给用户看)</summary>
public static string UpdateUrlOf(string serverBaseUrl) => NormalizeBase(serverBaseUrl) + UpdatePath;
private static string NormalizeBase(string serverBaseUrl)
{
var value = (serverBaseUrl ?? string.Empty).Trim().TrimEnd('/');
if (value.Length == 0) throw new InvalidOperationException("后端地址为空,无法安装插件");
return value;
}
/// <summary>拉 updates.xml,读 `<app appid="...">`</summary>
private static async Task<string> FetchExtensionIdAsync(string baseUrl, CancellationToken ct)
{
var url = baseUrl + UpdatePath;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
string xml;
try
{
xml = await http.GetStringAsync(url, ct).ConfigureAwait(false);
}
catch (HttpRequestException ex)
{
throw new InvalidOperationException(
$"拿不到插件更新清单({url}):{ex.Message}\n\n"
+ "服务端还没发布过插件包?先执行 backend 的 npm run extension:publish。", ex);
}
try
{
var id = XDocument.Parse(xml)
.Descendants()
.FirstOrDefault(element => element.Name.LocalName == "app")
?.Attribute("appid")?.Value?.Trim();
if (string.IsNullOrEmpty(id) || id.Length != 32)
{
throw new InvalidOperationException($"更新清单里没有有效的 appid({url})");
}
return id;
}
catch (Exception ex) when (ex is not InvalidOperationException)
{
throw new InvalidOperationException($"解析插件更新清单失败({url}):{ex.Message}", ex);
}
}
/// <summary>生成 .reg → runas 执行 reg import → 读注册表确认</summary>
private static async Task<HelperResult> ApplyAsync(string baseUrl, string id, bool install, CancellationToken ct)
{
var regFile = Path.Combine(Path.GetTempPath(), $"yuncang_ext_{Guid.NewGuid():N}.reg");
var regText = BuildReg(baseUrl, id, install);
if (regText.Length == 0)
{
// 卸载时没有任何我们写的值:直接算成功
AppLog.Write("[extension] 没有找到本软件写入的策略,无需提权");
return new HelperResult { Ok = true, Id = id, UpdateUrl = baseUrl + UpdatePath };
}
File.WriteAllText(regFile, regText, Encoding.Unicode);
var regExe = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "reg.exe");
var psi = new ProcessStartInfo(regExe, $"import \"{regFile}\"")
{
UseShellExecute = true, // runas 只能走 ShellExecute
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
};
AppLog.Write($"[extension] 提权导入策略({(install ? "安装" : "卸载")}):{psi.FileName} {psi.Arguments}");
try
{
using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false)
?? throw new InvalidOperationException("提权进程启动失败");
await process.WaitForExitAsync(ct).ConfigureAwait(false);
// 以注册表实际状态为准(reg 的退出码在不同系统上不完全可靠)
var ok = install ? HasExactPolicy(id, baseUrl) : !HasAnyOfOurPolicy();
if (!ok)
{
AppLog.Write($"[extension] reg import 退出码 {process.ExitCode},但注册表未生效({regText})");
throw new InvalidOperationException(
$"策略没有写进注册表(reg import 退出码 {process.ExitCode})。\n\n"
+ "可能被安全软件拦截了注册表写入;也可以手动导入下面这个文件后重试:\n"
+ regFile);
}
return new HelperResult
{
Ok = true,
Id = id,
UpdateUrl = baseUrl + UpdatePath,
Targets = BrowserPolicyRoots.Select(root => root.EndsWith("Chrome", StringComparison.OrdinalIgnoreCase) ? "Chrome" : "Edge").ToList(),
};
}
catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
{
throw new OperationCanceledException("已取消管理员授权,浏览器策略没有改动");
}
finally
{
TryDelete(regFile);
}
}
/// <summary>拼 .reg 文本(空文本 = 没有要改的东西)</summary>
private static string BuildReg(string baseUrl, string id, bool install)
{
var updateUrl = baseUrl + UpdatePath;
var sources = baseUrl + SourcesSuffix;
var builder = new StringBuilder();
var hasContent = false;
foreach (var root in BrowserPolicyRoots)
{
var forcelistPath = root + @"\ExtensionInstallForcelist";
var sourcesPath = root + @"\ExtensionInstallSources";
var forcelistLines = BuildValueLines(forcelistPath, $"{id};{updateUrl}", install);
var sourcesLines = BuildValueLines(sourcesPath, sources, install);
if (forcelistLines.Count == 0 && sourcesLines.Count == 0) continue;
if (!hasContent)
{
builder.AppendLine("Windows Registry Editor Version 5.00");
hasContent = true;
}
if (forcelistLines.Count > 0)
{
builder.AppendLine();
builder.AppendLine($"[HKEY_LOCAL_MACHINE\\{forcelistPath}]");
foreach (var line in forcelistLines) builder.AppendLine(line);
}
if (sourcesLines.Count > 0)
{
builder.AppendLine();
builder.AppendLine($"[HKEY_LOCAL_MACHINE\\{sourcesPath}]");
foreach (var line in sourcesLines) builder.AppendLine(line);
}
}
return hasContent ? builder.ToString() : string.Empty;
}
/// <summary>
/// 生成某个策略键要写的行(安装 = 写入/复用值名;卸载 = 删除我们写的值)
///
/// 安装时**复用已有的值名**(值就是我们想要的,或值是旧的我们 URL),
/// 顺手把重复的历史值删掉 —— 否则每点一次「安装」都会多出一条一样的策略。
/// </summary>
private static List<string> BuildValueLines(string policyPath, string desiredValue, bool install)
{
var existing = PolicyValues(policyPath);
if (!install)
{
return existing
.Where(item => item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
.Select(item => $"\"{item.Key}\"=-")
.ToList();
}
var lines = new List<string>();
// ① 已经是目标值 → 直接用这个值名
var target = existing
.FirstOrDefault(item => string.Equals(item.Value.Trim(), desiredValue, StringComparison.OrdinalIgnoreCase))
.Key;
// ② 否则复用「我们写的旧值」那个名字(比如域名换过)
if (target is null)
{
target = existing
.FirstOrDefault(item => item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
.Key;
}
// ③ 都没有才找一个空号(默认 "1",被别人占了就顺延)
target ??= PickFreeValueName(existing.Keys);
lines.Add($"\"{target}\"=\"{Escape(desiredValue)}\"");
// 清掉重复的历史条目(同一个扩展我们可能写过多条)
foreach (var item in existing)
{
if (string.Equals(item.Key, target, StringComparison.OrdinalIgnoreCase)) continue;
if (!item.Value.Contains(OurMarker, StringComparison.OrdinalIgnoreCase)) continue;
lines.Add($"\"{item.Key}\"=-");
}
return lines;
}
/// <summary>该策略键下的「值名 → 值」(读不到返回空字典)</summary>
private static Dictionary<string, string> PolicyValues(string policyPath)
{
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
using var key = baseKey.OpenSubKey(policyPath);
if (key is null) return result;
foreach (var name in key.GetValueNames())
{
if (key.GetValue(name) is string text) result[name] = text;
}
}
catch
{
// 读不到就当没有
}
return result;
}
/// <summary>找一个没被占用的值名</summary>
private static string PickFreeValueName(IEnumerable<string> used)
{
var taken = new HashSet<string>(used, StringComparer.OrdinalIgnoreCase);
for (var i = 1; i < 100; i++)
{
if (!taken.Contains(i.ToString())) return i.ToString();
}
return Guid.NewGuid().ToString("N");
}
/// <summary>装成功后该有的那条 forcelist 值在不在(读 HKLM 不需要管理员)</summary>
private static bool HasExactPolicy(string id, string baseUrl)
{
if (id.Length == 0) return false;
var expected = $"{id};{baseUrl}{UpdatePath}";
foreach (var root in BrowserPolicyRoots)
{
foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 })
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
using var key = baseKey.OpenSubKey(root + @"\ExtensionInstallForcelist");
if (key is null) continue;
foreach (var name in key.GetValueNames())
{
if (key.GetValue(name) is string text
&& string.Equals(text.Trim(), expected, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
catch
{
// 读不到就当没有
}
}
}
return false;
}
/// <summary>还有没有我们写的策略(卸载后应为 false)</summary>
private static bool HasAnyOfOurPolicy()
{
foreach (var root in BrowserPolicyRoots)
{
foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 })
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
using var key = baseKey.OpenSubKey(root + @"\ExtensionInstallForcelist");
if (key is null) continue;
foreach (var name in key.GetValueNames())
{
if (key.GetValue(name) is string text
&& text.Contains(OurMarker, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
catch
{
// 读不到就当没有
}
}
}
return false;
}
/// <summary>.reg 字符串里的转义(反斜杠、引号)</summary>
private static string Escape(string value)
=> value.Replace("\\", "\\\\").Replace("\"", "\\\"");
private static void TryDelete(string path)
{
try
{
if (File.Exists(path)) File.Delete(path);
}
catch
{
// 临时文件删不掉不影响业务
}
}
}