Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
2// OSCrypt primitives Chromium uses; Effect has no equivalent.
3import * as NodeCrypto from "node:crypto";
4
5import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as SqlClient from "effect/sql/SqlClient";
12import { ChildProcessSpawner } from "effect/process";
13
14import {
15 ChromiumKeyError,
16 ChromiumKeyFailure,
17 readWindowsKey,
18 resolveChromiumKeys,
19 type ChromiumKeyMaterial,
20} from "./ChromiumKeys.ts";
21import {
22 bareHost,
23 cookieScope,
24 snapshotCookieDatabase,
25 type CookieReadResult,
26 type ImportedCookie,
27} from "./CookieDatabase.ts";
28
29/** OSCrypt's CBC mode uses a fixed IV of 16 spaces rather than a per-record one. */
30const AES_CBC_IV = Buffer.alloc(16, 0x20);
31const AES_GCM_NONCE_LENGTH = 12;
32const AES_GCM_TAG_LENGTH = 16;
33const isChromiumKeyError = Schema.is(ChromiumKeyError);
34
35export const ChromiumCookieReadReason = Schema.Literals([
36 ...ChromiumKeyFailure.literals,
37 "browserRunning",
38]);
39export type ChromiumCookieReadReason = typeof ChromiumCookieReadReason.Type;
40
41export class ChromiumCookieReadError extends Schema.TaggedError<ChromiumCookieReadError>()(
42 "ChromiumCookieReadError",
43 {
44 reason: ChromiumCookieReadReason,
45 cookieDatabasePath: Schema.String,
46 cause: Schema.optional(Schema.Defect()),
47 },
48) {
49 override get message(): string {
50 return `Could not read Chromium cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
51 }
52}
53
54const CookieRow = Schema.Struct({
55 host_key: Schema.String,
56 name: Schema.String,
57 value: Schema.String,
58 encrypted_value: Schema.Uint8Array,
59 path: Schema.String,
60 expires_seconds: Schema.Number,
61 is_secure: Schema.Number,
62 is_httponly: Schema.Number,
63 samesite: Schema.Number,
64 top_frame_site_key: Schema.String,
65});
66const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow));
67const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
68const SchemaVersion = Schema.Union([
69 NonNegativeInt,
70 Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
71]);
72const decodeSchemaVersion = Schema.decodeUnknownEffect(
73 Schema.Tuple([Schema.Struct({ value: SchemaVersion })]),
74);
75
76/**
77 * Unspecified is imported as Electron's own `unspecified` rather than pinned to
78 * Lax, so the target browser applies its default just as the source did;
79 * anything unrecognised lands there too, since guessing "none" would widen a
80 * cookie's scope on import.
81 */
82const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => {
83 if (value === 0) return "no_restriction";
84 if (value === 1) return "lax";
85 if (value === 2) return "strict";
86 return "unspecified";
87};
88
89/**
90 * The microsecond value overflows JavaScript's safe integer range and
91 * `node:sqlite` refuses to narrow it, so the division happens in SQL and this
92 * only ever sees seconds.
93 */
94const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600;
95const toUnixSeconds = (webkitSeconds: number): number | undefined => {
96 if (webkitSeconds <= 0) return undefined;
97 return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS;
98};
99
100/**
101 * Chromium >= 127 prefixes the plaintext with SHA-256 of the host key, binding
102 * a cookie to its domain.
103 */
104const stripDomainBinding = (
105 plaintext: Buffer,
106 domain: string,
107 schemaVersion: number,
108): Buffer | null => {
109 if (schemaVersion < 24) return plaintext;
110 const domainHash = NodeCrypto.createHash("sha256").update(domain).digest();
111 return plaintext.length >= 32 && plaintext.subarray(0, 32).equals(domainHash)
112 ? plaintext.subarray(32)
113 : null;
114};
115
116const decryptCbc = (
117 payload: Buffer,
118 key: Buffer,
119 domain: string,
120 schemaVersion: number,
121): string | null => {
122 try {
123 const decipher = NodeCrypto.createDecipheriv("aes-128-cbc", key, AES_CBC_IV);
124 decipher.setAutoPadding(true);
125 const plaintext = Buffer.concat([decipher.update(payload), decipher.final()]);
126 return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
127 } catch {
128 return null;
129 }
130};
131
132const decryptGcm = (
133 payload: Buffer,
134 key: Buffer,
135 domain: string,
136 schemaVersion: number,
137): string | null => {
138 if (payload.length < AES_GCM_NONCE_LENGTH + AES_GCM_TAG_LENGTH) return null;
139 try {
140 const nonce = payload.subarray(0, AES_GCM_NONCE_LENGTH);
141 const ciphertext = payload.subarray(AES_GCM_NONCE_LENGTH, -AES_GCM_TAG_LENGTH);
142 const tag = payload.subarray(-AES_GCM_TAG_LENGTH);
143 const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", key, nonce);
144 decipher.setAuthTag(tag);
145 const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
146 return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
147 } catch {
148 return null;
149 }
150};
151
152export function decryptChromiumValue(
153 encrypted: Uint8Array,
154 keys: ChromiumKeyMaterial,
155 domain: string,
156 schemaVersion = 23,
157 platform: NodeJS.Platform = "linux",
158): string | null {
159 const buffer = Buffer.from(encrypted);
160 if (buffer.length === 0) return "";
161 const prefix = buffer.subarray(0, 3).toString("latin1");
162 const payload = buffer.subarray(3);
163
164 // Windows' legacy v10 format is AES-256-GCM. App-bound records use v20 and
165 // intentionally have no key here, so they fall through as undecryptable.
166 if (platform === "win32") {
167 return prefix === "v10" && keys.gcmV10
168 ? decryptGcm(payload, keys.gcmV10, domain, schemaVersion)
169 : null;
170 }
171
172 // Chromium retries a failed record with a key derived from an empty
173 // passphrase, because some Linux clients wrote data that way
174 // (crbug.com/1195256).
175 if (prefix === "v10") {
176 if (!keys.cbcV10) return null;
177 return (
178 decryptCbc(payload, keys.cbcV10, domain, schemaVersion) ??
179 (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
180 );
181 }
182 if (prefix === "v11") {
183 if (!keys.cbcV11) return null;
184 return (
185 decryptCbc(payload, keys.cbcV11, domain, schemaVersion) ??
186 (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
187 );
188 }
189 if (platform === "darwin" || platform === "linux") {
190 return stripDomainBinding(buffer, domain, schemaVersion)?.toString("utf8") ?? null;
191 }
192 return null;
193}
194
195export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiumCookieDatabase")(
196 function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) {
197 const result = yield* Effect.gen(function* () {
198 const sql = yield* SqlClient.SqlClient;
199 const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
200 Effect.flatMap(decodeSchemaVersion),
201 Effect.map(([row]) => row.value),
202 );
203 const raw =
204 schemaVersion >= 15
205 ? yield* sql`select host_key, name, value, encrypted_value, path,
206 expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
207 samesite, top_frame_site_key from cookies`
208 : yield* sql`select host_key, name, value, encrypted_value, path,
209 expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
210 samesite, '' as top_frame_site_key from cookies`;
211 return { rows: yield* decodeCookieRows(raw), schemaVersion };
212 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })));
213
214 const cookies: ImportedCookie[] = [];
215 let undecryptable = 0;
216 const undecryptableHosts = new Set<string>();
217 for (const row of result.rows) {
218 if (row.top_frame_site_key !== "") {
219 undecryptable += 1;
220 undecryptableHosts.add(bareHost(row.host_key));
221 continue;
222 }
223 const value =
224 row.encrypted_value.length === 0
225 ? row.value
226 : decryptChromiumValue(
227 row.encrypted_value,
228 keys,
229 row.host_key,
230 result.schemaVersion,
231 platform,
232 );
233 if (value === null) {
234 undecryptable += 1;
235 undecryptableHosts.add(bareHost(row.host_key));
236 continue;
237 }
238 const secure = row.is_secure === 1;
239 const scope = cookieScope(row.host_key, row.path, secure);
240 cookies.push({
241 url: scope.url,
242 name: row.name,
243 value,
244 domain: scope.domain,
245 path: row.path,
246 secure,
247 httpOnly: row.is_httponly === 1,
248 expirationDate: toUnixSeconds(row.expires_seconds),
249 sameSite: sameSiteFromColumn(row.samesite),
250 });
251 }
252 if (
253 cookies.length === 0 &&
254 keys.cbcV11Error !== undefined &&
255 result.rows.some(
256 (row) =>
257 row.top_frame_site_key === "" &&
258 Buffer.from(row.encrypted_value.subarray(0, 3)).toString("latin1") === "v11",
259 )
260 ) {
261 return yield* keys.cbcV11Error;
262 }
263 return {
264 cookies,
265 undecryptable,
266 undecryptableHosts: [...undecryptableHosts],
267 } satisfies CookieReadResult;
268 },
269);
270
271export interface ChromiumCookieSource {
272 readonly cookieDatabasePath: string;
273 readonly keychainService: string | undefined;
274 readonly keychainAccount: string | undefined;
275 readonly linuxSecretApplication: string | undefined;
276 readonly windowsLocalStatePath?: string;
277 readonly platform: NodeJS.Platform;
278}
279
280export const readChromiumCookies = Effect.fn("ChromiumCookies.readChromiumCookies")(function* (
281 source: ChromiumCookieSource,
282): Effect.fn.Return<
283 CookieReadResult,
284 ChromiumCookieReadError,
285 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
286> {
287 const keys = yield* (
288 source.platform === "win32" && source.windowsLocalStatePath
289 ? readWindowsKey(source.windowsLocalStatePath).pipe(Effect.map((gcmV10) => ({ gcmV10 })))
290 : resolveChromiumKeys({
291 platform: source.platform,
292 keychainService: source.keychainService,
293 keychainAccount: source.keychainAccount,
294 linuxSecretApplication: source.linuxSecretApplication,
295 })
296 ).pipe(
297 Effect.mapError(
298 (cause: ChromiumKeyError) =>
299 new ChromiumCookieReadError({
300 reason: cause.reason,
301 cookieDatabasePath: source.cookieDatabasePath,
302 cause,
303 }),
304 ),
305 );
306
307 const snapshotPath = yield* snapshotCookieDatabase(source.cookieDatabasePath).pipe(
308 Effect.mapError(
309 (cause) =>
310 new ChromiumCookieReadError({
311 reason: "readFailed",
312 cookieDatabasePath: source.cookieDatabasePath,
313 cause,
314 }),
315 ),
316 );
317
318 return yield* readChromiumCookieDatabase(snapshotPath, keys, source.platform).pipe(
319 Effect.mapError(
320 (cause) =>
321 new ChromiumCookieReadError({
322 reason: isChromiumKeyError(cause) ? cause.reason : "readFailed",
323 cookieDatabasePath: source.cookieDatabasePath,
324 cause,
325 }),
326 ),
327 );
328});