browserDataManager.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { createCipheriv, pbkdf2Sync } from "node:crypto";
  3. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { backup, DatabaseSync } from "node:sqlite";
  7. const lockedChromeSidecars = vi.hoisted(() => new Set<string>());
  8. vi.mock("node:fs/promises", async () => {
  9. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  10. return {
  11. ...actual,
  12. stat: async (path: Parameters<typeof actual.stat>[0]) =>
  13. lockedChromeSidecars.has(String(path))
  14. ? ({} as Awaited<ReturnType<typeof actual.stat>>)
  15. : actual.stat(path),
  16. copyFile: async (
  17. source: Parameters<typeof actual.copyFile>[0],
  18. destination: Parameters<typeof actual.copyFile>[1],
  19. mode?: Parameters<typeof actual.copyFile>[2],
  20. ) => {
  21. if (lockedChromeSidecars.has(String(source))) {
  22. throw Object.assign(new Error("Chrome sidecar is locked"), { code: "EBUSY" });
  23. }
  24. return actual.copyFile(source, destination, mode);
  25. },
  26. };
  27. });
  28. vi.mock("electron", () => ({
  29. session: {
  30. fromPartition: vi.fn(),
  31. },
  32. }));
  33. import {
  34. clearEmbeddedBrowserData,
  35. importChromeBrowserData,
  36. resolveChromeDefaultProfilePath,
  37. } from "../src/main/browserDataManager.js";
  38. import {
  39. getEmbeddedBrowserSitePermissionSnapshot as snapshotSitePermissions,
  40. initEmbeddedBrowserSitePermissions,
  41. resetEmbeddedBrowserSitePermissionsForTest,
  42. writeEmbeddedBrowserSitePermission,
  43. } from "../src/main/embeddedBrowserSitePermissions.js";
  44. import {
  45. cleanupChromeHelperTempRoot,
  46. discoverChromeLocalStorageOrigins,
  47. importChromeLocalStorage,
  48. } from "../src/main/chromeLocalStorageManager.js";
  49. import { WindowsChromeAppBoundImportError } from "../src/main/windowsChromeAppBoundKey.js";
  50. const logger = {
  51. info: vi.fn(),
  52. warn: vi.fn(),
  53. };
  54. const localStorageResult = {
  55. originsImported: 2,
  56. entriesImported: 5,
  57. originsSkipped: 1,
  58. originsFailed: 0,
  59. };
  60. const localStorageImporter = vi.fn(async () => localStorageResult);
  61. let tempRoot = "";
  62. beforeEach(async () => {
  63. tempRoot = await mkdtemp(join(tmpdir(), "zcode-browser-data-test-"));
  64. lockedChromeSidecars.clear();
  65. vi.clearAllMocks();
  66. });
  67. afterEach(async () => {
  68. await rm(tempRoot, { recursive: true, force: true });
  69. });
  70. function createChromeProfile(
  71. options: { encryptedValue?: Buffer; modernCookiePath?: boolean; value?: string } = {},
  72. ): string {
  73. const profilePath = join(tempRoot, "Default");
  74. const cookieDatabasePath = options.modernCookiePath
  75. ? join(profilePath, "Network", "Cookies")
  76. : join(profilePath, "Cookies");
  77. const cookieDatabase = new DatabaseSync(cookieDatabasePath);
  78. cookieDatabase.exec(`
  79. CREATE TABLE meta (key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
  80. INSERT INTO meta (key, value) VALUES ('version', '23');
  81. CREATE TABLE cookies (
  82. host_key TEXT NOT NULL,
  83. name TEXT NOT NULL,
  84. path TEXT NOT NULL,
  85. expires_utc INTEGER NOT NULL,
  86. is_secure INTEGER NOT NULL,
  87. is_httponly INTEGER NOT NULL,
  88. samesite INTEGER NOT NULL,
  89. value TEXT NOT NULL,
  90. encrypted_value BLOB NOT NULL
  91. );
  92. `);
  93. cookieDatabase
  94. .prepare("INSERT INTO cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
  95. .run(
  96. "example.com",
  97. "session",
  98. "/",
  99. 0n,
  100. 1n,
  101. 1n,
  102. 1n,
  103. options.value ?? "fixture-value",
  104. options.encryptedValue ?? Buffer.alloc(0),
  105. );
  106. cookieDatabase.close();
  107. return profilePath;
  108. }
  109. function encryptLinuxV10Cookie(value: string): Buffer {
  110. const key = pbkdf2Sync("peanuts", "saltysalt", 1, 16, "sha1");
  111. const cipher = createCipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
  112. return Buffer.concat([Buffer.from("v10"), cipher.update(value), cipher.final()]);
  113. }
  114. function createFailingSourceBackup(): {
  115. databaseBackup: typeof backup;
  116. getCallCount: () => number;
  117. } {
  118. let callCount = 0;
  119. return {
  120. databaseBackup: async (sourceDatabase, destination, options) => {
  121. callCount += 1;
  122. if (callCount === 1) {
  123. throw Object.assign(new Error("source WAL lock unavailable"), {
  124. code: "ERR_SQLITE_ERROR",
  125. });
  126. }
  127. return options
  128. ? backup(sourceDatabase, destination, options)
  129. : backup(sourceDatabase, destination);
  130. },
  131. getCallCount: () => callCount,
  132. };
  133. }
  134. function encryptWindowsCookieV20(value: string, key: Buffer): Buffer {
  135. const nonce = Buffer.alloc(12, 7);
  136. const cipher = createCipheriv("aes-256-gcm", key, nonce);
  137. const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
  138. return Buffer.concat([Buffer.from("v20"), nonce, ciphertext, cipher.getAuthTag()]);
  139. }
  140. describe("browserDataManager", () => {
  141. it("Chrome helper 临时目录清理失败时不覆盖已读取结果", async () => {
  142. const cleanupError = Object.assign(new Error("directory is not empty"), {
  143. code: "ENOTEMPTY",
  144. });
  145. const remover = vi.fn(async () => {
  146. throw cleanupError;
  147. });
  148. await expect(
  149. cleanupChromeHelperTempRoot({ tempRoot, logger, remover }),
  150. ).resolves.toBeUndefined();
  151. expect(remover).toHaveBeenCalledWith(tempRoot, {
  152. recursive: true,
  153. force: true,
  154. maxRetries: 5,
  155. retryDelay: 100,
  156. });
  157. expect(logger.warn).toHaveBeenCalledWith("[browser-data] Chrome helper 临时目录清理失败", {
  158. name: "Error",
  159. code: "ENOTEMPTY",
  160. });
  161. });
  162. it("使用 createRequire 加载 node:sqlite,避免桌面 bundle 丢失 node: 前缀", async () => {
  163. const source = await readFile(
  164. join(import.meta.dirname, "../src/main/chromeCookieManager.ts"),
  165. "utf8",
  166. );
  167. expect(source).toMatch(/nodeRequire\(\s*"node:sqlite",?\s*\)/);
  168. expect(source).not.toContain('await import("node:sqlite")');
  169. });
  170. it("按操作系统定位 Chrome Default Profile", () => {
  171. // Bugfix:resolveChromeDefaultProfilePath 用宿主 path.join 拼接,Windows 上分隔符是 `\`,
  172. // 而这里原来写死 POSIX 字面量,三条断言在 Windows 上都对不上。改用宿主 join 组装期望值,
  173. // 断言仍然表达同一个「各系统 Chrome Default Profile 布局」。
  174. expect(
  175. resolveChromeDefaultProfilePath({
  176. platform: "darwin",
  177. homeDir: "/Users/demo",
  178. }),
  179. ).toBe(join("/Users/demo", "Library", "Application Support", "Google", "Chrome", "Default"));
  180. expect(
  181. resolveChromeDefaultProfilePath({
  182. platform: "win32",
  183. homeDir: "C:\\Users\\demo",
  184. localAppData: "C:\\Users\\demo\\AppData\\Local",
  185. }),
  186. ).toContain(join("Google", "Chrome", "User Data", "Default"));
  187. expect(
  188. resolveChromeDefaultProfilePath({
  189. platform: "linux",
  190. homeDir: "/home/demo",
  191. }),
  192. ).toBe(join("/home/demo", ".config", "google-chrome", "Default"));
  193. });
  194. it("一键导入 Default Profile 的明文 Cookie", async () => {
  195. await mkdir(join(tempRoot, "Default"), { recursive: true });
  196. const profilePath = createChromeProfile();
  197. const set = vi.fn(async () => {});
  198. const flushStore = vi.fn(async () => {});
  199. const targetSession = {
  200. clearCache: vi.fn(async () => {}),
  201. clearStorageData: vi.fn(async () => {}),
  202. cookies: { set, flushStore },
  203. };
  204. const importedAt = Math.floor(Date.now() / 1000);
  205. const result = await importChromeBrowserData({
  206. logger,
  207. platform: "linux",
  208. profilePath,
  209. targetSession,
  210. localStorageImporter,
  211. });
  212. expect(result).toMatchObject({
  213. success: true,
  214. cookies: { imported: 1, skipped: 0, failed: 0 },
  215. localStorage: localStorageResult,
  216. });
  217. expect(set).toHaveBeenCalledWith(
  218. expect.objectContaining({
  219. url: "https://example.com/",
  220. name: "session",
  221. value: "fixture-value",
  222. httpOnly: true,
  223. sameSite: "lax",
  224. expirationDate: expect.any(Number),
  225. }),
  226. );
  227. const cookieDetails = set.mock.calls[0]?.[0];
  228. expect(cookieDetails?.expirationDate).toBeGreaterThan(importedAt + 399 * 24 * 60 * 60);
  229. expect(flushStore).toHaveBeenCalledOnce();
  230. expect(logger.info).toHaveBeenCalledWith("[browser-data] Chrome Cookie 写入完成", {
  231. importedCount: 1,
  232. skippedCount: 0,
  233. failedCount: 0,
  234. });
  235. });
  236. it("兼容新版 Chrome 的 Network/Cookies 数据库路径", async () => {
  237. await mkdir(join(tempRoot, "Default", "Network"), { recursive: true });
  238. const profilePath = createChromeProfile({ modernCookiePath: true });
  239. const set = vi.fn(async () => {});
  240. const result = await importChromeBrowserData({
  241. logger,
  242. platform: "linux",
  243. profilePath,
  244. localStorageImporter,
  245. targetSession: {
  246. clearCache: vi.fn(async () => {}),
  247. clearStorageData: vi.fn(async () => {}),
  248. cookies: { set, flushStore: vi.fn(async () => {}) },
  249. },
  250. });
  251. expect(result.success).toBe(true);
  252. expect(set).toHaveBeenCalledOnce();
  253. });
  254. it("在线备份失败后不复制 Windows 可能锁定的 SHM", async () => {
  255. await mkdir(join(tempRoot, "Default"), { recursive: true });
  256. const profilePath = createChromeProfile();
  257. const cookieDatabasePath = join(profilePath, "Cookies");
  258. // Windows 的占用锁无法在非 Windows CI 精确构造;这里让文件系统报告 SHM
  259. // 存在且 copyFile 返回 EBUSY,证明 fallback 只复制持久化主库/WAL。
  260. lockedChromeSidecars.add(`${cookieDatabasePath}-shm`);
  261. const failingBackup = createFailingSourceBackup();
  262. const set = vi.fn(async () => {});
  263. const result = await importChromeBrowserData({
  264. chromeCookieDatabaseBackup: failingBackup.databaseBackup,
  265. logger,
  266. platform: "linux",
  267. profilePath,
  268. localStorageImporter,
  269. targetSession: {
  270. clearCache: vi.fn(async () => {}),
  271. clearStorageData: vi.fn(async () => {}),
  272. cookies: { set, flushStore: vi.fn(async () => {}) },
  273. },
  274. });
  275. expect(result.success).toBe(true);
  276. expect(set).toHaveBeenCalledOnce();
  277. expect(failingBackup.getCallCount()).toBe(2);
  278. expect(logger.warn).toHaveBeenCalledWith(
  279. "[browser-data] Chrome Cookie 在线备份不可用,回退 WAL 文件快照",
  280. { name: "Error", code: "ERR_SQLITE_ERROR" },
  281. );
  282. });
  283. it("在线备份失败后从文件快照保留 Chrome WAL 中已提交的 Cookie", async () => {
  284. await mkdir(join(tempRoot, "Default"), { recursive: true });
  285. const profilePath = createChromeProfile();
  286. const database = new DatabaseSync(join(profilePath, "Cookies"));
  287. database.exec("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0;");
  288. database
  289. .prepare("INSERT INTO cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
  290. .run("wal.example.com", "wal-session", "/", 0n, 1n, 0n, 0n, "wal-value", Buffer.alloc(0));
  291. const failingBackup = createFailingSourceBackup();
  292. const set = vi.fn(async () => {});
  293. try {
  294. const result = await importChromeBrowserData({
  295. chromeCookieDatabaseBackup: failingBackup.databaseBackup,
  296. logger,
  297. platform: "linux",
  298. profilePath,
  299. localStorageImporter,
  300. targetSession: {
  301. clearCache: vi.fn(async () => {}),
  302. clearStorageData: vi.fn(async () => {}),
  303. cookies: { set, flushStore: vi.fn(async () => {}) },
  304. },
  305. });
  306. expect(result).toMatchObject({
  307. success: true,
  308. cookies: { imported: 2, skipped: 0, failed: 0 },
  309. });
  310. expect(set).toHaveBeenCalledWith(
  311. expect.objectContaining({ name: "wal-session", value: "wal-value" }),
  312. );
  313. expect(failingBackup.getCallCount()).toBe(2);
  314. } finally {
  315. database.close();
  316. }
  317. });
  318. it("Chrome Profile 不存在时返回可操作错误", async () => {
  319. const result = await importChromeBrowserData({
  320. logger,
  321. profilePath: join(tempRoot, "missing"),
  322. });
  323. expect(result).toMatchObject({
  324. success: false,
  325. error: "chrome_profile_not_found",
  326. cookies: { imported: 0 },
  327. });
  328. });
  329. it("macOS/Linux 未安装 Chrome 时在 Profile 发现前停止导入", async () => {
  330. const chromeExecutableDiscovery = vi.fn(async () => null);
  331. const chromeProfileDiscovery = vi.fn(async () => ({
  332. success: false as const,
  333. error: "chrome_profile_not_found" as const,
  334. }));
  335. const result = await importChromeBrowserData({
  336. logger,
  337. platform: "linux",
  338. chromeExecutableDiscovery,
  339. chromeProfileDiscovery,
  340. });
  341. expect(result).toMatchObject({
  342. success: false,
  343. error: "chrome_executable_not_found",
  344. cookies: { imported: 0 },
  345. });
  346. expect(chromeExecutableDiscovery).toHaveBeenCalledOnce();
  347. expect(chromeProfileDiscovery).not.toHaveBeenCalled();
  348. expect(localStorageImporter).not.toHaveBeenCalled();
  349. });
  350. it("Profile 自动发现无法消歧时不修改目标 session", async () => {
  351. const result = await importChromeBrowserData({
  352. logger,
  353. // 该用例只验证 profile 消歧失败;显式注入 executable,避免依赖测试机是否安装 Chrome。
  354. chromeExecutableDiscovery: async () => "/usr/bin/google-chrome",
  355. chromeProfileDiscovery: async () => ({
  356. success: false,
  357. error: "chrome_profile_ambiguous",
  358. }),
  359. });
  360. expect(result).toMatchObject({
  361. success: false,
  362. error: "chrome_profile_ambiguous",
  363. cookies: { imported: 0 },
  364. });
  365. });
  366. it("macOS 用户拒绝钥匙串授权后终止整次导入", async () => {
  367. await mkdir(join(tempRoot, "Default"), { recursive: true });
  368. const profilePath = createChromeProfile({
  369. value: "",
  370. encryptedValue: Buffer.concat([Buffer.from("v10"), Buffer.alloc(48, 1)]),
  371. });
  372. const set = vi.fn(async () => {});
  373. const flushStore = vi.fn(async () => {});
  374. const deniedError = Object.assign(new Error("User canceled the operation"), { code: 128 });
  375. const macChromeSafeStorageSecretReader = vi.fn(async () => {
  376. throw deniedError;
  377. });
  378. const result = await importChromeBrowserData({
  379. logger,
  380. platform: "darwin",
  381. profilePath,
  382. macChromeSafeStorageSecretReader,
  383. localStorageImporter,
  384. targetSession: {
  385. clearCache: vi.fn(async () => {}),
  386. clearStorageData: vi.fn(async () => {}),
  387. cookies: { set, flushStore },
  388. },
  389. });
  390. expect(result).toMatchObject({
  391. success: false,
  392. error: "chrome_cookie_access_denied",
  393. cookies: { imported: 0, skipped: 0, failed: 0 },
  394. localStorage: {
  395. originsImported: 0,
  396. entriesImported: 0,
  397. originsSkipped: 0,
  398. originsFailed: 0,
  399. },
  400. });
  401. expect(macChromeSafeStorageSecretReader).toHaveBeenCalledOnce();
  402. expect(set).not.toHaveBeenCalled();
  403. expect(flushStore).not.toHaveBeenCalled();
  404. expect(localStorageImporter).not.toHaveBeenCalled();
  405. expect(logger.warn).toHaveBeenCalledWith(
  406. "[browser-data] Chrome 数据导入已取消:macOS 钥匙串授权被拒绝",
  407. );
  408. });
  409. it("Linux v10 Cookie 继续在本进程解密,不启动 Chrome helper", async () => {
  410. await mkdir(join(tempRoot, "Default"), { recursive: true });
  411. const profilePath = createChromeProfile({
  412. value: "",
  413. encryptedValue: encryptLinuxV10Cookie("linux-v10-value"),
  414. });
  415. const chromeCookieHelper = vi.fn(async () => []);
  416. const set = vi.fn(async () => {});
  417. const result = await importChromeBrowserData({
  418. logger,
  419. platform: "linux",
  420. profilePath,
  421. chromeExecutablePath: "/usr/bin/google-chrome",
  422. chromeCookieHelper,
  423. localStorageImporter,
  424. targetSession: {
  425. clearCache: vi.fn(async () => {}),
  426. clearStorageData: vi.fn(async () => {}),
  427. cookies: { set, flushStore: vi.fn(async () => {}) },
  428. },
  429. });
  430. expect(result).toMatchObject({
  431. success: true,
  432. cookies: { imported: 1, skipped: 0, failed: 0 },
  433. });
  434. expect(chromeCookieHelper).not.toHaveBeenCalled();
  435. expect(set).toHaveBeenCalledWith(expect.objectContaining({ value: "linux-v10-value" }));
  436. });
  437. it("Linux v11 Cookie 由同品牌 Chrome helper 解密并转发 KWallet 后端", async () => {
  438. await mkdir(join(tempRoot, "Default"), { recursive: true });
  439. const profilePath = createChromeProfile({
  440. value: "",
  441. encryptedValue: Buffer.concat([Buffer.from("v11"), Buffer.alloc(48, 1)]),
  442. });
  443. const chromeCookieHelper = vi.fn(async () => [
  444. {
  445. domain: ".example.com",
  446. expires: 0,
  447. httpOnly: true,
  448. name: "session",
  449. path: "/",
  450. sameSite: "Lax" as const,
  451. secure: true,
  452. session: true,
  453. value: "linux-v11-value",
  454. },
  455. ]);
  456. const set = vi.fn(async () => {});
  457. const result = await importChromeBrowserData({
  458. logger,
  459. platform: "linux",
  460. // Bugfix:这条用例既不传 profilePath 也不传 chromeExecutablePath,
  461. // importChromeBrowserData 会先做可执行文件发现(browserDataManager.ts:124),
  462. // 在非 Linux 宿主上探测不到 /usr/bin/google-chrome,直接以
  463. // chrome_executable_not_found 返回,chromeProfileDiscovery 根本不会被调用,
  464. // helper 断言只能看到 0 次调用。这里注入发现结果,让用例只考察
  465. // 「v11 Cookie 交给同品牌 helper 并转发 KWallet 后端」这一件事,不依赖宿主是否装了 Chrome。
  466. chromeExecutableDiscovery: async () => "/usr/bin/google-chrome",
  467. chromeProfileDiscovery: async () => ({
  468. success: true,
  469. source: {
  470. browser: "chrome",
  471. executablePath: "/usr/bin/google-chrome",
  472. passwordStore: "kwallet6",
  473. profileDirectory: "Default",
  474. profilePath,
  475. userDataDir: tempRoot,
  476. },
  477. }),
  478. chromeCookieHelper,
  479. localStorageImporter,
  480. targetSession: {
  481. clearCache: vi.fn(async () => {}),
  482. clearStorageData: vi.fn(async () => {}),
  483. cookies: { set, flushStore: vi.fn(async () => {}) },
  484. },
  485. });
  486. expect(chromeCookieHelper).toHaveBeenCalledWith(
  487. expect.objectContaining({
  488. executablePath: "/usr/bin/google-chrome",
  489. passwordStore: "kwallet6",
  490. }),
  491. );
  492. expect(result).toMatchObject({
  493. success: true,
  494. cookies: { imported: 1, skipped: 0, failed: 0 },
  495. });
  496. expect(set).toHaveBeenCalledWith(expect.objectContaining({ value: "linux-v11-value" }));
  497. });
  498. it("Linux v11 helper 不可用时保留 LocalStorage 并返回保护提示", async () => {
  499. await mkdir(join(tempRoot, "Default"), { recursive: true });
  500. const profilePath = createChromeProfile({
  501. value: "",
  502. encryptedValue: Buffer.concat([Buffer.from("v11"), Buffer.alloc(48, 1)]),
  503. });
  504. const result = await importChromeBrowserData({
  505. logger,
  506. platform: "linux",
  507. profilePath,
  508. chromeExecutablePath: "/usr/bin/google-chrome",
  509. chromeCookieHelper: vi.fn(async () => {
  510. throw new Error("keyring unavailable");
  511. }),
  512. localStorageImporter,
  513. targetSession: {
  514. clearCache: vi.fn(async () => {}),
  515. clearStorageData: vi.fn(async () => {}),
  516. cookies: {
  517. set: vi.fn(async () => {}),
  518. flushStore: vi.fn(async () => {}),
  519. },
  520. },
  521. });
  522. expect(result).toMatchObject({
  523. success: true,
  524. cookies: { imported: 0, skipped: 1 },
  525. localStorage: localStorageResult,
  526. issues: expect.arrayContaining(["chrome_cookie_protection_unsupported"]),
  527. });
  528. });
  529. it("Windows v20 Cookie 在本次管理员授权后由原生 helper 解密", async () => {
  530. await mkdir(join(tempRoot, "Default"), { recursive: true });
  531. const masterKey = Buffer.alloc(32, 9);
  532. const profilePath = createChromeProfile({
  533. value: "",
  534. encryptedValue: encryptWindowsCookieV20("helper-value", masterKey),
  535. });
  536. const helperResult = Buffer.from(masterKey);
  537. const windowsChromeAppBoundKeyReader = vi.fn(async () => helperResult);
  538. const failingBackup = createFailingSourceBackup();
  539. const set = vi.fn(async () => {});
  540. const result = await importChromeBrowserData({
  541. allowElevatedChromeDecryption: true,
  542. chromeCookieDatabaseBackup: failingBackup.databaseBackup,
  543. logger,
  544. platform: "win32",
  545. profilePath,
  546. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  547. windowsChromeAppBoundKeyReader,
  548. localStorageImporter,
  549. targetSession: {
  550. clearCache: vi.fn(async () => {}),
  551. clearStorageData: vi.fn(async () => {}),
  552. cookies: { set, flushStore: vi.fn(async () => {}) },
  553. },
  554. });
  555. expect(windowsChromeAppBoundKeyReader).toHaveBeenCalledOnce();
  556. expect(failingBackup.getCallCount()).toBe(2);
  557. expect(windowsChromeAppBoundKeyReader).toHaveBeenCalledWith(
  558. expect.objectContaining({
  559. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  560. userDataDir: tempRoot,
  561. }),
  562. );
  563. expect(result).toMatchObject({
  564. success: true,
  565. cookies: { imported: 1, skipped: 0, failed: 0 },
  566. });
  567. expect(set).toHaveBeenCalledWith(
  568. expect.objectContaining({ value: "helper-value", url: "https://example.com/" }),
  569. );
  570. expect(helperResult.every((value) => value === 0)).toBe(true);
  571. });
  572. it("Windows v20 helper 不可用时保留 LocalStorage 并返回稳定错误", async () => {
  573. await mkdir(join(tempRoot, "Default"), { recursive: true });
  574. const profilePath = createChromeProfile({
  575. value: "",
  576. encryptedValue: Buffer.concat([Buffer.from("v20"), Buffer.alloc(48, 1)]),
  577. });
  578. const result = await importChromeBrowserData({
  579. allowElevatedChromeDecryption: true,
  580. logger,
  581. platform: "win32",
  582. profilePath,
  583. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  584. windowsChromeAppBoundKeyReader: vi.fn(async () => {
  585. throw new WindowsChromeAppBoundImportError("chrome_cookie_helper_verification_failed");
  586. }),
  587. localStorageImporter,
  588. targetSession: {
  589. clearCache: vi.fn(async () => {}),
  590. clearStorageData: vi.fn(async () => {}),
  591. cookies: {
  592. set: vi.fn(async () => {}),
  593. flushStore: vi.fn(async () => {}),
  594. },
  595. },
  596. });
  597. expect(result).toMatchObject({
  598. success: true,
  599. cookies: { imported: 0, skipped: 1 },
  600. localStorage: localStorageResult,
  601. issues: expect.arrayContaining(["chrome_cookie_helper_verification_failed"]),
  602. });
  603. });
  604. it("Windows v20 授权失败时整批 Cookie 都不写入", async () => {
  605. await mkdir(join(tempRoot, "Default"), { recursive: true });
  606. const profilePath = createChromeProfile({
  607. value: "",
  608. encryptedValue: Buffer.concat([Buffer.from("v20"), Buffer.alloc(48, 1)]),
  609. });
  610. const cookieDatabase = new DatabaseSync(join(profilePath, "Cookies"));
  611. cookieDatabase
  612. .prepare("INSERT INTO cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
  613. .run("plain.example.com", "plain", "/", 0n, 1n, 1n, 1n, "plain-value", Buffer.alloc(0));
  614. cookieDatabase.close();
  615. const set = vi.fn(async () => {});
  616. const result = await importChromeBrowserData({
  617. allowElevatedChromeDecryption: true,
  618. logger,
  619. platform: "win32",
  620. profilePath,
  621. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  622. windowsChromeAppBoundKeyReader: vi.fn(async () => {
  623. throw new WindowsChromeAppBoundImportError("chrome_cookie_elevation_cancelled");
  624. }),
  625. localStorageImporter,
  626. targetSession: {
  627. clearCache: vi.fn(async () => {}),
  628. clearStorageData: vi.fn(async () => {}),
  629. cookies: { set, flushStore: vi.fn(async () => {}) },
  630. },
  631. });
  632. expect(set).not.toHaveBeenCalled();
  633. expect(result).toMatchObject({
  634. success: true,
  635. cookies: { imported: 0, skipped: 2, failed: 0 },
  636. localStorage: localStorageResult,
  637. issues: expect.arrayContaining(["chrome_cookie_elevation_cancelled"]),
  638. });
  639. });
  640. it("Windows 未获得本次确认时不启动 helper,但仍可导入 LocalStorage", async () => {
  641. await mkdir(join(tempRoot, "Default"), { recursive: true });
  642. const profilePath = createChromeProfile({
  643. value: "",
  644. encryptedValue: Buffer.concat([Buffer.from("v20"), Buffer.alloc(48, 1)]),
  645. });
  646. const windowsChromeAppBoundKeyReader = vi.fn(async () => Buffer.alloc(32));
  647. const result = await importChromeBrowserData({
  648. logger,
  649. platform: "win32",
  650. profilePath,
  651. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  652. windowsChromeAppBoundKeyReader,
  653. localStorageImporter,
  654. targetSession: {
  655. clearCache: vi.fn(async () => {}),
  656. clearStorageData: vi.fn(async () => {}),
  657. cookies: { set: vi.fn(async () => {}), flushStore: vi.fn(async () => {}) },
  658. },
  659. });
  660. expect(windowsChromeAppBoundKeyReader).not.toHaveBeenCalled();
  661. expect(result).toMatchObject({
  662. success: true,
  663. localStorage: localStorageResult,
  664. issues: expect.arrayContaining(["chrome_cookie_elevation_required"]),
  665. });
  666. });
  667. it("没有 Cookie 数据库时仍可只导入 LocalStorage", async () => {
  668. const profilePath = join(tempRoot, "Default");
  669. await mkdir(profilePath, { recursive: true });
  670. const result = await importChromeBrowserData({
  671. logger,
  672. profilePath,
  673. localStorageImporter,
  674. targetSession: {
  675. clearCache: vi.fn(async () => {}),
  676. clearStorageData: vi.fn(async () => {}),
  677. cookies: {
  678. set: vi.fn(async () => {}),
  679. flushStore: vi.fn(async () => {}),
  680. },
  681. },
  682. });
  683. expect(result).toMatchObject({
  684. success: true,
  685. cookies: { imported: 0 },
  686. localStorage: localStorageResult,
  687. });
  688. });
  689. it("只从 Chrome LocalStorage metadata key 发现 HTTP(S) origin", async () => {
  690. const localStoragePath = join(tempRoot, "Local Storage");
  691. const levelDbPath = join(localStoragePath, "leveldb");
  692. await mkdir(levelDbPath, { recursive: true });
  693. await writeFile(
  694. join(levelDbPath, "000001.ldb"),
  695. Buffer.from(
  696. "binary\0META:https://chat.z.ai\0META:http://localhost:3000\0META:chrome-extension://ignored",
  697. "latin1",
  698. ),
  699. );
  700. await expect(discoverChromeLocalStorageOrigins(localStoragePath)).resolves.toEqual([
  701. "http://localhost:3000",
  702. "https://chat.z.ai",
  703. ]);
  704. });
  705. it("先复制 LocalStorage 快照,再从快照发现 origin", async () => {
  706. const profilePath = join(tempRoot, "Default");
  707. const levelDbPath = join(profilePath, "Local Storage", "leveldb");
  708. await mkdir(levelDbPath, { recursive: true });
  709. await writeFile(
  710. join(levelDbPath, "000001.ldb"),
  711. Buffer.from("binary\0META:https://chat.z.ai", "latin1"),
  712. );
  713. const result = await importChromeLocalStorage({
  714. profilePath,
  715. platform: "aix",
  716. logger,
  717. targetSession: {} as Electron.Session,
  718. });
  719. expect(result).toMatchObject({
  720. originsImported: 0,
  721. originsFailed: 1,
  722. error: "chrome_executable_not_found",
  723. });
  724. });
  725. it("普通清理保留 Cookie,全量清理使用 Electron 全存储清理", async () => {
  726. const clearCache = vi.fn(async () => {});
  727. const clearStorageData = vi.fn(async () => {});
  728. const targetSession = {
  729. clearCache,
  730. clearStorageData,
  731. cookies: {
  732. set: vi.fn(async () => {}),
  733. flushStore: vi.fn(async () => {}),
  734. },
  735. };
  736. await clearEmbeddedBrowserData({ logger, mode: "cache", targetSession });
  737. expect(clearStorageData).toHaveBeenNthCalledWith(1, {
  738. storages: ["shadercache", "serviceworkers", "cachestorage"],
  739. });
  740. await clearEmbeddedBrowserData({ logger, mode: "all", targetSession });
  741. expect(clearStorageData).toHaveBeenNthCalledWith(2);
  742. expect(clearCache).toHaveBeenCalledTimes(2);
  743. });
  744. it("全量清理同时清空站点权限同意记录,普通清理保留", async () => {
  745. const clearCache = vi.fn(async () => {});
  746. const clearStorageData = vi.fn(async () => {});
  747. const targetSession = {
  748. clearCache,
  749. clearStorageData,
  750. cookies: { set: vi.fn(async () => {}), flushStore: vi.fn(async () => {}) },
  751. };
  752. resetEmbeddedBrowserSitePermissionsForTest();
  753. await initEmbeddedBrowserSitePermissions({ logger });
  754. await writeEmbeddedBrowserSitePermission("https://example.com", "media", "allow");
  755. await clearEmbeddedBrowserData({ logger, mode: "cache", targetSession });
  756. expect(snapshotSitePermissions()).toEqual({
  757. "https://example.com": { media: "allow" },
  758. });
  759. await clearEmbeddedBrowserData({ logger, mode: "all", targetSession });
  760. expect(snapshotSitePermissions()).toEqual({});
  761. resetEmbeddedBrowserSitePermissionsForTest();
  762. });
  763. });