chromeProfileDiscovery.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  2. import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import {
  6. buildStandardChromeInstallations,
  7. discoverChromeProfile,
  8. parseRunningChromeInstallations,
  9. resolveChromeExecutablePath,
  10. type ChromeInstallationCandidate,
  11. } from "../src/main/chromeProfileDiscovery.js";
  12. let tempRoot = "";
  13. beforeEach(async () => {
  14. tempRoot = await mkdtemp(join(tmpdir(), "zcode-chrome-discovery-test-"));
  15. });
  16. afterEach(async () => {
  17. await rm(tempRoot, { recursive: true, force: true });
  18. });
  19. async function createUserData(options: {
  20. dataProfiles?: string[];
  21. lastUsed?: string;
  22. name?: string;
  23. profiles: string[];
  24. }): Promise<ChromeInstallationCandidate> {
  25. const userDataDir = join(tempRoot, options.name ?? "User Data");
  26. const dataProfiles = new Set(options.dataProfiles ?? options.profiles);
  27. await mkdir(userDataDir, { recursive: true });
  28. for (const profile of options.profiles) {
  29. await mkdir(join(userDataDir, profile), { recursive: true });
  30. if (dataProfiles.has(profile)) {
  31. await mkdir(join(userDataDir, profile, "Network"), { recursive: true });
  32. await writeFile(join(userDataDir, profile, "Network", "Cookies"), "");
  33. }
  34. }
  35. await writeFile(
  36. join(userDataDir, "Local State"),
  37. JSON.stringify({
  38. profile: {
  39. last_used: options.lastUsed,
  40. info_cache: Object.fromEntries(options.profiles.map((profile) => [profile, {}])),
  41. },
  42. }),
  43. );
  44. return {
  45. browser: "chrome",
  46. userDataDir,
  47. executablePaths: [],
  48. };
  49. }
  50. describe("chromeProfileDiscovery", () => {
  51. it("优先选择 Local State 中最近使用的 Profile", async () => {
  52. const installation = await createUserData({
  53. lastUsed: "Profile 2",
  54. profiles: ["Default", "Profile 2"],
  55. });
  56. await expect(discoverChromeProfile({ installations: [installation] })).resolves.toMatchObject({
  57. success: true,
  58. source: {
  59. profileDirectory: "Profile 2",
  60. profilePath: join(installation.userDataDir, "Profile 2"),
  61. },
  62. });
  63. });
  64. it("最近使用项无效时 fallback 到 Default", async () => {
  65. const installation = await createUserData({
  66. lastUsed: "Profile 9",
  67. profiles: ["Default", "Profile 2"],
  68. });
  69. await expect(discoverChromeProfile({ installations: [installation] })).resolves.toMatchObject({
  70. success: true,
  71. source: { profileDirectory: "Default" },
  72. });
  73. });
  74. it("跳过没有浏览器数据的 Default,选择实际可导入的 Profile", async () => {
  75. const installation = await createUserData({
  76. dataProfiles: ["Profile 2"],
  77. lastUsed: "Default",
  78. profiles: ["Default", "Profile 2"],
  79. });
  80. await expect(discoverChromeProfile({ installations: [installation] })).resolves.toMatchObject({
  81. success: true,
  82. source: { profileDirectory: "Profile 2" },
  83. });
  84. });
  85. it("标准安装 Profile 为空时继续发现后续沙箱安装", async () => {
  86. const standardInstallation = await createUserData({
  87. dataProfiles: [],
  88. name: "XDG Chrome",
  89. profiles: ["Default"],
  90. });
  91. const snapInstallation = await createUserData({
  92. name: "Snap Chromium",
  93. profiles: ["Default"],
  94. });
  95. snapInstallation.browser = "chromium";
  96. await expect(
  97. discoverChromeProfile({ installations: [standardInstallation, snapInstallation] }),
  98. ).resolves.toMatchObject({
  99. success: true,
  100. source: {
  101. browser: "chromium",
  102. profilePath: join(snapInstallation.userDataDir, "Default"),
  103. },
  104. });
  105. });
  106. it("没有 Default 时选择唯一可用 Profile", async () => {
  107. const installation = await createUserData({ profiles: ["Profile 3"] });
  108. await expect(discoverChromeProfile({ installations: [installation] })).resolves.toMatchObject({
  109. success: true,
  110. source: { profileDirectory: "Profile 3" },
  111. });
  112. });
  113. it("多个 Profile 且无法确定来源时返回歧义错误", async () => {
  114. const installation = await createUserData({ profiles: ["Profile 2", "Profile 3"] });
  115. await expect(discoverChromeProfile({ installations: [installation] })).resolves.toEqual({
  116. success: false,
  117. error: "chrome_profile_ambiguous",
  118. });
  119. });
  120. it("发现运行中 Chrome 的自定义 user-data-dir", () => {
  121. expect(
  122. parseRunningChromeInstallations([
  123. '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --user-data-dir="D:\\Chrome Data" --profile-directory="Profile 2"',
  124. ]),
  125. ).toEqual([
  126. expect.objectContaining({
  127. browser: "chrome",
  128. executablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  129. userDataDir: "D:\\Chrome Data",
  130. }),
  131. ]);
  132. });
  133. it("保留 Linux Chrome 显式选择的受支持 password store", () => {
  134. expect(
  135. parseRunningChromeInstallations([
  136. "/usr/bin/google-chrome --user-data-dir=/home/demo/.config/google-chrome --password-store=kwallet6",
  137. ]),
  138. ).toEqual([
  139. expect.objectContaining({
  140. browser: "chrome",
  141. executablePath: "/usr/bin/google-chrome",
  142. passwordStore: "kwallet6",
  143. userDataDir: "/home/demo/.config/google-chrome",
  144. }),
  145. ]);
  146. });
  147. it("Linux Chrome 使用标准 Profile 时也合并运行进程的 password store", () => {
  148. const fallback: ChromeInstallationCandidate = {
  149. browser: "chrome",
  150. executablePaths: ["/usr/bin/google-chrome", "/opt/google/chrome/chrome"],
  151. userDataDir: "/home/demo/.config/google-chrome",
  152. };
  153. expect(
  154. parseRunningChromeInstallations(
  155. [
  156. "/opt/google/chrome/chrome --type=renderer --password-store=basic",
  157. "/opt/google/chrome/chrome --password-store=gnome-libsecret",
  158. ],
  159. [fallback],
  160. ),
  161. ).toEqual([
  162. expect.objectContaining({
  163. executablePath: "/opt/google/chrome/chrome",
  164. passwordStore: "gnome-libsecret",
  165. userDataDir: fallback.userDataDir,
  166. }),
  167. ]);
  168. });
  169. it("Profile 自动发现结果携带 Linux 主进程的 password store", async () => {
  170. const installation = await createUserData({ profiles: ["Default"] });
  171. installation.executablePaths = ["/opt/google/chrome/chrome"];
  172. await expect(
  173. discoverChromeProfile({
  174. platform: "linux",
  175. installations: [installation],
  176. processCommandLines: ["/opt/google/chrome/chrome --password-store=gnome-libsecret"],
  177. }),
  178. ).resolves.toMatchObject({
  179. success: true,
  180. source: {
  181. executablePath: "/opt/google/chrome/chrome",
  182. passwordStore: "gnome-libsecret",
  183. profilePath: join(installation.userDataDir, "Default"),
  184. },
  185. });
  186. });
  187. it("忽略未知 password store,避免把任意运行参数转发给 helper", () => {
  188. const installations = parseRunningChromeInstallations([
  189. "/usr/bin/google-chrome --user-data-dir=/home/demo/.config/google-chrome --password-store=unknown-backend",
  190. ]);
  191. expect(installations).toHaveLength(1);
  192. expect(installations[0]).not.toHaveProperty("passwordStore");
  193. });
  194. it("忽略 Electron/Chrome 的 crashpad 与 helper 子进程", () => {
  195. expect(
  196. parseRunningChromeInstallations([
  197. "/Applications/ZCode.app/Contents/Frameworks/Electron Framework.framework/Helpers/chrome_crashpad_handler --user-data-dir=/tmp/zcode",
  198. ]),
  199. ).toEqual([]);
  200. });
  201. it("Windows 标准候选覆盖多渠道和 Program Files x86", () => {
  202. const installations = buildStandardChromeInstallations({
  203. platform: "win32",
  204. homeDir: "C:\\Users\\demo",
  205. localAppData: "C:\\Users\\demo\\AppData\\Local",
  206. programFiles: "C:\\Program Files",
  207. programFilesX86: "C:\\Program Files (x86)",
  208. });
  209. expect(installations.map((item) => item.browser)).toEqual([
  210. "chrome",
  211. "chrome-beta",
  212. "chrome-dev",
  213. "chrome-canary",
  214. "chrome-for-testing",
  215. "chromium",
  216. ]);
  217. expect(installations[0]?.executablePaths.join("\n")).toContain("Program Files (x86)");
  218. });
  219. it("Linux 标准候选覆盖 XDG、Snap 与 Flatpak Profile", () => {
  220. const installations = buildStandardChromeInstallations({
  221. platform: "linux",
  222. homeDir: "/home/demo",
  223. env: {},
  224. });
  225. // Bugfix:buildStandardChromeInstallations 用宿主 path.join 拼 userDataDir,Windows 上
  226. // 分隔符是 `\`,而这里原来写死 POSIX 字面量,用例在 Windows 上必然失败。改用宿主 join
  227. // 组装期望值,断言仍然表达同一组「XDG / Snap / Flatpak 数据目录」。
  228. expect(installations.map(({ userDataDir }) => userDataDir)).toEqual(
  229. expect.arrayContaining([
  230. join("/home/demo", ".config", "google-chrome"),
  231. join("/home/demo", ".config", "chromium"),
  232. join("/home/demo", "snap", "chromium", "common", "chromium"),
  233. join("/home/demo", ".var/app/com.google.Chrome/config/google-chrome"),
  234. join("/home/demo", ".var/app/org.chromium.Chromium/config/chromium"),
  235. ]),
  236. );
  237. expect(
  238. installations.find(({ userDataDir }) => userDataDir.includes("com.google.Chrome"))
  239. ?.executablePaths,
  240. ).toContain("/var/lib/flatpak/exports/bin/com.google.Chrome");
  241. });
  242. it("优先使用环境变量显式指定的非默认 Chrome 路径", async () => {
  243. const executablePath = join(tempRoot, "custom", "chrome");
  244. await mkdir(join(tempRoot, "custom"), { recursive: true });
  245. await writeFile(executablePath, "#!/bin/sh\n");
  246. await chmod(executablePath, 0o755);
  247. await expect(
  248. resolveChromeExecutablePath({
  249. platform: "linux",
  250. env: { CHROME_PATH: executablePath, PATH: "" },
  251. installations: [],
  252. processCommandLines: [],
  253. registeredExecutablePaths: [],
  254. }),
  255. ).resolves.toBe(executablePath);
  256. });
  257. it("从运行中的 Chrome 主进程发现非默认可执行文件", async () => {
  258. const executablePath = join(tempRoot, "portable", "chrome");
  259. await mkdir(join(tempRoot, "portable"), { recursive: true });
  260. await writeFile(executablePath, "#!/bin/sh\n");
  261. await chmod(executablePath, 0o755);
  262. await expect(
  263. resolveChromeExecutablePath({
  264. platform: "linux",
  265. env: { PATH: "" },
  266. installations: [],
  267. processCommandLines: [`${executablePath} --no-first-run`],
  268. registeredExecutablePaths: [],
  269. }),
  270. ).resolves.toBe(executablePath);
  271. });
  272. it("从 Linux PATH 发现非默认目录中的 Chrome", async () => {
  273. const binDir = join(tempRoot, "bin");
  274. const executablePath = join(binDir, "google-chrome-stable");
  275. await mkdir(binDir, { recursive: true });
  276. await writeFile(executablePath, "#!/bin/sh\n");
  277. await chmod(executablePath, 0o755);
  278. await expect(
  279. resolveChromeExecutablePath({
  280. platform: "linux",
  281. env: { PATH: binDir },
  282. installations: [],
  283. processCommandLines: [],
  284. registeredExecutablePaths: [],
  285. }),
  286. ).resolves.toBe(executablePath);
  287. });
  288. it("从 Linux XDG desktop entry 发现非默认目录中的 Chrome", async () => {
  289. const executablePath = join(tempRoot, "apps", "chromium");
  290. const xdgDataHome = join(tempRoot, "share");
  291. const applicationsDir = join(xdgDataHome, "applications");
  292. await mkdir(join(tempRoot, "apps"), { recursive: true });
  293. await mkdir(applicationsDir, { recursive: true });
  294. await writeFile(executablePath, "#!/bin/sh\n");
  295. await chmod(executablePath, 0o755);
  296. await writeFile(
  297. join(applicationsDir, "custom-browser.desktop"),
  298. `[Desktop Entry]\nType=Application\nName=Chrome\nExec="${executablePath}" %U\n`,
  299. );
  300. await expect(
  301. resolveChromeExecutablePath({
  302. platform: "linux",
  303. env: {
  304. PATH: "",
  305. XDG_DATA_HOME: xdgDataHome,
  306. XDG_DATA_DIRS: join(tempRoot, "empty-share"),
  307. },
  308. homeDir: tempRoot,
  309. installations: [],
  310. processCommandLines: [],
  311. }),
  312. ).resolves.toBe(executablePath);
  313. });
  314. it("接受 macOS Spotlight 已解析出的非默认应用可执行文件", async () => {
  315. const executablePath = join(tempRoot, "Browsers", "Google Chrome");
  316. await mkdir(join(tempRoot, "Browsers"), { recursive: true });
  317. await writeFile(executablePath, "#!/bin/sh\n");
  318. await chmod(executablePath, 0o755);
  319. await expect(
  320. resolveChromeExecutablePath({
  321. platform: "darwin",
  322. env: {},
  323. installations: [],
  324. processCommandLines: [],
  325. registeredExecutablePaths: [executablePath],
  326. }),
  327. ).resolves.toBe(executablePath);
  328. });
  329. it("所有安全来源都没有 Chrome 时返回未找到", async () => {
  330. await expect(
  331. resolveChromeExecutablePath({
  332. platform: "linux",
  333. env: { PATH: "" },
  334. installations: [],
  335. processCommandLines: [],
  336. registeredExecutablePaths: [],
  337. }),
  338. ).resolves.toBeNull();
  339. });
  340. });