chromeCookieManager.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /* eslint-disable max-lines */
  2. // 安全说明:Cookie 快照、跨平台解密选择与整批写入必须留在同一事务审计边界,
  3. // 避免拆分后让 Windows App-Bound 原子失败语义与 Linux helper 回退顺序发生漂移。
  4. import { createDecipheriv, pbkdf2Sync } from "node:crypto";
  5. import { copyFile, mkdtemp, rm, stat } from "node:fs/promises";
  6. import { createRequire } from "node:module";
  7. import { tmpdir } from "node:os";
  8. import { dirname, join, relative } from "node:path";
  9. import type { ChromeBrowserDataImportError } from "@zcode/shared";
  10. import { readChromeCookiesWithHelper } from "./chromeLocalStorageManager.js";
  11. import {
  12. toCookieDetails,
  13. toCookieDetailsFromHelper,
  14. type ChromeCookieRow,
  15. } from "./chromeCookieMapping.js";
  16. import {
  17. ChromeCookieAccessDeniedError,
  18. readMacChromeSafeStorageSecret,
  19. readWindowsChromeMasterKey,
  20. type MacChromeSafeStorageSecretReader,
  21. } from "./chromeCredentialManager.js";
  22. import type { LinuxChromePasswordStore } from "./chromeInstallationCandidates.js";
  23. import {
  24. readWindowsChromeAppBoundKey,
  25. WindowsChromeAppBoundImportError,
  26. type WindowsChromeAppBoundKeyReader,
  27. } from "./windowsChromeAppBoundKey.js";
  28. const nodeRequire = createRequire(import.meta.url);
  29. // tsup/esbuild 会把动态 import("node:sqlite") 错误改写为 import("sqlite"),
  30. // Electron 运行时因此报 ERR_MODULE_NOT_FOUND。createRequire 能稳定保留 node: 协议。
  31. const { DatabaseSync, backup } = nodeRequire("node:sqlite") as typeof import("node:sqlite");
  32. const COOKIE_IMPORT_CONCURRENCY = 32;
  33. const DATABASE_SNAPSHOT_COPY_ATTEMPTS = 3;
  34. interface BrowserDataLogger {
  35. info: (...args: unknown[]) => void;
  36. warn: (...args: unknown[]) => void;
  37. }
  38. interface CookieTargetSession {
  39. cookies: {
  40. set(details: Electron.CookiesSetDetails): Promise<void>;
  41. flushStore(): Promise<void>;
  42. };
  43. }
  44. type CookieDecryptor = (encrypted: Uint8Array, hostKey: string, schemaVersion: number) => string;
  45. export type ChromeCookieHelper = typeof readChromeCookiesWithHelper;
  46. export type ChromeCookieDatabaseBackup = typeof backup;
  47. interface CookieDecryptorResource {
  48. decrypt: CookieDecryptor;
  49. dispose(): void;
  50. }
  51. export interface ChromeCookieImportResult {
  52. databaseFound: boolean;
  53. issues: ChromeBrowserDataImportError[];
  54. rowCount: number;
  55. stats: {
  56. imported: number;
  57. skipped: number;
  58. failed: number;
  59. };
  60. }
  61. function pathExists(path: string): Promise<boolean> {
  62. return stat(path).then(
  63. () => true,
  64. () => false,
  65. );
  66. }
  67. function toSafeBrowserDataError(error: unknown): { name: string; code?: string } {
  68. if (!(error instanceof Error)) return { name: "UnknownError" };
  69. const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
  70. return { name: error.name || "Error", ...(code ? { code } : {}) };
  71. }
  72. function stripChromeHostDigest(value: Buffer, schemaVersion: number): Buffer {
  73. // Chrome Cookie schema 24+ 在加密明文前附加 SHA-256(host_key);这里只移除固定长度摘要。
  74. return schemaVersion >= 24 && value.length >= 32 ? value.subarray(32) : value;
  75. }
  76. function createCbcDecryptor(secret: string, iterations: number): CookieDecryptorResource {
  77. const key = pbkdf2Sync(secret, "saltysalt", iterations, 16, "sha1");
  78. return {
  79. decrypt: (encrypted, _hostKey, schemaVersion) => {
  80. const buffer = Buffer.from(encrypted);
  81. if (buffer.subarray(0, 3).toString("ascii") !== "v10") {
  82. throw new Error("chrome_cookie_encryption_unsupported");
  83. }
  84. const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
  85. const decrypted = Buffer.concat([decipher.update(buffer.subarray(3)), decipher.final()]);
  86. try {
  87. return stripChromeHostDigest(decrypted, schemaVersion).toString("utf8");
  88. } finally {
  89. decrypted.fill(0);
  90. }
  91. },
  92. dispose: () => key.fill(0),
  93. };
  94. }
  95. function createWindowsGcmDecryptor(
  96. masterKey: Buffer,
  97. acceptedPrefixes: ReadonlySet<string>,
  98. ): CookieDecryptorResource {
  99. return {
  100. decrypt: (encrypted, _hostKey, schemaVersion) => {
  101. const buffer = Buffer.from(encrypted);
  102. const prefix = buffer.subarray(0, 3).toString("ascii");
  103. if (!acceptedPrefixes.has(prefix)) {
  104. throw new Error("chrome_cookie_encryption_unsupported");
  105. }
  106. const nonce = buffer.subarray(3, 15);
  107. const authTag = buffer.subarray(buffer.length - 16);
  108. const ciphertext = buffer.subarray(15, buffer.length - 16);
  109. const decipher = createDecipheriv("aes-256-gcm", masterKey, nonce);
  110. decipher.setAuthTag(authTag);
  111. const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
  112. try {
  113. return stripChromeHostDigest(decrypted, schemaVersion).toString("utf8");
  114. } finally {
  115. decrypted.fill(0);
  116. }
  117. },
  118. dispose: () => masterKey.fill(0),
  119. };
  120. }
  121. async function createCookieDecryptor(
  122. platform: NodeJS.Platform,
  123. profilePath: string,
  124. macChromeSafeStorageSecretReader?: MacChromeSafeStorageSecretReader,
  125. ): Promise<CookieDecryptorResource> {
  126. if (platform === "darwin") {
  127. return createCbcDecryptor(
  128. await readMacChromeSafeStorageSecret(macChromeSafeStorageSecretReader),
  129. 1003,
  130. );
  131. }
  132. if (platform === "win32") {
  133. return createWindowsGcmDecryptor(
  134. await readWindowsChromeMasterKey(dirname(profilePath)),
  135. new Set(["v10", "v11"]),
  136. );
  137. }
  138. return createCbcDecryptor("peanuts", 1);
  139. }
  140. async function withDatabaseSnapshot<T>(
  141. sourcePath: string,
  142. logger: BrowserDataLogger,
  143. databaseBackup: ChromeCookieDatabaseBackup,
  144. run: (snapshotPath: string) => T | Promise<T>,
  145. ): Promise<T> {
  146. const tempDir = await mkdtemp(join(tmpdir(), "zcode-browser-import-"));
  147. const snapshotPath = join(tempDir, "database.sqlite");
  148. let sourceDatabase: import("node:sqlite").DatabaseSync | null = null;
  149. try {
  150. try {
  151. sourceDatabase = new DatabaseSync(sourcePath, { readOnly: true });
  152. await databaseBackup(sourceDatabase, snapshotPath);
  153. sourceDatabase.close();
  154. sourceDatabase = null;
  155. } catch (onlineBackupError) {
  156. sourceDatabase?.close();
  157. sourceDatabase = null;
  158. logger.warn(
  159. "[browser-data] Chrome Cookie 在线备份不可用,回退 WAL 文件快照",
  160. toSafeBrowserDataError(onlineBackupError),
  161. );
  162. let fallbackError: unknown = onlineBackupError;
  163. for (let attempt = 1; attempt <= DATABASE_SNAPSHOT_COPY_ATTEMPTS; attempt += 1) {
  164. const stagedPath = join(tempDir, `source-${attempt}.sqlite`);
  165. let stagedDatabase: import("node:sqlite").DatabaseSync | null = null;
  166. try {
  167. await rm(snapshotPath, { force: true });
  168. await copyFile(sourcePath, stagedPath);
  169. const sourceWalPath = `${sourcePath}-wal`;
  170. if (await pathExists(sourceWalPath)) {
  171. await copyFile(sourceWalPath, `${stagedPath}-wal`);
  172. }
  173. // Chrome 的 SHM 仅用于并发协调且在 Windows 上可能被独占锁定。
  174. // 临时目录中的 SQLite 会自行重建 SHM,再通过 Online Backup 固化并校验主库与 WAL。
  175. stagedDatabase = new DatabaseSync(stagedPath, { readOnly: true });
  176. await databaseBackup(stagedDatabase, snapshotPath);
  177. stagedDatabase.close();
  178. stagedDatabase = null;
  179. logger.info("[browser-data] Chrome Cookie WAL 文件快照完成", { attempt });
  180. fallbackError = null;
  181. break;
  182. } catch (error) {
  183. fallbackError = error;
  184. } finally {
  185. stagedDatabase?.close();
  186. await rm(stagedPath, { force: true });
  187. await rm(`${stagedPath}-wal`, { force: true });
  188. await rm(`${stagedPath}-shm`, { force: true });
  189. }
  190. }
  191. if (fallbackError) {
  192. logger.warn(
  193. "[browser-data] Chrome Cookie WAL 文件快照失败",
  194. toSafeBrowserDataError(fallbackError),
  195. );
  196. throw fallbackError;
  197. }
  198. }
  199. return await run(snapshotPath);
  200. } finally {
  201. // TypeScript 会把前面显式置空后的 finally 路径收窄成 never,
  202. // 但 SQLite backup 在异常边界仍可能留下句柄;保留运行时兜底并显式恢复实际联合类型。
  203. const danglingDatabase = sourceDatabase as import("node:sqlite").DatabaseSync | null;
  204. danglingDatabase?.close();
  205. await rm(tempDir, { recursive: true, force: true });
  206. }
  207. }
  208. async function readChromeCookies(databasePath: string): Promise<{
  209. rows: ChromeCookieRow[];
  210. schemaVersion: number;
  211. }> {
  212. const database = new DatabaseSync(databasePath, { readOnly: true });
  213. try {
  214. const versionRow = database.prepare("SELECT value FROM meta WHERE key = 'version'").get() as
  215. | { value?: string }
  216. | undefined;
  217. const statement = database.prepare(
  218. "SELECT host_key, name, path, expires_utc, is_secure, is_httponly, samesite, value, encrypted_value FROM cookies",
  219. );
  220. statement.setReadBigInts(true);
  221. return {
  222. rows: statement.all() as unknown as ChromeCookieRow[],
  223. schemaVersion: Number(versionRow?.value ?? 0),
  224. };
  225. } finally {
  226. database.close();
  227. }
  228. }
  229. async function resolveChromeCookieDatabasePath(profilePath: string): Promise<string | null> {
  230. for (const candidate of [join(profilePath, "Network", "Cookies"), join(profilePath, "Cookies")]) {
  231. if (await pathExists(candidate)) return candidate;
  232. }
  233. return null;
  234. }
  235. function hasEncryptedCookiePrefix(rows: ChromeCookieRow[], prefix: "v11" | "v20"): boolean {
  236. return rows.some(
  237. (row) => Buffer.from(row.encrypted_value).subarray(0, 3).toString("ascii") === prefix,
  238. );
  239. }
  240. async function collectCookieDetails(options: {
  241. allowElevatedChromeDecryption?: boolean;
  242. chromeCookieHelper: ChromeCookieHelper;
  243. chromeExecutablePath?: string;
  244. chromePasswordStore?: LinuxChromePasswordStore;
  245. cookieDatabasePath: string;
  246. cookieDatabaseRelativePath: string;
  247. importedAt: number;
  248. issues: Set<ChromeBrowserDataImportError>;
  249. logger: BrowserDataLogger;
  250. macChromeSafeStorageSecretReader?: MacChromeSafeStorageSecretReader;
  251. platform: NodeJS.Platform;
  252. profilePath: string;
  253. rows: ChromeCookieRow[];
  254. schemaVersion: number;
  255. windowsChromeAppBoundKeyReader: WindowsChromeAppBoundKeyReader;
  256. }): Promise<{ details: Electron.CookiesSetDetails[]; skipped: number }> {
  257. if (options.platform === "linux" && hasEncryptedCookiePrefix(options.rows, "v11")) {
  258. if (options.chromeExecutablePath) {
  259. try {
  260. const helperCookies = await options.chromeCookieHelper({
  261. cookieDatabasePath: options.cookieDatabasePath,
  262. cookieDatabaseRelativePath: options.cookieDatabaseRelativePath,
  263. executablePath: options.chromeExecutablePath,
  264. logger: options.logger,
  265. ...(options.platform === "linux" && options.chromePasswordStore
  266. ? { passwordStore: options.chromePasswordStore }
  267. : {}),
  268. profilePath: options.profilePath,
  269. });
  270. if (helperCookies.length > 0 || options.rows.length === 0) {
  271. options.logger.info("[browser-data] Chrome helper Cookie 快照读取完成", {
  272. returnedCount: helperCookies.length,
  273. reason: "linux-keyring-v11",
  274. });
  275. return {
  276. details: helperCookies.map((cookie) =>
  277. toCookieDetailsFromHelper(cookie, options.importedAt),
  278. ),
  279. skipped: Math.max(0, options.rows.length - helperCookies.length),
  280. };
  281. }
  282. } catch (error) {
  283. options.logger.warn("[browser-data] Chrome Cookie helper 不可用", {
  284. reason: "linux-keyring-v11",
  285. ...toSafeBrowserDataError(error),
  286. });
  287. }
  288. } else {
  289. options.issues.add("chrome_executable_not_found");
  290. }
  291. // Linux v11 绑定系统密钥环;同品牌 Chrome helper 不可用时,只能继续尝试
  292. // 当前进程可安全解密的旧格式,不能绕过系统密钥保护。
  293. options.issues.add("chrome_cookie_protection_unsupported");
  294. }
  295. let appBoundDecryptor: CookieDecryptorResource | null = null;
  296. const containsAppBoundCookie =
  297. options.platform === "win32" && hasEncryptedCookiePrefix(options.rows, "v20");
  298. if (containsAppBoundCookie) {
  299. if (!options.allowElevatedChromeDecryption) {
  300. options.issues.add("chrome_cookie_elevation_required");
  301. } else if (options.chromeExecutablePath) {
  302. try {
  303. const key = await options.windowsChromeAppBoundKeyReader({
  304. chromeExecutablePath: options.chromeExecutablePath,
  305. logger: options.logger,
  306. userDataDir: dirname(options.profilePath),
  307. });
  308. appBoundDecryptor = createWindowsGcmDecryptor(key, new Set(["v20"]));
  309. options.logger.info("[browser-data] Chrome App-Bound 解密材料已就绪");
  310. } catch (error) {
  311. const issue =
  312. error instanceof WindowsChromeAppBoundImportError
  313. ? error.code
  314. : "chrome_cookie_app_bound_decryption_failed";
  315. options.issues.add(issue);
  316. options.logger.warn(
  317. "[browser-data] Chrome App-Bound Cookie 原生解密失败",
  318. toSafeBrowserDataError(error),
  319. );
  320. }
  321. } else {
  322. options.issues.add("chrome_executable_not_found");
  323. }
  324. if (!appBoundDecryptor) {
  325. // 同一 Chrome 数据库可能同时包含明文、旧版和 v20 Cookie。
  326. // App-Bound 授权失败时 Cookie 阶段必须保持原子性,不能悄悄写入同批的普通 Cookie。
  327. return { details: [], skipped: options.rows.length };
  328. }
  329. }
  330. let legacyDecryptor: CookieDecryptorResource | null = null;
  331. const needsLegacyDecryptor = options.rows.some((row) => {
  332. if (row.value || row.encrypted_value.length === 0) return false;
  333. return Buffer.from(row.encrypted_value).subarray(0, 3).toString("ascii") !== "v20";
  334. });
  335. if (needsLegacyDecryptor) {
  336. try {
  337. legacyDecryptor = await createCookieDecryptor(
  338. options.platform,
  339. options.profilePath,
  340. options.macChromeSafeStorageSecretReader,
  341. );
  342. } catch (error) {
  343. if (error instanceof ChromeCookieAccessDeniedError) throw error;
  344. options.issues.add("chrome_cookie_protection_unsupported");
  345. options.logger.warn("[browser-data] Chrome Cookie 系统解密材料不可用");
  346. }
  347. }
  348. const details: Electron.CookiesSetDetails[] = [];
  349. let skipped = 0;
  350. let protectedCookieSkipped = false;
  351. try {
  352. for (const row of options.rows) {
  353. let value = row.value;
  354. if (!value && row.encrypted_value.length > 0) {
  355. const prefix = Buffer.from(row.encrypted_value).subarray(0, 3).toString("ascii");
  356. const decryptor = prefix === "v20" ? appBoundDecryptor : legacyDecryptor;
  357. if (!decryptor) {
  358. skipped += 1;
  359. protectedCookieSkipped = true;
  360. continue;
  361. }
  362. try {
  363. value = decryptor.decrypt(row.encrypted_value, row.host_key, options.schemaVersion);
  364. } catch {
  365. skipped += 1;
  366. protectedCookieSkipped = true;
  367. continue;
  368. }
  369. }
  370. if (!value) {
  371. skipped += 1;
  372. continue;
  373. }
  374. details.push(toCookieDetails(row, value, options.importedAt));
  375. }
  376. } finally {
  377. appBoundDecryptor?.dispose();
  378. legacyDecryptor?.dispose();
  379. }
  380. if (protectedCookieSkipped && options.issues.size === 0) {
  381. options.issues.add("chrome_cookie_protection_unsupported");
  382. }
  383. return { details, skipped };
  384. }
  385. export async function importChromeCookies(options: {
  386. allowElevatedChromeDecryption?: boolean;
  387. chromeCookieHelper?: ChromeCookieHelper;
  388. databaseBackup?: ChromeCookieDatabaseBackup;
  389. chromeExecutablePath?: string;
  390. chromePasswordStore?: LinuxChromePasswordStore;
  391. logger: BrowserDataLogger;
  392. macChromeSafeStorageSecretReader?: MacChromeSafeStorageSecretReader;
  393. platform: NodeJS.Platform;
  394. profilePath: string;
  395. targetSession: CookieTargetSession;
  396. windowsChromeAppBoundKeyReader?: WindowsChromeAppBoundKeyReader;
  397. }): Promise<ChromeCookieImportResult> {
  398. const cookieDatabasePath = await resolveChromeCookieDatabasePath(options.profilePath);
  399. if (!cookieDatabasePath) {
  400. return {
  401. databaseFound: false,
  402. issues: [],
  403. rowCount: 0,
  404. stats: { imported: 0, skipped: 0, failed: 0 },
  405. };
  406. }
  407. const cookieDatabaseRelativePath = relative(options.profilePath, cookieDatabasePath);
  408. return withDatabaseSnapshot(
  409. cookieDatabasePath,
  410. options.logger,
  411. options.databaseBackup ?? backup,
  412. async (snapshotPath) => {
  413. const { rows, schemaVersion } = await readChromeCookies(snapshotPath);
  414. options.logger.info("[browser-data] Chrome Cookie 快照读取完成", {
  415. sourceCount: rows.length,
  416. });
  417. const issues = new Set<ChromeBrowserDataImportError>();
  418. const collected = await collectCookieDetails({
  419. allowElevatedChromeDecryption: options.allowElevatedChromeDecryption,
  420. chromeCookieHelper: options.chromeCookieHelper ?? readChromeCookiesWithHelper,
  421. chromeExecutablePath: options.chromeExecutablePath,
  422. chromePasswordStore: options.chromePasswordStore,
  423. cookieDatabasePath: snapshotPath,
  424. cookieDatabaseRelativePath,
  425. importedAt: Math.floor(Date.now() / 1000),
  426. issues,
  427. logger: options.logger,
  428. macChromeSafeStorageSecretReader: options.macChromeSafeStorageSecretReader,
  429. platform: options.platform,
  430. profilePath: options.profilePath,
  431. rows,
  432. schemaVersion,
  433. windowsChromeAppBoundKeyReader:
  434. options.windowsChromeAppBoundKeyReader ?? readWindowsChromeAppBoundKey,
  435. });
  436. const stats = { imported: 0, skipped: collected.skipped, failed: 0 };
  437. for (let offset = 0; offset < collected.details.length; offset += COOKIE_IMPORT_CONCURRENCY) {
  438. const batch = collected.details.slice(offset, offset + COOKIE_IMPORT_CONCURRENCY);
  439. const statuses = await Promise.allSettled(
  440. batch.map((details) => options.targetSession.cookies.set(details)),
  441. );
  442. for (const status of statuses) {
  443. if (status.status === "fulfilled") stats.imported += 1;
  444. else stats.failed += 1;
  445. }
  446. }
  447. await options.targetSession.cookies.flushStore();
  448. options.logger.info("[browser-data] Chrome Cookie 写入完成", {
  449. importedCount: stats.imported,
  450. skippedCount: stats.skipped,
  451. failedCount: stats.failed,
  452. });
  453. return { databaseFound: true, issues: [...issues], rowCount: rows.length, stats };
  454. },
  455. );
  456. }