@asterxsk/kiln 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +155 -155
  2. package/agent/AGENTS.md +67 -67
  3. package/agent/README.md +5 -5
  4. package/agent/extensions/ask-user/index.ts +418 -418
  5. package/agent/extensions/ask-user/install.ps1 +27 -27
  6. package/agent/extensions/ask-user/install.sh +24 -24
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/install.ps1 +27 -27
  14. package/agent/extensions/background-terminals/install.sh +24 -24
  15. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  16. package/agent/extensions/background-terminals/output.test.ts +109 -109
  17. package/agent/extensions/background-terminals/package-lock.json +769 -769
  18. package/agent/extensions/background-terminals/package.json +17 -17
  19. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  20. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  21. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  22. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  23. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  24. package/agent/extensions/background-terminals/src/output.ts +84 -84
  25. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  26. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  27. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  28. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  29. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  30. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  31. package/agent/extensions/destructive/README.md +31 -31
  32. package/agent/extensions/destructive/index.ts +88 -88
  33. package/agent/extensions/destructive/install.ps1 +27 -27
  34. package/agent/extensions/destructive/install.sh +24 -24
  35. package/agent/extensions/file-search/index.spec.ts +443 -443
  36. package/agent/extensions/file-search/index.ts +459 -459
  37. package/agent/extensions/file-search/install.ps1 +27 -27
  38. package/agent/extensions/file-search/install.sh +24 -24
  39. package/agent/extensions/file-search/package-lock.json +2253 -2253
  40. package/agent/extensions/file-search/package.json +23 -23
  41. package/agent/extensions/file-search/src/args.ts +122 -122
  42. package/agent/extensions/file-search/src/binaries.ts +422 -422
  43. package/agent/extensions/file-search/src/output.ts +126 -126
  44. package/agent/extensions/file-search/src/process.ts +146 -146
  45. package/agent/extensions/file-search/src/prompt.ts +52 -52
  46. package/agent/extensions/file-search/tsconfig.json +7 -7
  47. package/agent/extensions/goal/README.md +50 -50
  48. package/agent/extensions/goal/index.ts +155 -155
  49. package/agent/extensions/goal/install.ps1 +27 -27
  50. package/agent/extensions/goal/install.sh +24 -24
  51. package/agent/extensions/kiln-update/README.md +38 -25
  52. package/agent/extensions/kiln-update/index.ts +177 -99
  53. package/agent/extensions/modelconf/PLAN.md +915 -915
  54. package/agent/extensions/modelconf/README.md +66 -66
  55. package/agent/extensions/modelconf/index.ts +296 -296
  56. package/agent/extensions/modelconf/install.ps1 +27 -27
  57. package/agent/extensions/modelconf/install.sh +24 -24
  58. package/agent/extensions/modelconf/package-lock.json +1809 -1809
  59. package/agent/extensions/modelconf/package.json +13 -13
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
  61. package/agent/extensions/modelconf/src/glob.ts +13 -13
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -164
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  66. package/agent/extensions/modelconf/tsconfig.json +15 -15
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  68. package/agent/extensions/pi-web-access/LICENSE +21 -21
  69. package/agent/extensions/pi-web-access/README.md +470 -470
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  71. package/agent/extensions/pi-web-access/activity.ts +101 -101
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  73. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  74. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  75. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  76. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  77. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  78. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  79. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  80. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  81. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  82. package/agent/extensions/pi-web-access/exa.ts +526 -526
  83. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  84. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  85. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  86. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  87. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  88. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  89. package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
  90. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  91. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  92. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  93. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  94. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  95. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  96. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  97. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  98. package/agent/extensions/pi-web-access/package.json +64 -64
  99. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  100. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  101. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  102. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  103. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  104. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  105. package/agent/extensions/pi-web-access/search-types.ts +20 -20
  106. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  107. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  108. package/agent/extensions/pi-web-access/storage.ts +521 -521
  109. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  110. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  111. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  112. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  113. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  114. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  115. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  116. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  117. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  118. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  119. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  120. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  121. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  122. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  123. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  124. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  125. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  126. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  127. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  128. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  129. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  130. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  131. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  132. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  133. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  134. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  135. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  136. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  137. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  138. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  139. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  140. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  141. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  142. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  143. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  144. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  145. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  146. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  147. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  148. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  149. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  150. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
  151. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  152. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
  153. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  154. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  155. package/agent/extensions/pi-web-access/utils.ts +451 -451
  156. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  157. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  158. package/agent/extensions/shared/activity-status.ts +31 -31
  159. package/agent/extensions/shared/child-session.test.ts +270 -270
  160. package/agent/extensions/shared/child-session.ts +148 -148
  161. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  162. package/agent/extensions/shared/context-utilization.ts +47 -47
  163. package/agent/extensions/shared/dashboard-state.ts +99 -99
  164. package/agent/extensions/shared/install.ps1 +27 -27
  165. package/agent/extensions/shared/install.sh +24 -24
  166. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  167. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  168. package/agent/extensions/skillsconf/README.md +74 -74
  169. package/agent/extensions/skillsconf/index.ts +92 -92
  170. package/agent/extensions/skillsconf/install.ps1 +27 -27
  171. package/agent/extensions/skillsconf/install.sh +24 -24
  172. package/agent/extensions/skillsconf/package-lock.json +1809 -1809
  173. package/agent/extensions/skillsconf/package.json +18 -18
  174. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
  175. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
  176. package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
  177. package/agent/extensions/skillsconf/src/filter.ts +74 -74
  178. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
  179. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
  180. package/agent/extensions/skillsconf/src/persistence.ts +169 -169
  181. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
  182. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
  183. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
  184. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
  185. package/agent/extensions/skillsconf/tsconfig.json +15 -15
  186. package/agent/extensions/statusline/index.ts +273 -282
  187. package/agent/extensions/statusline/install.ps1 +27 -27
  188. package/agent/extensions/statusline/install.sh +24 -24
  189. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  190. package/agent/extensions/subagents/claude.test.ts +119 -119
  191. package/agent/extensions/subagents/codex.test.ts +102 -102
  192. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  193. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  194. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  195. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  196. package/agent/extensions/subagents/index.ts +779 -779
  197. package/agent/extensions/subagents/install.ps1 +27 -27
  198. package/agent/extensions/subagents/install.sh +24 -24
  199. package/agent/extensions/subagents/manager.test.ts +276 -276
  200. package/agent/extensions/subagents/package-lock.json +2244 -2244
  201. package/agent/extensions/subagents/package.json +19 -19
  202. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  203. package/agent/extensions/subagents/src/backend.ts +73 -73
  204. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  205. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  206. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  207. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  208. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  209. package/agent/extensions/subagents/src/domain.ts +253 -253
  210. package/agent/extensions/subagents/src/format.ts +74 -74
  211. package/agent/extensions/subagents/src/manager.ts +736 -736
  212. package/agent/extensions/subagents/src/prompt.ts +92 -92
  213. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  214. package/agent/extensions/subagents/src/runtime.ts +53 -53
  215. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  216. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  217. package/agent/extensions/subagents/takeover.test.ts +29 -29
  218. package/agent/extensions/subagents/tsconfig.json +7 -7
  219. package/agent/extensions/todo/AGENTS.md +38 -38
  220. package/agent/extensions/todo/LICENSE +21 -21
  221. package/agent/extensions/todo/config.ts +55 -55
  222. package/agent/extensions/todo/index.ts +151 -151
  223. package/agent/extensions/todo/install.ps1 +27 -27
  224. package/agent/extensions/todo/install.sh +24 -24
  225. package/agent/extensions/todo/locales/de.json +17 -17
  226. package/agent/extensions/todo/locales/en.json +15 -15
  227. package/agent/extensions/todo/locales/es.json +17 -17
  228. package/agent/extensions/todo/locales/fr.json +17 -17
  229. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  230. package/agent/extensions/todo/locales/pt.json +17 -17
  231. package/agent/extensions/todo/locales/ru.json +17 -17
  232. package/agent/extensions/todo/locales/uk.json +17 -17
  233. package/agent/extensions/todo/locales/zh.json +17 -17
  234. package/agent/extensions/todo/package-lock.json +3358 -3358
  235. package/agent/extensions/todo/package.json +67 -67
  236. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  237. package/agent/extensions/todo/state/invariants.ts +20 -20
  238. package/agent/extensions/todo/state/replay.ts +38 -38
  239. package/agent/extensions/todo/state/selectors.ts +107 -107
  240. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  241. package/agent/extensions/todo/state/state.ts +18 -18
  242. package/agent/extensions/todo/state/store.ts +82 -82
  243. package/agent/extensions/todo/state/task-graph.ts +57 -57
  244. package/agent/extensions/todo/todo-overlay.ts +200 -200
  245. package/agent/extensions/todo/todo.ts +155 -155
  246. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  247. package/agent/extensions/todo/tool/types.ts +206 -206
  248. package/agent/extensions/todo/view/format.ts +177 -177
  249. package/agent/extensions/trim-context/README.md +54 -54
  250. package/agent/extensions/trim-context/index.ts +487 -487
  251. package/agent/extensions/trim-context/install.ps1 +27 -27
  252. package/agent/extensions/trim-context/install.sh +24 -24
  253. package/agent/keybindings.json +7 -7
  254. package/agent/version.txt +1 -1
  255. package/bin/kiln.js +20 -13
  256. package/package.json +1 -1
  257. package/agent/extensions/taste/index.ts +0 -443
  258. package/agent/extensions/taste/install.ps1 +0 -27
  259. package/agent/extensions/taste/install.sh +0 -24
