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; /// /// 「工具 → 安装谷歌插件」:用**企业策略**把 Chrome / Edge 的扩展装上 /// /// 为什么不能像以前那样「复制解压目录 + 加载已解压」: /// - 那只在开发者模式生效,每台机器要人手动点,Chrome 每次启动还会提示「请停用以开发者模式运行的扩展程序」; /// - 策略安装(ExtensionInstallForcelist)只认 `<扩展ID>;`,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,稳得多。 /// public static class ExtensionInstaller { /// 更新清单路径(相对后端地址) private const string UpdatePath = "/download/extension/updates.xml"; /// 允许安装来源的匹配串(非商店 CRX 必须放行,否则 Chrome 直接拒绝) private const string SourcesSuffix = "/download/extension/*"; /// 我们写的策略以后都带这个特征,卸载时按它精确匹配,不误删别人的策略 private const string OurMarker = "/download/extension/"; /// Chrome / Edge 的策略根(都支持 ExtensionInstallForcelist + ExtensionInstallSources) private static readonly string[] BrowserPolicyRoots = { @"SOFTWARE\Policies\Google\Chrome", @"SOFTWARE\Policies\Microsoft\Edge", }; /// 用户点了 UAC 的「否」 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 Targets { get; set; } = new(); } /// /// 装插件(**会弹一次 UAC**) /// /// 用户取消了 UAC 授权 /// 拉不到更新清单 / 策略没写进去 public static async Task 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); } /// 卸插件(**会弹一次 UAC**):只删带我们 URL 特征的那几条策略 public static Task UninstallAsync(string serverBaseUrl, CancellationToken ct = default) => ApplyAsync(NormalizeBase(serverBaseUrl), string.Empty, install: false, ct); /// 更新清单地址(失败提示里要给用户看) 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; } /// 拉 updates.xml,读 `` private static async Task 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); } } /// 生成 .reg → runas 执行 reg import → 读注册表确认 private static async Task 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); } } /// 拼 .reg 文本(空文本 = 没有要改的东西) 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; } /// /// 生成某个策略键要写的行(安装 = 写入/复用值名;卸载 = 删除我们写的值) /// /// 安装时**复用已有的值名**(值就是我们想要的,或值是旧的我们 URL), /// 顺手把重复的历史值删掉 —— 否则每点一次「安装」都会多出一条一样的策略。 /// private static List 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(); // ① 已经是目标值 → 直接用这个值名 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; } /// 该策略键下的「值名 → 值」(读不到返回空字典) private static Dictionary PolicyValues(string policyPath) { var result = new Dictionary(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; } /// 找一个没被占用的值名 private static string PickFreeValueName(IEnumerable used) { var taken = new HashSet(used, StringComparer.OrdinalIgnoreCase); for (var i = 1; i < 100; i++) { if (!taken.Contains(i.ToString())) return i.ToString(); } return Guid.NewGuid().ToString("N"); } /// 装成功后该有的那条 forcelist 值在不在(读 HKLM 不需要管理员) 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; } /// 还有没有我们写的策略(卸载后应为 false) 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; } /// .reg 字符串里的转义(反斜杠、引号) private static string Escape(string value) => value.Replace("\\", "\\\\").Replace("\"", "\\\""); private static void TryDelete(string path) { try { if (File.Exists(path)) File.Delete(path); } catch { // 临时文件删不掉不影响业务 } } }