@@ -1,669 +1,669 @@
1
- import { execFile } from "node:child_process";
2
- import { pbkdf2Sync, createDecipheriv } from "node:crypto";
3
- import { copyFileSync, existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
4
- import { tmpdir, homedir } from "node:os";
5
- import { isAbsolute, join, sep } from "node:path";
6
- import { isBrowserCookieAccessAllowed, type BrowserCookiePreset } from "./gemini-web-config.ts";
7
-
8
- export type CookieMap = Record<string, string>;
9
-
10
- interface BrowserConfig {
11
- id: BrowserCookiePreset;
12
- name: string;
13
- baseDir: string;
14
- usesLocalAppData?: boolean;
15
- keychainService?: string;
16
- keychainAccount?: string;
17
- secretToolApp?: string;
18
- }
19
-
20
- type SqliteRow = Record<string, unknown>;
21
- type SqliteFailure = "unavailable" | "query";
22
-
23
- export type BrowserCookieAttemptStatus =
24
- | "missing-database"
25
- | "missing-required-cookies"
26
- | "password-read-failed"
27
- | "decryption-failed"
28
- | "sqlite-unavailable"
29
- | "sqlite-query-failed"
30
- | "unsafe-profile"
31
- | "no-host-cookies";
32
-
33
- export interface BrowserCookieAttemptDiagnostic {
34
- browser: string;
35
- profile: string;
36
- status: BrowserCookieAttemptStatus;
37
- }
38
-
39
- export interface BrowserCookieDiagnosticDetails {
40
- message: string;
41
- attempts: BrowserCookieAttemptDiagnostic[];
42
- }
43
-
44
- interface BrowserCookieEntry {
45
- name: string;
46
- value: string;
47
- path: string;
48
- }
49
-
50
- const GOOGLE_ORIGINS = [
51
- "https://gemini.google.com",
52
- "https://accounts.google.com",
53
- "https://www.google.com",
54
- ];
55
-
56
- const ALL_COOKIE_NAMES = new Set([
57
- "__Secure-1PSID", "__Secure-1PSIDTS", "__Secure-1PSIDCC", "__Secure-1PAPISID", "NID", "AEC", "SOCS",
58
- "__Secure-BUCKET", "__Secure-ENID", "SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-3PSID",
59
- "__Secure-3PSIDTS", "__Secure-3PAPISID", "SIDCC",
60
- ]);
61
-
62
- const MACOS_BROWSER_CONFIGS: BrowserConfig[] = [
63
- { id: "helium", name: "Helium", baseDir: "Library/Application Support/net.imput.helium", keychainService: "Helium Storage Key", keychainAccount: "Helium" },
64
- { id: "chrome", name: "Chrome", baseDir: "Library/Application Support/Google/Chrome", keychainService: "Chrome Safe Storage", keychainAccount: "Chrome" },
65
- { id: "brave", name: "Brave", baseDir: "Library/Application Support/BraveSoftware/Brave-Browser", keychainService: "Brave Safe Storage", keychainAccount: "Brave" },
66
- { id: "arc", name: "Arc", baseDir: "Library/Application Support/Arc/User Data", keychainService: "Arc Safe Storage", keychainAccount: "Arc" },
67
- ];
68
-
69
- const LINUX_BROWSER_CONFIGS: BrowserConfig[] = [
70
- { id: "chromium", name: "Chromium", baseDir: ".config/chromium", secretToolApp: "chromium" },
71
- { id: "chrome", name: "Chrome", baseDir: ".config/google-chrome", secretToolApp: "chrome" },
72
- ];
73
-
74
- const WINDOWS_BROWSER_CONFIGS: BrowserConfig[] = [
75
- { id: "chrome", name: "Chrome", baseDir: "Google/Chrome/User Data", usesLocalAppData: true },
76
- { id: "edge", name: "Edge", baseDir: "Microsoft/Edge/User Data", usesLocalAppData: true },
77
- ];
78
-
79
- const browserPasswordCache = new Map<string, Promise<string | null>>();
80
- let lastCookieDiagnostic: string | null = null;
81
- let lastCookieDiagnosticDetails: BrowserCookieDiagnosticDetails | null = null;
82
- let sqliteModule: typeof import("node:sqlite") | null = null;
83
- let sqliteImportAttempted = false;
84
-
85
- export function getLastGoogleCookieDiagnostic(): string | null {
86
- return lastCookieDiagnostic;
87
- }
88
-
89
- export function getLastBrowserCookieDiagnostic(): string | null {
90
- return lastCookieDiagnostic;
91
- }
92
-
93
- export function getLastGoogleCookieDiagnosticDetails(): BrowserCookieDiagnosticDetails | null {
94
- return lastCookieDiagnosticDetails;
95
- }
96
-
97
- export async function getGoogleCookies(
98
- options?: { browser?: BrowserCookiePreset; profile?: string; requiredCookies?: string[] },
99
- ): Promise<{ cookies: CookieMap; warnings: string[] } | null> {
100
- return getBrowserCookiesForHosts({
101
- hosts: GOOGLE_ORIGINS.map((origin) => new URL(origin).hostname),
102
- browser: options?.browser,
103
- profile: options?.profile,
104
- requiredCookies: options?.requiredCookies,
105
- cookieNames: ALL_COOKIE_NAMES,
106
- requiredLabel: "Gemini",
107
- });
108
- }
109
-
110
- export async function getBrowserCookiesForHosts(
111
- options: { hosts: string[]; browser?: BrowserCookiePreset; profile?: string; requiredCookies?: string[]; cookieNames?: Iterable<string>; requiredLabel?: string; requestUrl?: URL },
112
- ): Promise<{ cookies: CookieMap; warnings: string[]; cookieHeader?: string } | null> {
113
- lastCookieDiagnostic = null;
114
- lastCookieDiagnosticDetails = null;
115
- if (!isBrowserCookieAccessAllowed()) {
116
- setCookieDiagnostic("Browser cookie access is disabled; enable allowBrowserCookies to use browser cookies.");
117
- return null;
118
- }
119
-
120
- const currentPlatform = process.platform;
121
- const platformConfigs = currentPlatform === "darwin" ? MACOS_BROWSER_CONFIGS : currentPlatform === "linux" ? LINUX_BROWSER_CONFIGS : currentPlatform === "win32" ? WINDOWS_BROWSER_CONFIGS : [];
122
- const configs = options.browser ? platformConfigs.filter((config) => config.id === options.browser) : platformConfigs;
123
- if (options.browser && configs.length === 0) {
124
- setCookieDiagnostic(`Browser preset '${options.browser}' is not supported on this platform.`);
125
- return null;
126
- }
127
- if (configs.length === 0) {
128
- setCookieDiagnostic("Chromium cookie extraction is unsupported on this platform.");
129
- return null;
130
- }
131
-
132
- const warningSet = new Set<string>();
133
- const rawProfile = typeof options.profile === "string" ? options.profile.trim() : "";
134
- const requestedProfile = normalizeProfileName(options.profile);
135
- if (rawProfile && !requestedProfile) {
136
- setCookieDiagnostic("Configured Chromium profile must be a profile directory name, not a path.");
137
- return null;
138
- }
139
- const requiredCookies = normalizeCookieNames(options.requiredCookies);
140
- const cookieNames = normalizeCookieNames(options.cookieNames ? [...options.cookieNames] : undefined);
141
- const hosts = normalizeHosts(options.hosts);
142
- if (hosts.length === 0) {
143
- setCookieDiagnostic("No valid cookie hosts were requested.");
144
- return null;
145
- }
146
- const attempts: BrowserCookieAttemptDiagnostic[] = [];
147
- const home = currentPlatform === "win32" ? process.env.USERPROFILE || homedir() : homedir();
148
- let sawCookieDatabase = false;
149
- let sawRequiredCookies = false;
150
- let sawAnyHostCookie = false;
151
- let sawBackendFailure: SqliteFailure | undefined;
152
- let sawUnsafeProfilePath = false;
153
- let sawWindowsAppBoundCookie = false;
154
- let sawDecryptionFailure = false;
155
-
156
- for (const config of configs) {
157
- const profiles = requestedProfile ? [requestedProfile] : listBrowserProfiles(home, config);
158
- for (const profile of profiles) {
159
- const profilePath = resolveProfilePath(home, config, profile);
160
- if (profilePath === "outside-root") {
161
- sawUnsafeProfilePath = true;
162
- recordCookieAttempt(attempts, config, profile, "unsafe-profile");
163
- continue;
164
- }
165
- if (!profilePath) {
166
- recordCookieAttempt(attempts, config, profile, "missing-database");
167
- continue;
168
- }
169
- const cookiesPath = cookieDatabasePath(profilePath, config);
170
- if (!cookiesPath) {
171
- recordCookieAttempt(attempts, config, profile, "missing-database");
172
- continue;
173
- }
174
- sawCookieDatabase = true;
175
-
176
- const tempDir = mkdtempSync(join(tmpdir(), "pi-chrome-cookies-"));
177
- try {
178
- const tempDb = join(tempDir, "Cookies");
179
- copyFileSync(cookiesPath, tempDb);
180
- copySidecar(cookiesPath, tempDb, "-wal");
181
- copySidecar(cookiesPath, tempDb, "-shm");
182
-
183
- if (requiredCookies?.length) {
184
- const preflight = await hasCookieNames(tempDb, hosts, requiredCookies);
185
- if (preflight.failure) {
186
- sawBackendFailure = preflight.failure;
187
- recordCookieAttempt(attempts, config, profile, preflight.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
188
- continue;
189
- }
190
- if (!preflight.present) {
191
- recordCookieAttempt(attempts, config, profile, "missing-required-cookies");
192
- continue;
193
- }
194
- sawRequiredCookies = true;
195
- }
196
-
197
- const key = currentPlatform === "win32"
198
- ? await readWindowsEncryptionKey(config, home)
199
- : await readBrowserPassword(config, currentPlatform).then((password) => password ? pbkdf2Sync(password, "saltysalt", currentPlatform === "darwin" ? 1003 : 1, 16, "sha1") : null);
200
- if (!key) {
201
- warningSet.add(currentPlatform === "win32"
202
- ? `Could not read ${config.name} Windows cookie encryption key`
203
- : `Could not read ${config.name} cookie encryption password`);
204
- recordCookieAttempt(attempts, config, profile, "password-read-failed");
205
- continue;
206
- }
207
- const metaVersion = await readMetaVersion(tempDb);
208
- if (metaVersion.failure) {
209
- sawBackendFailure = metaVersion.failure;
210
- recordCookieAttempt(attempts, config, profile, metaVersion.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
211
- }
212
- if (metaVersion.value === null) continue;
213
- const rowsResult = await queryCookieRows(tempDb, hosts, cookieNames ?? null, Boolean(options.requestUrl));
214
- if (rowsResult.status === "failure") {
215
- sawBackendFailure = rowsResult.failure;
216
- recordCookieAttempt(attempts, config, profile, rowsResult.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
217
- continue;
218
- }
219
-
220
- const entries: BrowserCookieEntry[] = [];
221
- const cookies: CookieMap = {};
222
- const requiredDecryptFailures = new Set<string>();
223
- for (const row of rowsResult.rows) {
224
- const name = typeof row.name === "string" ? row.name : "";
225
- if (!name) continue;
226
- let value = typeof row.value === "string" && row.value.length > 0 ? row.value : null;
227
- if (!value && typeof row.encrypted_value_hex === "string" && /^[0-9a-f]*$/i.test(row.encrypted_value_hex)) {
228
- const encrypted = Buffer.from(row.encrypted_value_hex, "hex");
229
- if (currentPlatform === "win32" && encrypted.subarray(0, 3).toString("utf8") === "v20") sawWindowsAppBoundCookie = true;
230
- value = currentPlatform === "win32"
231
- ? decryptWindowsCookieValue(encrypted, key, metaVersion.value >= 24)
232
- : decryptCookieValue(encrypted, key, metaVersion.value >= 24);
233
- if (!value && requiredCookies?.includes(name)) requiredDecryptFailures.add(name);
234
- }
235
- if (!value) continue;
236
- const path = typeof row.path === "string" && row.path.startsWith("/") ? row.path : "/";
237
- if (options.requestUrl && !pathMatches(options.requestUrl.pathname || "/", path)) continue;
238
- entries.push({ name, value, path });
239
- if (!cookies[name]) cookies[name] = value;
240
- }
241
-
242
- if (entries.length > 0) sawAnyHostCookie = true;
243
- if (requiredCookies?.length && !requiredCookies.every((name) => Boolean(cookies[name]))) {
244
- if (requiredCookies.some((name) => !cookies[name] && requiredDecryptFailures.has(name))) {
245
- sawDecryptionFailure = true;
246
- recordCookieAttempt(attempts, config, profile, "decryption-failed");
247
- } else {
248
- recordCookieAttempt(attempts, config, profile, "missing-required-cookies");
249
- }
250
- continue;
251
- }
252
- if (entries.length === 0) {
253
- recordCookieAttempt(attempts, config, profile, requiredDecryptFailures.size > 0 ? "decryption-failed" : "no-host-cookies");
254
- if (requiredDecryptFailures.size > 0) sawDecryptionFailure = true;
255
- continue;
256
- }
257
- return {
258
- cookies,
259
- warnings: [...warningSet],
260
- ...(options.requestUrl ? { cookieHeader: buildCookieHeader(entries) } : {}),
261
- };
262
- } finally {
263
- rmSync(tempDir, { recursive: true, force: true });
264
- }
265
- }
266
- }
267
-
268
- if (sawBackendFailure === "unavailable") {
269
- setCookieDiagnostic("SQLite backend unavailable: install sqlite3 or use a runtime with SQLite support.", attempts);
270
- } else if (sawBackendFailure === "query") {
271
- setCookieDiagnostic("SQLite query failed while reading the copied Chromium cookie database.", attempts);
272
- } else if (sawUnsafeProfilePath) {
273
- setCookieDiagnostic("Configured Chromium profile must resolve inside the browser profile root.", attempts);
274
- } else if (!sawCookieDatabase) {
275
- setCookieDiagnostic(requestedProfile
276
- ? `Chromium profile '${requestedProfile}' does not contain a cookie database.`
277
- : "No detected Chromium profile contains a cookie database.", attempts);
278
- } else if (requiredCookies?.length && !sawRequiredCookies) {
279
- setCookieDiagnostic(`No detected Chromium profile contains the required ${options.requiredLabel ?? "browser"} cookies.`, attempts);
280
- } else if (sawWindowsAppBoundCookie) {
281
- setCookieDiagnostic("Windows Chromium v20 app-bound cookies are not supported.", attempts);
282
- } else if (warningSet.size > 0) {
283
- setCookieDiagnostic([...warningSet][0], attempts);
284
- } else if (sawDecryptionFailure) {
285
- setCookieDiagnostic(`Required ${options.requiredLabel ?? "browser"} cookies could not be decrypted.`, attempts);
286
- } else if (!sawAnyHostCookie) {
287
- setCookieDiagnostic(options.requestUrl
288
- ? "No detected Chromium profile contains cookies for the requested URL."
289
- : "No detected Chromium profile contains cookies for the requested host.", attempts);
290
- } else {
291
- setCookieDiagnostic("Required Gemini cookies were not available or could not be decrypted.", attempts);
292
- }
293
- return null;
294
- }
295
-
296
- function setCookieDiagnostic(message: string, attempts: BrowserCookieAttemptDiagnostic[] = []): void {
297
- lastCookieDiagnostic = message;
298
- lastCookieDiagnosticDetails = { message, attempts };
299
- }
300
-
301
- function recordCookieAttempt(attempts: BrowserCookieAttemptDiagnostic[], config: BrowserConfig, profile: string, status: BrowserCookieAttemptStatus): void {
302
- attempts.push({ browser: config.name, profile, status });
303
- }
304
-
305
- function normalizeProfileName(value: string | undefined): string | undefined {
306
- if (typeof value !== "string") return undefined;
307
- const normalized = value.trim();
308
- if (!normalized) return undefined;
309
- if (isAbsolute(normalized) || normalized === "." || normalized === ".." || normalized.includes("/") || normalized.includes("\\")) {
310
- return undefined;
311
- }
312
- return normalized;
313
- }
314
-
315
- function resolveProfilePath(home: string, config: BrowserConfig, profile: string): string | "outside-root" | null {
316
- const basePath = browserBasePath(home, config);
317
- const profilePath = join(basePath, profile);
318
- if (!cookieDatabasePath(profilePath, config)) return null;
319
- try {
320
- const baseRealPath = realpathSync(basePath);
321
- const profileRealPath = realpathSync(profilePath);
322
- if (profileRealPath !== baseRealPath && !profileRealPath.startsWith(`${baseRealPath}${sep}`)) return "outside-root";
323
- return profileRealPath;
324
- } catch {
325
- return null;
326
- }
327
- }
328
-
329
- function cookieDatabasePath(profilePath: string, config: BrowserConfig): string | null {
330
- const networkCookies = join(profilePath, "Network", "Cookies");
331
- if (config.usesLocalAppData && existsSync(networkCookies)) return networkCookies;
332
- const legacyCookies = join(profilePath, "Cookies");
333
- return existsSync(legacyCookies) ? legacyCookies : null;
334
- }
335
-
336
- function browserBasePath(home: string, config: BrowserConfig): string {
337
- return config.usesLocalAppData
338
- ? join(process.env.LOCALAPPDATA || join(home, "AppData", "Local"), config.baseDir)
339
- : join(home, config.baseDir);
340
- }
341
-
342
- function normalizeCookieNames(names: string[] | undefined): string[] | undefined {
343
- if (!names?.length) return undefined;
344
- const normalized = names.filter((name): name is string => typeof name === "string").map((name) => name.trim()).filter(Boolean);
345
- return normalized.length > 0 ? [...new Set(normalized)] : undefined;
346
- }
347
-
348
- function normalizeHosts(hosts: string[]): string[] {
349
- return [...new Set(hosts.map(host => host.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "")).filter(Boolean))];
350
- }
351
-
352
- function listBrowserProfiles(home: string, config: BrowserConfig): string[] {
353
- const basePath = browserBasePath(home, config);
354
- if (!existsSync(basePath)) return ["Default"];
355
- const profiles = new Set<string>();
356
- try {
357
- for (const entry of readdirSync(basePath, { withFileTypes: true })) {
358
- if (entry.isDirectory() && cookieDatabasePath(join(basePath, entry.name), config)) profiles.add(entry.name);
359
- }
360
- } catch {
361
- }
362
- if (profiles.size === 0) return ["Default"];
363
- return [...profiles].sort(compareProfileNames);
364
- }
365
-
366
- function compareProfileNames(a: string, b: string): number {
367
- const key = (name: string): [number, number] => {
368
- if (name === "Default") return [0, 0];
369
- const profile = /^Profile\s+(\d+)$/i.exec(name);
370
- if (profile) return [1, Number(profile[1])];
371
- const person = /^Person\s+(\d+)$/i.exec(name);
372
- if (person) return [2, Number(person[1])];
373
- return [3, Number.MAX_SAFE_INTEGER];
374
- };
375
- const [ap, ai] = key(a);
376
- const [bp, bi] = key(b);
377
- return ap - bp || ai - bi || a.localeCompare(b, undefined, { sensitivity: "base", numeric: true });
378
- }
379
-
380
- function decryptCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {
381
- const buf = Buffer.from(encrypted);
382
- if (buf.length < 3 || !/^v\d\d$/.test(buf.subarray(0, 3).toString("utf8"))) return null;
383
- const ciphertext = buf.subarray(3);
384
- if (!ciphertext.length) return "";
385
- try {
386
- const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
387
- decipher.setAutoPadding(false);
388
- const unpadded = removePkcs7Padding(Buffer.concat([decipher.update(ciphertext), decipher.final()]));
389
- const bytes = stripHash && unpadded.length >= 32 ? unpadded.subarray(32) : unpadded;
390
- const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
391
- let i = 0;
392
- while (i < decoded.length && decoded.charCodeAt(i) < 0x20) i++;
393
- return decoded.slice(i);
394
- } catch {
395
- return null;
396
- }
397
- }
398
-
399
- function decryptWindowsCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {
400
- const buf = Buffer.from(encrypted);
401
- if (buf.subarray(0, 3).toString("utf8") !== "v10" || buf.length < 3 + 12 + 16) return null;
402
- try {
403
- const nonce = buf.subarray(3, 15);
404
- const ciphertext = buf.subarray(15, -16);
405
- const decipher = createDecipheriv("aes-256-gcm", key, nonce);
406
- decipher.setAuthTag(buf.subarray(-16));
407
- const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
408
- return new TextDecoder("utf-8", { fatal: true }).decode(stripHash && plaintext.length >= 32 ? plaintext.subarray(32) : plaintext);
409
- } catch {
410
- return null;
411
- }
412
- }
413
-
414
- function removePkcs7Padding(buf: Buffer): Buffer {
415
- if (!buf.length) return buf;
416
- const padding = buf[buf.length - 1];
417
- return !padding || padding > 16 ? buf : buf.subarray(0, buf.length - padding);
418
- }
419
-
420
- function readBrowserPassword(config: BrowserConfig, currentPlatform: typeof process.platform): Promise<string | null> {
421
- const cacheKey = `${currentPlatform}:${config.name}`;
422
- const cached = browserPasswordCache.get(cacheKey);
423
- if (cached) return cached;
424
- const passwordResult = currentPlatform === "darwin"
425
- ? config.keychainAccount && config.keychainService
426
- ? readKeychainPassword(config.keychainAccount, config.keychainService).then(password => ({ password, cacheable: Boolean(password) }))
427
- : Promise.resolve({ password: null, cacheable: false })
428
- : currentPlatform === "linux"
429
- ? readLinuxPassword(config.secretToolApp)
430
- : Promise.resolve({ password: null, cacheable: false });
431
- const passwordPromise = passwordResult.then(({ password, cacheable }) => {
432
- if (!cacheable) browserPasswordCache.delete(cacheKey);
433
- return password;
434
- }, (error) => {
435
- browserPasswordCache.delete(cacheKey);
436
- throw error;
437
- });
438
- browserPasswordCache.set(cacheKey, passwordPromise);
439
- return passwordPromise;
440
- }
441
-
442
- async function readWindowsEncryptionKey(config: BrowserConfig, home: string): Promise<Buffer | null> {
443
- try {
444
- const localState = JSON.parse(readFileSync(join(browserBasePath(home, config), "Local State"), "utf8")) as { os_crypt?: { encrypted_key?: unknown } };
445
- const encodedKey = localState.os_crypt?.encrypted_key;
446
- if (typeof encodedKey !== "string") return null;
447
- const protectedKey = Buffer.from(encodedKey, "base64");
448
- if (protectedKey.subarray(0, 5).toString("utf8") !== "DPAPI") return null;
449
- const decrypted = await unprotectWindowsData(protectedKey.subarray(5));
450
- return decrypted?.length === 32 ? decrypted : null;
451
- } catch {
452
- return null;
453
- }
454
- }
455
-
456
- function unprotectWindowsData(protectedData: Buffer): Promise<Buffer | null> {
457
- return new Promise((resolve) => {
458
- const script = "Add-Type -AssemblyName System.Security;$data=[Convert]::FromBase64String($env:PIWA_PROTECTED);$clear=[System.Security.Cryptography.ProtectedData]::Unprotect($data,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Convert]::ToBase64String($clear))";
459
- const encoded = Buffer.from(script, "utf16le").toString("base64");
460
- execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { timeout: 5000, maxBuffer: 1024 * 1024, env: { ...process.env, PIWA_PROTECTED: protectedData.toString("base64") } }, (err, stdout) => {
461
- if (err) { resolve(null); return; }
462
- try {
463
- resolve(Buffer.from(stdout.trim(), "base64"));
464
- } catch {
465
- resolve(null);
466
- }
467
- });
468
- });
469
- }
470
-
471
- function readKeychainPassword(account: string, service: string): Promise<string | null> {
472
- return new Promise((resolve) => {
473
- execFile("security", ["find-generic-password", "-w", "-a", account, "-s", service], { timeout: 5000 }, (err, stdout) => {
474
- if (err) { resolve(null); return; }
475
- resolve(stdout.trim() || null);
476
- });
477
- });
478
- }
479
-
480
- function readLinuxPassword(secretToolApp: string | undefined): Promise<{ password: string; cacheable: boolean }> {
481
- if (!secretToolApp) return Promise.resolve({ password: "peanuts", cacheable: true });
482
- return new Promise((resolve) => {
483
- execFile("secret-tool", ["lookup", "application", secretToolApp], { timeout: 5000 }, (err, stdout) => {
484
- if (err) { resolve({ password: "peanuts", cacheable: false }); return; }
485
- const password = stdout.trim();
486
- resolve(password ? { password, cacheable: true } : { password: "peanuts", cacheable: false });
487
- });
488
- });
489
- }
490
-
491
- async function importSqlite(): Promise<typeof import("node:sqlite") | null> {
492
- if (process.env.PI_WEB_ACCESS_DISABLE_NODE_SQLITE === "1") return null;
493
- if (sqliteImportAttempted) return sqliteModule;
494
- sqliteImportAttempted = true;
495
- const orig = process.emitWarning.bind(process);
496
- process.emitWarning = ((warning: string | Error, ...args: unknown[]) => {
497
- const msg = typeof warning === "string" ? warning : warning?.message ?? "";
498
- if (msg.includes("SQLite is an experimental feature")) return;
499
- return (orig as Function)(warning, ...args);
500
- }) as typeof process.emitWarning;
501
- try {
502
- sqliteModule = await import("node:sqlite");
503
- } catch {
504
- sqliteModule = null;
505
- } finally {
506
- process.emitWarning = orig;
507
- }
508
- return sqliteModule;
509
- }
510
-
511
- type QueryResult =
512
- | { status: "success"; rows: SqliteRow[] }
513
- | { status: "failure"; failure: SqliteFailure };
514
-
515
- async function runSqliteQuery(dbPath: string, sql: string): Promise<QueryResult> {
516
- const sqlite = await importSqlite();
517
- let queryFailed = false;
518
- if (sqlite) {
519
- try {
520
- const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
521
- try {
522
- return { status: "success", rows: db.prepare(sql).all() as SqliteRow[] };
523
- } finally {
524
- db.close();
525
- }
526
- } catch {
527
- queryFailed = true;
528
- }
529
- }
530
-
531
- const cli = await runSqliteCli(dbPath, sql);
532
- if (cli.status === "success") return cli;
533
- if (cli.failure === "query") queryFailed = true;
534
- const python = await runPythonSqlite(dbPath, sql);
535
- if (python.status === "success") return python;
536
- if (python.failure === "query") queryFailed = true;
537
- return { status: "failure", failure: queryFailed ? "query" : "unavailable" };
538
- }
539
-
540
- function runSqliteCli(dbPath: string, sql: string): Promise<QueryResult> {
541
- return new Promise((resolve) => {
542
- execFile("sqlite3", ["-readonly", "-json", dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
543
- if (err) { resolve({ status: "failure", failure: err.code === "ENOENT" ? "unavailable" : "query" }); return; }
544
- try {
545
- const parsed = JSON.parse(stdout || "[]");
546
- resolve(Array.isArray(parsed) ? { status: "success", rows: parsed as SqliteRow[] } : { status: "failure", failure: "query" });
547
- } catch {
548
- resolve({ status: "failure", failure: "query" });
549
- }
550
- });
551
- });
552
- }
553
-
554
- function runPythonSqlite(dbPath: string, sql: string): Promise<QueryResult> {
555
- const script = "import json,sqlite3,sys\ntry:\n c=sqlite3.connect('file:'+sys.argv[1]+'?mode=ro',uri=True)\n c.row_factory=sqlite3.Row\n print(json.dumps([dict(r) for r in c.execute(sys.argv[2]).fetchall()]))\nexcept Exception:\n sys.exit(1)";
556
- return new Promise((resolve) => {
557
- execFile("python3", ["-c", script, dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
558
- if (err) { resolve({ status: "failure", failure: err.code === "ENOENT" ? "unavailable" : "query" }); return; }
559
- try {
560
- const parsed = JSON.parse(stdout || "[]");
561
- resolve(Array.isArray(parsed) ? { status: "success", rows: parsed as SqliteRow[] } : { status: "failure", failure: "query" });
562
- } catch {
563
- resolve({ status: "failure", failure: "query" });
564
- }
565
- });
566
- });
567
- }
568
-
569
- async function readMetaVersion(dbPath: string): Promise<{ value: number | null; failure?: SqliteFailure }> {
570
- const result = await runSqliteQuery(dbPath, "SELECT value FROM meta WHERE key = 'version'");
571
- if (result.status === "failure") {
572
- return result.failure === "unavailable"
573
- ? { value: null, failure: result.failure }
574
- : { value: 0 };
575
- }
576
- const value = result.rows[0]?.value;
577
- if (typeof value === "number") return { value: Math.floor(value) };
578
- if (typeof value === "string") return { value: parseInt(value, 10) || 0 };
579
- return { value: 0 };
580
- }
581
-
582
- async function hasCookieNames(dbPath: string, hosts: string[], names: string[]): Promise<{ present: boolean; failure?: SqliteFailure }> {
583
- const result = await runSqliteQuery(dbPath, `SELECT DISTINCT name FROM cookies WHERE ${buildCookieWhere(hosts, names)}`);
584
- if (result.status === "failure") return { present: false, failure: result.failure };
585
- const present = new Set(result.rows.map((row) => typeof row.name === "string" ? row.name : ""));
586
- return { present: names.every((name) => present.has(name)) };
587
- }
588
-
589
- async function queryCookieRows(dbPath: string, hosts: string[], names: Iterable<string> | null, filterExpired: boolean): Promise<QueryResult> {
590
- const columns = await readCookieColumns(dbPath);
591
- if (columns.status === "failure") return columns;
592
- const pathExpr = columns.columns.has("path") ? "path" : "'/' AS path";
593
- const expiresExpr = columns.columns.has("expires_utc") ? chromeExpiryMillisExpr() : "0";
594
- const expiryFilter = filterExpired && columns.columns.has("expires_utc") ? ` AND (${expiresExpr} = 0 OR ${expiresExpr} > ${chromeExpiryNowMillis()})` : "";
595
- const partitionFilter = filterExpired ? unpartitionedCookieFilter(columns.columns) : "";
596
- return runSqliteQuery(dbPath, `SELECT name, value, host_key, ${pathExpr}, ${expiresExpr} AS expires_utc, hex(encrypted_value) AS encrypted_value_hex FROM cookies WHERE ${buildCookieWhere(hosts, names ?? undefined)}${expiryFilter}${partitionFilter} ORDER BY length(path) DESC, ${expiresExpr} ASC`);
597
- }
598
-
599
- async function readCookieColumns(dbPath: string): Promise<{ status: "success"; columns: Set<string> } | { status: "failure"; failure: SqliteFailure }> {
600
- const result = await runSqliteQuery(dbPath, "PRAGMA table_info(cookies)");
601
- if (result.status === "failure") return result;
602
- return { status: "success", columns: new Set(result.rows.map(row => typeof row.name === "string" ? row.name : "")) };
603
- }
604
-
605
- function chromeExpiryMillisExpr(): string {
606
- return "CASE WHEN expires_utc = 0 THEN 0 ELSE CAST(expires_utc / 1000 AS INTEGER) + CASE WHEN expires_utc % 1000 = 0 THEN 0 ELSE 1 END END";
607
- }
608
-
609
- function chromeExpiryNowMillis(): number {
610
- return Date.now() + 11644473600000;
611
- }
612
-
613
- function unpartitionedCookieFilter(columns: Set<string>): string {
614
- const clauses: string[] = [];
615
- if (columns.has("top_frame_site_key")) clauses.push("(top_frame_site_key IS NULL OR top_frame_site_key = '')");
616
- if (columns.has("partition_key")) clauses.push("(partition_key IS NULL OR partition_key = '')");
617
- if (columns.has("is_partitioned")) clauses.push("(is_partitioned IS NULL OR is_partitioned = 0)");
618
- return clauses.length > 0 ? ` AND ${clauses.join(" AND ")}` : "";
619
- }
620
-
621
- function buildCookieHeader(entries: BrowserCookieEntry[]): string {
622
- return entries
623
- .sort((a, b) => b.path.length - a.path.length)
624
- .map(({ name, value }) => `${name}=${value}`)
625
- .join("; ");
626
- }
627
-
628
- function pathMatches(requestPath: string, cookiePath: string): boolean {
629
- if (requestPath === cookiePath) return true;
630
- if (!requestPath.startsWith(cookiePath)) return false;
631
- if (cookiePath.endsWith("/")) return true;
632
- return requestPath[cookiePath.length] === "/";
633
- }
634
-
635
- function buildCookieWhere(hosts: string[], cookieNames?: Iterable<string>): string {
636
- const hostClauses: string[] = [];
637
- for (const host of hosts) {
638
- const escapedHost = escapeSqlString(host);
639
- hostClauses.push(`host_key = '${escapedHost}'`);
640
- for (const candidate of domainCookieHosts(host)) {
641
- hostClauses.push(`host_key = '.${escapeSqlString(candidate)}'`);
642
- }
643
- }
644
- let where = `(${[...new Set(hostClauses)].join(" OR ")})`;
645
- const names = cookieNames ? [...cookieNames].filter(Boolean) : [];
646
- if (names.length) where += ` AND name IN (${names.map((name) => `'${escapeSqlString(name)}'`).join(", ")})`;
647
- return where;
648
- }
649
-
650
- function escapeSqlString(value: string): string {
651
- return value.replaceAll("'", "''");
652
- }
653
-
654
- function domainCookieHosts(host: string): string[] {
655
- const parts = host.split(".").filter(Boolean);
656
- if (parts.length <= 1) return [];
657
- const candidates = new Set<string>();
658
- for (let i = 0; i <= parts.length - 2; i++) candidates.add(parts.slice(i).join("."));
659
- return [...candidates];
660
- }
661
-
662
- function copySidecar(srcDb: string, targetDb: string, suffix: string): void {
663
- const sidecar = `${srcDb}${suffix}`;
664
- if (!existsSync(sidecar)) return;
665
- try {
666
- copyFileSync(sidecar, `${targetDb}${suffix}`);
667
- } catch {
668
- }
669
- }
1
+ import { execFile } from "node:child_process";
2
+ import { pbkdf2Sync, createDecipheriv } from "node:crypto";
3
+ import { copyFileSync, existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
4
+ import { tmpdir, homedir } from "node:os";
5
+ import { isAbsolute, join, sep } from "node:path";
6
+ import { isBrowserCookieAccessAllowed, type BrowserCookiePreset } from "./gemini-web-config.ts";
7
+
8
+ export type CookieMap = Record<string, string>;
9
+
10
+ interface BrowserConfig {
11
+ id: BrowserCookiePreset;
12
+ name: string;
13
+ baseDir: string;
14
+ usesLocalAppData?: boolean;
15
+ keychainService?: string;
16
+ keychainAccount?: string;
17
+ secretToolApp?: string;
18
+ }
19
+
20
+ type SqliteRow = Record<string, unknown>;
21
+ type SqliteFailure = "unavailable" | "query";
22
+
23
+ export type BrowserCookieAttemptStatus =
24
+ | "missing-database"
25
+ | "missing-required-cookies"
26
+ | "password-read-failed"
27
+ | "decryption-failed"
28
+ | "sqlite-unavailable"
29
+ | "sqlite-query-failed"
30
+ | "unsafe-profile"
31
+ | "no-host-cookies";
32
+
33
+ export interface BrowserCookieAttemptDiagnostic {
34
+ browser: string;
35
+ profile: string;
36
+ status: BrowserCookieAttemptStatus;
37
+ }
38
+
39
+ export interface BrowserCookieDiagnosticDetails {
40
+ message: string;
41
+ attempts: BrowserCookieAttemptDiagnostic[];
42
+ }
43
+
44
+ interface BrowserCookieEntry {
45
+ name: string;
46
+ value: string;
47
+ path: string;
48
+ }
49
+
50
+ const GOOGLE_ORIGINS = [
51
+ "https://gemini.google.com",
52
+ "https://accounts.google.com",
53
+ "https://www.google.com",
54
+ ];
55
+
56
+ const ALL_COOKIE_NAMES = new Set([
57
+ "__Secure-1PSID", "__Secure-1PSIDTS", "__Secure-1PSIDCC", "__Secure-1PAPISID", "NID", "AEC", "SOCS",
58
+ "__Secure-BUCKET", "__Secure-ENID", "SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-3PSID",
59
+ "__Secure-3PSIDTS", "__Secure-3PAPISID", "SIDCC",
60
+ ]);
61
+
62
+ const MACOS_BROWSER_CONFIGS: BrowserConfig[] = [
63
+ { id: "helium", name: "Helium", baseDir: "Library/Application Support/net.imput.helium", keychainService: "Helium Storage Key", keychainAccount: "Helium" },
64
+ { id: "chrome", name: "Chrome", baseDir: "Library/Application Support/Google/Chrome", keychainService: "Chrome Safe Storage", keychainAccount: "Chrome" },
65
+ { id: "brave", name: "Brave", baseDir: "Library/Application Support/BraveSoftware/Brave-Browser", keychainService: "Brave Safe Storage", keychainAccount: "Brave" },
66
+ { id: "arc", name: "Arc", baseDir: "Library/Application Support/Arc/User Data", keychainService: "Arc Safe Storage", keychainAccount: "Arc" },
67
+ ];
68
+
69
+ const LINUX_BROWSER_CONFIGS: BrowserConfig[] = [
70
+ { id: "chromium", name: "Chromium", baseDir: ".config/chromium", secretToolApp: "chromium" },
71
+ { id: "chrome", name: "Chrome", baseDir: ".config/google-chrome", secretToolApp: "chrome" },
72
+ ];
73
+
74
+ const WINDOWS_BROWSER_CONFIGS: BrowserConfig[] = [
75
+ { id: "chrome", name: "Chrome", baseDir: "Google/Chrome/User Data", usesLocalAppData: true },
76
+ { id: "edge", name: "Edge", baseDir: "Microsoft/Edge/User Data", usesLocalAppData: true },
77
+ ];
78
+
79
+ const browserPasswordCache = new Map<string, Promise<string | null>>();
80
+ let lastCookieDiagnostic: string | null = null;
81
+ let lastCookieDiagnosticDetails: BrowserCookieDiagnosticDetails | null = null;
82
+ let sqliteModule: typeof import("node:sqlite") | null = null;
83
+ let sqliteImportAttempted = false;
84
+
85
+ export function getLastGoogleCookieDiagnostic(): string | null {
86
+ return lastCookieDiagnostic;
87
+ }
88
+
89
+ export function getLastBrowserCookieDiagnostic(): string | null {
90
+ return lastCookieDiagnostic;
91
+ }
92
+
93
+ export function getLastGoogleCookieDiagnosticDetails(): BrowserCookieDiagnosticDetails | null {
94
+ return lastCookieDiagnosticDetails;
95
+ }
96
+
97
+ export async function getGoogleCookies(
98
+ options?: { browser?: BrowserCookiePreset; profile?: string; requiredCookies?: string[] },
99
+ ): Promise<{ cookies: CookieMap; warnings: string[] } | null> {
100
+ return getBrowserCookiesForHosts({
101
+ hosts: GOOGLE_ORIGINS.map((origin) => new URL(origin).hostname),
102
+ browser: options?.browser,
103
+ profile: options?.profile,
104
+ requiredCookies: options?.requiredCookies,
105
+ cookieNames: ALL_COOKIE_NAMES,
106
+ requiredLabel: "Gemini",
107
+ });
108
+ }
109
+
110
+ export async function getBrowserCookiesForHosts(
111
+ options: { hosts: string[]; browser?: BrowserCookiePreset; profile?: string; requiredCookies?: string[]; cookieNames?: Iterable<string>; requiredLabel?: string; requestUrl?: URL },
112
+ ): Promise<{ cookies: CookieMap; warnings: string[]; cookieHeader?: string } | null> {
113
+ lastCookieDiagnostic = null;
114
+ lastCookieDiagnosticDetails = null;
115
+ if (!isBrowserCookieAccessAllowed()) {
116
+ setCookieDiagnostic("Browser cookie access is disabled; enable allowBrowserCookies to use browser cookies.");
117
+ return null;
118
+ }
119
+
120
+ const currentPlatform = process.platform;
121
+ const platformConfigs = currentPlatform === "darwin" ? MACOS_BROWSER_CONFIGS : currentPlatform === "linux" ? LINUX_BROWSER_CONFIGS : currentPlatform === "win32" ? WINDOWS_BROWSER_CONFIGS : [];
122
+ const configs = options.browser ? platformConfigs.filter((config) => config.id === options.browser) : platformConfigs;
123
+ if (options.browser && configs.length === 0) {
124
+ setCookieDiagnostic(`Browser preset '${options.browser}' is not supported on this platform.`);
125
+ return null;
126
+ }
127
+ if (configs.length === 0) {
128
+ setCookieDiagnostic("Chromium cookie extraction is unsupported on this platform.");
129
+ return null;
130
+ }
131
+
132
+ const warningSet = new Set<string>();
133
+ const rawProfile = typeof options.profile === "string" ? options.profile.trim() : "";
134
+ const requestedProfile = normalizeProfileName(options.profile);
135
+ if (rawProfile && !requestedProfile) {
136
+ setCookieDiagnostic("Configured Chromium profile must be a profile directory name, not a path.");
137
+ return null;
138
+ }
139
+ const requiredCookies = normalizeCookieNames(options.requiredCookies);
140
+ const cookieNames = normalizeCookieNames(options.cookieNames ? [...options.cookieNames] : undefined);
141
+ const hosts = normalizeHosts(options.hosts);
142
+ if (hosts.length === 0) {
143
+ setCookieDiagnostic("No valid cookie hosts were requested.");
144
+ return null;
145
+ }
146
+ const attempts: BrowserCookieAttemptDiagnostic[] = [];
147
+ const home = currentPlatform === "win32" ? process.env.USERPROFILE || homedir() : homedir();
148
+ let sawCookieDatabase = false;
149
+ let sawRequiredCookies = false;
150
+ let sawAnyHostCookie = false;
151
+ let sawBackendFailure: SqliteFailure | undefined;
152
+ let sawUnsafeProfilePath = false;
153
+ let sawWindowsAppBoundCookie = false;
154
+ let sawDecryptionFailure = false;
155
+
156
+ for (const config of configs) {
157
+ const profiles = requestedProfile ? [requestedProfile] : listBrowserProfiles(home, config);
158
+ for (const profile of profiles) {
159
+ const profilePath = resolveProfilePath(home, config, profile);
160
+ if (profilePath === "outside-root") {
161
+ sawUnsafeProfilePath = true;
162
+ recordCookieAttempt(attempts, config, profile, "unsafe-profile");
163
+ continue;
164
+ }
165
+ if (!profilePath) {
166
+ recordCookieAttempt(attempts, config, profile, "missing-database");
167
+ continue;
168
+ }
169
+ const cookiesPath = cookieDatabasePath(profilePath, config);
170
+ if (!cookiesPath) {
171
+ recordCookieAttempt(attempts, config, profile, "missing-database");
172
+ continue;
173
+ }
174
+ sawCookieDatabase = true;
175
+
176
+ const tempDir = mkdtempSync(join(tmpdir(), "pi-chrome-cookies-"));
177
+ try {
178
+ const tempDb = join(tempDir, "Cookies");
179
+ copyFileSync(cookiesPath, tempDb);
180
+ copySidecar(cookiesPath, tempDb, "-wal");
181
+ copySidecar(cookiesPath, tempDb, "-shm");
182
+
183
+ if (requiredCookies?.length) {
184
+ const preflight = await hasCookieNames(tempDb, hosts, requiredCookies);
185
+ if (preflight.failure) {
186
+ sawBackendFailure = preflight.failure;
187
+ recordCookieAttempt(attempts, config, profile, preflight.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
188
+ continue;
189
+ }
190
+ if (!preflight.present) {
191
+ recordCookieAttempt(attempts, config, profile, "missing-required-cookies");
192
+ continue;
193
+ }
194
+ sawRequiredCookies = true;
195
+ }
196
+
197
+ const key = currentPlatform === "win32"
198
+ ? await readWindowsEncryptionKey(config, home)
199
+ : await readBrowserPassword(config, currentPlatform).then((password) => password ? pbkdf2Sync(password, "saltysalt", currentPlatform === "darwin" ? 1003 : 1, 16, "sha1") : null);
200
+ if (!key) {
201
+ warningSet.add(currentPlatform === "win32"
202
+ ? `Could not read ${config.name} Windows cookie encryption key`
203
+ : `Could not read ${config.name} cookie encryption password`);
204
+ recordCookieAttempt(attempts, config, profile, "password-read-failed");
205
+ continue;
206
+ }
207
+ const metaVersion = await readMetaVersion(tempDb);
208
+ if (metaVersion.failure) {
209
+ sawBackendFailure = metaVersion.failure;
210
+ recordCookieAttempt(attempts, config, profile, metaVersion.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
211
+ }
212
+ if (metaVersion.value === null) continue;
213
+ const rowsResult = await queryCookieRows(tempDb, hosts, cookieNames ?? null, Boolean(options.requestUrl));
214
+ if (rowsResult.status === "failure") {
215
+ sawBackendFailure = rowsResult.failure;
216
+ recordCookieAttempt(attempts, config, profile, rowsResult.failure === "unavailable" ? "sqlite-unavailable" : "sqlite-query-failed");
217
+ continue;
218
+ }
219
+
220
+ const entries: BrowserCookieEntry[] = [];
221
+ const cookies: CookieMap = {};
222
+ const requiredDecryptFailures = new Set<string>();
223
+ for (const row of rowsResult.rows) {
224
+ const name = typeof row.name === "string" ? row.name : "";
225
+ if (!name) continue;
226
+ let value = typeof row.value === "string" && row.value.length > 0 ? row.value : null;
227
+ if (!value && typeof row.encrypted_value_hex === "string" && /^[0-9a-f]*$/i.test(row.encrypted_value_hex)) {
228
+ const encrypted = Buffer.from(row.encrypted_value_hex, "hex");
229
+ if (currentPlatform === "win32" && encrypted.subarray(0, 3).toString("utf8") === "v20") sawWindowsAppBoundCookie = true;
230
+ value = currentPlatform === "win32"
231
+ ? decryptWindowsCookieValue(encrypted, key, metaVersion.value >= 24)
232
+ : decryptCookieValue(encrypted, key, metaVersion.value >= 24);
233
+ if (!value && requiredCookies?.includes(name)) requiredDecryptFailures.add(name);
234
+ }
235
+ if (!value) continue;
236
+ const path = typeof row.path === "string" && row.path.startsWith("/") ? row.path : "/";
237
+ if (options.requestUrl && !pathMatches(options.requestUrl.pathname || "/", path)) continue;
238
+ entries.push({ name, value, path });
239
+ if (!cookies[name]) cookies[name] = value;
240
+ }
241
+
242
+ if (entries.length > 0) sawAnyHostCookie = true;
243
+ if (requiredCookies?.length && !requiredCookies.every((name) => Boolean(cookies[name]))) {
244
+ if (requiredCookies.some((name) => !cookies[name] && requiredDecryptFailures.has(name))) {
245
+ sawDecryptionFailure = true;
246
+ recordCookieAttempt(attempts, config, profile, "decryption-failed");
247
+ } else {
248
+ recordCookieAttempt(attempts, config, profile, "missing-required-cookies");
249
+ }
250
+ continue;
251
+ }
252
+ if (entries.length === 0) {
253
+ recordCookieAttempt(attempts, config, profile, requiredDecryptFailures.size > 0 ? "decryption-failed" : "no-host-cookies");
254
+ if (requiredDecryptFailures.size > 0) sawDecryptionFailure = true;
255
+ continue;
256
+ }
257
+ return {
258
+ cookies,
259
+ warnings: [...warningSet],
260
+ ...(options.requestUrl ? { cookieHeader: buildCookieHeader(entries) } : {}),
261
+ };
262
+ } finally {
263
+ rmSync(tempDir, { recursive: true, force: true });
264
+ }
265
+ }
266
+ }
267
+
268
+ if (sawBackendFailure === "unavailable") {
269
+ setCookieDiagnostic("SQLite backend unavailable: install sqlite3 or use a runtime with SQLite support.", attempts);
270
+ } else if (sawBackendFailure === "query") {
271
+ setCookieDiagnostic("SQLite query failed while reading the copied Chromium cookie database.", attempts);
272
+ } else if (sawUnsafeProfilePath) {
273
+ setCookieDiagnostic("Configured Chromium profile must resolve inside the browser profile root.", attempts);
274
+ } else if (!sawCookieDatabase) {
275
+ setCookieDiagnostic(requestedProfile
276
+ ? `Chromium profile '${requestedProfile}' does not contain a cookie database.`
277
+ : "No detected Chromium profile contains a cookie database.", attempts);
278
+ } else if (requiredCookies?.length && !sawRequiredCookies) {
279
+ setCookieDiagnostic(`No detected Chromium profile contains the required ${options.requiredLabel ?? "browser"} cookies.`, attempts);
280
+ } else if (sawWindowsAppBoundCookie) {
281
+ setCookieDiagnostic("Windows Chromium v20 app-bound cookies are not supported.", attempts);
282
+ } else if (warningSet.size > 0) {
283
+ setCookieDiagnostic([...warningSet][0], attempts);
284
+ } else if (sawDecryptionFailure) {
285
+ setCookieDiagnostic(`Required ${options.requiredLabel ?? "browser"} cookies could not be decrypted.`, attempts);
286
+ } else if (!sawAnyHostCookie) {
287
+ setCookieDiagnostic(options.requestUrl
288
+ ? "No detected Chromium profile contains cookies for the requested URL."
289
+ : "No detected Chromium profile contains cookies for the requested host.", attempts);
290
+ } else {
291
+ setCookieDiagnostic("Required Gemini cookies were not available or could not be decrypted.", attempts);
292
+ }
293
+ return null;
294
+ }
295
+
296
+ function setCookieDiagnostic(message: string, attempts: BrowserCookieAttemptDiagnostic[] = []): void {
297
+ lastCookieDiagnostic = message;
298
+ lastCookieDiagnosticDetails = { message, attempts };
299
+ }
300
+
301
+ function recordCookieAttempt(attempts: BrowserCookieAttemptDiagnostic[], config: BrowserConfig, profile: string, status: BrowserCookieAttemptStatus): void {
302
+ attempts.push({ browser: config.name, profile, status });
303
+ }
304
+
305
+ function normalizeProfileName(value: string | undefined): string | undefined {
306
+ if (typeof value !== "string") return undefined;
307
+ const normalized = value.trim();
308
+ if (!normalized) return undefined;
309
+ if (isAbsolute(normalized) || normalized === "." || normalized === ".." || normalized.includes("/") || normalized.includes("\\")) {
310
+ return undefined;
311
+ }
312
+ return normalized;
313
+ }
314
+
315
+ function resolveProfilePath(home: string, config: BrowserConfig, profile: string): string | "outside-root" | null {
316
+ const basePath = browserBasePath(home, config);
317
+ const profilePath = join(basePath, profile);
318
+ if (!cookieDatabasePath(profilePath, config)) return null;
319
+ try {
320
+ const baseRealPath = realpathSync(basePath);
321
+ const profileRealPath = realpathSync(profilePath);
322
+ if (profileRealPath !== baseRealPath && !profileRealPath.startsWith(`${baseRealPath}${sep}`)) return "outside-root";
323
+ return profileRealPath;
324
+ } catch {
325
+ return null;
326
+ }
327
+ }
328
+
329
+ function cookieDatabasePath(profilePath: string, config: BrowserConfig): string | null {
330
+ const networkCookies = join(profilePath, "Network", "Cookies");
331
+ if (config.usesLocalAppData && existsSync(networkCookies)) return networkCookies;
332
+ const legacyCookies = join(profilePath, "Cookies");
333
+ return existsSync(legacyCookies) ? legacyCookies : null;
334
+ }
335
+
336
+ function browserBasePath(home: string, config: BrowserConfig): string {
337
+ return config.usesLocalAppData
338
+ ? join(process.env.LOCALAPPDATA || join(home, "AppData", "Local"), config.baseDir)
339
+ : join(home, config.baseDir);
340
+ }
341
+
342
+ function normalizeCookieNames(names: string[] | undefined): string[] | undefined {
343
+ if (!names?.length) return undefined;
344
+ const normalized = names.filter((name): name is string => typeof name === "string").map((name) => name.trim()).filter(Boolean);
345
+ return normalized.length > 0 ? [...new Set(normalized)] : undefined;
346
+ }
347
+
348
+ function normalizeHosts(hosts: string[]): string[] {
349
+ return [...new Set(hosts.map(host => host.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "")).filter(Boolean))];
350
+ }
351
+
352
+ function listBrowserProfiles(home: string, config: BrowserConfig): string[] {
353
+ const basePath = browserBasePath(home, config);
354
+ if (!existsSync(basePath)) return ["Default"];
355
+ const profiles = new Set<string>();
356
+ try {
357
+ for (const entry of readdirSync(basePath, { withFileTypes: true })) {
358
+ if (entry.isDirectory() && cookieDatabasePath(join(basePath, entry.name), config)) profiles.add(entry.name);
359
+ }
360
+ } catch {
361
+ }
362
+ if (profiles.size === 0) return ["Default"];
363
+ return [...profiles].sort(compareProfileNames);
364
+ }
365
+
366
+ function compareProfileNames(a: string, b: string): number {
367
+ const key = (name: string): [number, number] => {
368
+ if (name === "Default") return [0, 0];
369
+ const profile = /^Profile\s+(\d+)$/i.exec(name);
370
+ if (profile) return [1, Number(profile[1])];
371
+ const person = /^Person\s+(\d+)$/i.exec(name);
372
+ if (person) return [2, Number(person[1])];
373
+ return [3, Number.MAX_SAFE_INTEGER];
374
+ };
375
+ const [ap, ai] = key(a);
376
+ const [bp, bi] = key(b);
377
+ return ap - bp || ai - bi || a.localeCompare(b, undefined, { sensitivity: "base", numeric: true });
378
+ }
379
+
380
+ function decryptCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {
381
+ const buf = Buffer.from(encrypted);
382
+ if (buf.length < 3 || !/^v\d\d$/.test(buf.subarray(0, 3).toString("utf8"))) return null;
383
+ const ciphertext = buf.subarray(3);
384
+ if (!ciphertext.length) return "";
385
+ try {
386
+ const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
387
+ decipher.setAutoPadding(false);
388
+ const unpadded = removePkcs7Padding(Buffer.concat([decipher.update(ciphertext), decipher.final()]));
389
+ const bytes = stripHash && unpadded.length >= 32 ? unpadded.subarray(32) : unpadded;
390
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
391
+ let i = 0;
392
+ while (i < decoded.length && decoded.charCodeAt(i) < 0x20) i++;
393
+ return decoded.slice(i);
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+
399
+ function decryptWindowsCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {
400
+ const buf = Buffer.from(encrypted);
401
+ if (buf.subarray(0, 3).toString("utf8") !== "v10" || buf.length < 3 + 12 + 16) return null;
402
+ try {
403
+ const nonce = buf.subarray(3, 15);
404
+ const ciphertext = buf.subarray(15, -16);
405
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
406
+ decipher.setAuthTag(buf.subarray(-16));
407
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
408
+ return new TextDecoder("utf-8", { fatal: true }).decode(stripHash && plaintext.length >= 32 ? plaintext.subarray(32) : plaintext);
409
+ } catch {
410
+ return null;
411
+ }
412
+ }
413
+
414
+ function removePkcs7Padding(buf: Buffer): Buffer {
415
+ if (!buf.length) return buf;
416
+ const padding = buf[buf.length - 1];
417
+ return !padding || padding > 16 ? buf : buf.subarray(0, buf.length - padding);
418
+ }
419
+
420
+ function readBrowserPassword(config: BrowserConfig, currentPlatform: typeof process.platform): Promise<string | null> {
421
+ const cacheKey = `${currentPlatform}:${config.name}`;
422
+ const cached = browserPasswordCache.get(cacheKey);
423
+ if (cached) return cached;
424
+ const passwordResult = currentPlatform === "darwin"
425
+ ? config.keychainAccount && config.keychainService
426
+ ? readKeychainPassword(config.keychainAccount, config.keychainService).then(password => ({ password, cacheable: Boolean(password) }))
427
+ : Promise.resolve({ password: null, cacheable: false })
428
+ : currentPlatform === "linux"
429
+ ? readLinuxPassword(config.secretToolApp)
430
+ : Promise.resolve({ password: null, cacheable: false });
431
+ const passwordPromise = passwordResult.then(({ password, cacheable }) => {
432
+ if (!cacheable) browserPasswordCache.delete(cacheKey);
433
+ return password;
434
+ }, (error) => {
435
+ browserPasswordCache.delete(cacheKey);
436
+ throw error;
437
+ });
438
+ browserPasswordCache.set(cacheKey, passwordPromise);
439
+ return passwordPromise;
440
+ }
441
+
442
+ async function readWindowsEncryptionKey(config: BrowserConfig, home: string): Promise<Buffer | null> {
443
+ try {
444
+ const localState = JSON.parse(readFileSync(join(browserBasePath(home, config), "Local State"), "utf8")) as { os_crypt?: { encrypted_key?: unknown } };
445
+ const encodedKey = localState.os_crypt?.encrypted_key;
446
+ if (typeof encodedKey !== "string") return null;
447
+ const protectedKey = Buffer.from(encodedKey, "base64");
448
+ if (protectedKey.subarray(0, 5).toString("utf8") !== "DPAPI") return null;
449
+ const decrypted = await unprotectWindowsData(protectedKey.subarray(5));
450
+ return decrypted?.length === 32 ? decrypted : null;
451
+ } catch {
452
+ return null;
453
+ }
454
+ }
455
+
456
+ function unprotectWindowsData(protectedData: Buffer): Promise<Buffer | null> {
457
+ return new Promise((resolve) => {
458
+ const script = "Add-Type -AssemblyName System.Security;$data=[Convert]::FromBase64String($env:PIWA_PROTECTED);$clear=[System.Security.Cryptography.ProtectedData]::Unprotect($data,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Convert]::ToBase64String($clear))";
459
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
460
+ execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { timeout: 5000, maxBuffer: 1024 * 1024, env: { ...process.env, PIWA_PROTECTED: protectedData.toString("base64") } }, (err, stdout) => {
461
+ if (err) { resolve(null); return; }
462
+ try {
463
+ resolve(Buffer.from(stdout.trim(), "base64"));
464
+ } catch {
465
+ resolve(null);
466
+ }
467
+ });
468
+ });
469
+ }
470
+
471
+ function readKeychainPassword(account: string, service: string): Promise<string | null> {
472
+ return new Promise((resolve) => {
473
+ execFile("security", ["find-generic-password", "-w", "-a", account, "-s", service], { timeout: 5000 }, (err, stdout) => {
474
+ if (err) { resolve(null); return; }
475
+ resolve(stdout.trim() || null);
476
+ });
477
+ });
478
+ }
479
+
480
+ function readLinuxPassword(secretToolApp: string | undefined): Promise<{ password: string; cacheable: boolean }> {
481
+ if (!secretToolApp) return Promise.resolve({ password: "peanuts", cacheable: true });
482
+ return new Promise((resolve) => {
483
+ execFile("secret-tool", ["lookup", "application", secretToolApp], { timeout: 5000 }, (err, stdout) => {
484
+ if (err) { resolve({ password: "peanuts", cacheable: false }); return; }
485
+ const password = stdout.trim();
486
+ resolve(password ? { password, cacheable: true } : { password: "peanuts", cacheable: false });
487
+ });
488
+ });
489
+ }
490
+
491
+ async function importSqlite(): Promise<typeof import("node:sqlite") | null> {
492
+ if (process.env.PI_WEB_ACCESS_DISABLE_NODE_SQLITE === "1") return null;
493
+ if (sqliteImportAttempted) return sqliteModule;
494
+ sqliteImportAttempted = true;
495
+ const orig = process.emitWarning.bind(process);
496
+ process.emitWarning = ((warning: string | Error, ...args: unknown[]) => {
497
+ const msg = typeof warning === "string" ? warning : warning?.message ?? "";
498
+ if (msg.includes("SQLite is an experimental feature")) return;
499
+ return (orig as Function)(warning, ...args);
500
+ }) as typeof process.emitWarning;
501
+ try {
502
+ sqliteModule = await import("node:sqlite");
503
+ } catch {
504
+ sqliteModule = null;
505
+ } finally {
506
+ process.emitWarning = orig;
507
+ }
508
+ return sqliteModule;
509
+ }
510
+
511
+ type QueryResult =
512
+ | { status: "success"; rows: SqliteRow[] }
513
+ | { status: "failure"; failure: SqliteFailure };
514
+
515
+ async function runSqliteQuery(dbPath: string, sql: string): Promise<QueryResult> {
516
+ const sqlite = await importSqlite();
517
+ let queryFailed = false;
518
+ if (sqlite) {
519
+ try {
520
+ const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
521
+ try {
522
+ return { status: "success", rows: db.prepare(sql).all() as SqliteRow[] };
523
+ } finally {
524
+ db.close();
525
+ }
526
+ } catch {
527
+ queryFailed = true;
528
+ }
529
+ }
530
+
531
+ const cli = await runSqliteCli(dbPath, sql);
532
+ if (cli.status === "success") return cli;
533
+ if (cli.failure === "query") queryFailed = true;
534
+ const python = await runPythonSqlite(dbPath, sql);
535
+ if (python.status === "success") return python;
536
+ if (python.failure === "query") queryFailed = true;
537
+ return { status: "failure", failure: queryFailed ? "query" : "unavailable" };
538
+ }
539
+
540
+ function runSqliteCli(dbPath: string, sql: string): Promise<QueryResult> {
541
+ return new Promise((resolve) => {
542
+ execFile("sqlite3", ["-readonly", "-json", dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
543
+ if (err) { resolve({ status: "failure", failure: err.code === "ENOENT" ? "unavailable" : "query" }); return; }
544
+ try {
545
+ const parsed = JSON.parse(stdout || "[]");
546
+ resolve(Array.isArray(parsed) ? { status: "success", rows: parsed as SqliteRow[] } : { status: "failure", failure: "query" });
547
+ } catch {
548
+ resolve({ status: "failure", failure: "query" });
549
+ }
550
+ });
551
+ });
552
+ }
553
+
554
+ function runPythonSqlite(dbPath: string, sql: string): Promise<QueryResult> {
555
+ const script = "import json,sqlite3,sys\ntry:\n c=sqlite3.connect('file:'+sys.argv[1]+'?mode=ro',uri=True)\n c.row_factory=sqlite3.Row\n print(json.dumps([dict(r) for r in c.execute(sys.argv[2]).fetchall()]))\nexcept Exception:\n sys.exit(1)";
556
+ return new Promise((resolve) => {
557
+ execFile("python3", ["-c", script, dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
558
+ if (err) { resolve({ status: "failure", failure: err.code === "ENOENT" ? "unavailable" : "query" }); return; }
559
+ try {
560
+ const parsed = JSON.parse(stdout || "[]");
561
+ resolve(Array.isArray(parsed) ? { status: "success", rows: parsed as SqliteRow[] } : { status: "failure", failure: "query" });
562
+ } catch {
563
+ resolve({ status: "failure", failure: "query" });
564
+ }
565
+ });
566
+ });
567
+ }
568
+
569
+ async function readMetaVersion(dbPath: string): Promise<{ value: number | null; failure?: SqliteFailure }> {
570
+ const result = await runSqliteQuery(dbPath, "SELECT value FROM meta WHERE key = 'version'");
571
+ if (result.status === "failure") {
572
+ return result.failure === "unavailable"
573
+ ? { value: null, failure: result.failure }
574
+ : { value: 0 };
575
+ }
576
+ const value = result.rows[0]?.value;
577
+ if (typeof value === "number") return { value: Math.floor(value) };
578
+ if (typeof value === "string") return { value: parseInt(value, 10) || 0 };
579
+ return { value: 0 };
580
+ }
581
+
582
+ async function hasCookieNames(dbPath: string, hosts: string[], names: string[]): Promise<{ present: boolean; failure?: SqliteFailure }> {
583
+ const result = await runSqliteQuery(dbPath, `SELECT DISTINCT name FROM cookies WHERE ${buildCookieWhere(hosts, names)}`);
584
+ if (result.status === "failure") return { present: false, failure: result.failure };
585
+ const present = new Set(result.rows.map((row) => typeof row.name === "string" ? row.name : ""));
586
+ return { present: names.every((name) => present.has(name)) };
587
+ }
588
+
589
+ async function queryCookieRows(dbPath: string, hosts: string[], names: Iterable<string> | null, filterExpired: boolean): Promise<QueryResult> {
590
+ const columns = await readCookieColumns(dbPath);
591
+ if (columns.status === "failure") return columns;
592
+ const pathExpr = columns.columns.has("path") ? "path" : "'/' AS path";
593
+ const expiresExpr = columns.columns.has("expires_utc") ? chromeExpiryMillisExpr() : "0";
594
+ const expiryFilter = filterExpired && columns.columns.has("expires_utc") ? ` AND (${expiresExpr} = 0 OR ${expiresExpr} > ${chromeExpiryNowMillis()})` : "";
595
+ const partitionFilter = filterExpired ? unpartitionedCookieFilter(columns.columns) : "";
596
+ return runSqliteQuery(dbPath, `SELECT name, value, host_key, ${pathExpr}, ${expiresExpr} AS expires_utc, hex(encrypted_value) AS encrypted_value_hex FROM cookies WHERE ${buildCookieWhere(hosts, names ?? undefined)}${expiryFilter}${partitionFilter} ORDER BY length(path) DESC, ${expiresExpr} ASC`);
597
+ }
598
+
599
+ async function readCookieColumns(dbPath: string): Promise<{ status: "success"; columns: Set<string> } | { status: "failure"; failure: SqliteFailure }> {
600
+ const result = await runSqliteQuery(dbPath, "PRAGMA table_info(cookies)");
601
+ if (result.status === "failure") return result;
602
+ return { status: "success", columns: new Set(result.rows.map(row => typeof row.name === "string" ? row.name : "")) };
603
+ }
604
+
605
+ function chromeExpiryMillisExpr(): string {
606
+ return "CASE WHEN expires_utc = 0 THEN 0 ELSE CAST(expires_utc / 1000 AS INTEGER) + CASE WHEN expires_utc % 1000 = 0 THEN 0 ELSE 1 END END";
607
+ }
608
+
609
+ function chromeExpiryNowMillis(): number {
610
+ return Date.now() + 11644473600000;
611
+ }
612
+
613
+ function unpartitionedCookieFilter(columns: Set<string>): string {
614
+ const clauses: string[] = [];
615
+ if (columns.has("top_frame_site_key")) clauses.push("(top_frame_site_key IS NULL OR top_frame_site_key = '')");
616
+ if (columns.has("partition_key")) clauses.push("(partition_key IS NULL OR partition_key = '')");
617
+ if (columns.has("is_partitioned")) clauses.push("(is_partitioned IS NULL OR is_partitioned = 0)");
618
+ return clauses.length > 0 ? ` AND ${clauses.join(" AND ")}` : "";
619
+ }
620
+
621
+ function buildCookieHeader(entries: BrowserCookieEntry[]): string {
622
+ return entries
623
+ .sort((a, b) => b.path.length - a.path.length)
624
+ .map(({ name, value }) => `${name}=${value}`)
625
+ .join("; ");
626
+ }
627
+
628
+ function pathMatches(requestPath: string, cookiePath: string): boolean {
629
+ if (requestPath === cookiePath) return true;
630
+ if (!requestPath.startsWith(cookiePath)) return false;
631
+ if (cookiePath.endsWith("/")) return true;
632
+ return requestPath[cookiePath.length] === "/";
633
+ }
634
+
635
+ function buildCookieWhere(hosts: string[], cookieNames?: Iterable<string>): string {
636
+ const hostClauses: string[] = [];
637
+ for (const host of hosts) {
638
+ const escapedHost = escapeSqlString(host);
639
+ hostClauses.push(`host_key = '${escapedHost}'`);
640
+ for (const candidate of domainCookieHosts(host)) {
641
+ hostClauses.push(`host_key = '.${escapeSqlString(candidate)}'`);
642
+ }
643
+ }
644
+ let where = `(${[...new Set(hostClauses)].join(" OR ")})`;
645
+ const names = cookieNames ? [...cookieNames].filter(Boolean) : [];
646
+ if (names.length) where += ` AND name IN (${names.map((name) => `'${escapeSqlString(name)}'`).join(", ")})`;
647
+ return where;
648
+ }
649
+
650
+ function escapeSqlString(value: string): string {
651
+ return value.replaceAll("'", "''");
652
+ }
653
+
654
+ function domainCookieHosts(host: string): string[] {
655
+ const parts = host.split(".").filter(Boolean);
656
+ if (parts.length <= 1) return [];
657
+ const candidates = new Set<string>();
658
+ for (let i = 0; i <= parts.length - 2; i++) candidates.add(parts.slice(i).join("."));
659
+ return [...candidates];
660
+ }
661
+
662
+ function copySidecar(srcDb: string, targetDb: string, suffix: string): void {
663
+ const sidecar = `${srcDb}${suffix}`;
664
+ if (!existsSync(sidecar)) return;
665
+ try {
666
+ copyFileSync(sidecar, `${targetDb}${suffix}`);
667
+ } catch {
668
+ }
669
+ }