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/** Preserve unspecified SameSite; guessing no_restriction would widen cookie scope. */
77const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => {
78 if (value === 0) return "no_restriction";
79 if (value === 1) return "lax";
80 if (value === 2) return "strict";
81 return "unspecified";
82};
83
84/** Convert microseconds in SQL: node:sqlite refuses integers beyond JavaScript's safe range. */
85const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600;
86const toUnixSeconds = (webkitSeconds: number): number | undefined => {
87 if (webkitSeconds <= 0) return undefined;
88 return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS;
89};
90
91// Chromium 127+ prefixes plaintext with the host-key SHA-256 to bind its domain.
92const stripDomainBinding = (
93 plaintext: Buffer,
94 domain: string,
95 schemaVersion: number,
96): Buffer | null => {
97 if (schemaVersion < 24) return plaintext;
98 const domainHash = NodeCrypto.createHash("sha256").update(domain).digest();
99 return plaintext.length >= 32 && plaintext.subarray(0, 32).equals(domainHash)
100 ? plaintext.subarray(32)
101 : null;
102};
103
104const decryptCbc = (
105 payload: Buffer,
106 key: Buffer,
107 domain: string,
108 schemaVersion: number,
109): string | null => {
110 try {
111 const decipher = NodeCrypto.createDecipheriv("aes-128-cbc", key, AES_CBC_IV);
112 decipher.setAutoPadding(true);
113 const plaintext = Buffer.concat([decipher.update(payload), decipher.final()]);
114 return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
115 } catch {
116 return null;
117 }
118};
119
120const decryptGcm = (
121 payload: Buffer,
122 key: Buffer,
123 domain: string,
124 schemaVersion: number,
125): string | null => {
126 if (payload.length < AES_GCM_NONCE_LENGTH + AES_GCM_TAG_LENGTH) return null;
127 try {
128 const nonce = payload.subarray(0, AES_GCM_NONCE_LENGTH);
129 const ciphertext = payload.subarray(AES_GCM_NONCE_LENGTH, -AES_GCM_TAG_LENGTH);
130 const tag = payload.subarray(-AES_GCM_TAG_LENGTH);
131 const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", key, nonce);
132 decipher.setAuthTag(tag);
133 const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
134 return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null;
135 } catch {
136 return null;
137 }
138};
139
140export function decryptChromiumValue(
141 encrypted: Uint8Array,
142 keys: ChromiumKeyMaterial,
143 domain: string,
144 schemaVersion = 23,
145 platform: NodeJS.Platform = "linux",
146): string | null {
147 const buffer = Buffer.from(encrypted);
148 if (buffer.length === 0) return "";
149 const prefix = buffer.subarray(0, 3).toString("latin1");
150 const payload = buffer.subarray(3);
151
152 // Windows v10 uses AES-256-GCM; app-bound v20 records have no key here.
153 if (platform === "win32") {
154 return prefix === "v10" && keys.gcmV10
155 ? decryptGcm(payload, keys.gcmV10, domain, schemaVersion)
156 : null;
157 }
158
159 // Retry the empty-passphrase key used by some Linux clients (crbug.com/1195256).
160 if (prefix === "v10") {
161 if (!keys.cbcV10) return null;
162 return (
163 decryptCbc(payload, keys.cbcV10, domain, schemaVersion) ??
164 (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
165 );
166 }
167 if (prefix === "v11") {
168 if (!keys.cbcV11) return null;
169 return (
170 decryptCbc(payload, keys.cbcV11, domain, schemaVersion) ??
171 (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null)
172 );
173 }
174 if (platform === "darwin" || platform === "linux") {
175 return stripDomainBinding(buffer, domain, schemaVersion)?.toString("utf8") ?? null;
176 }
177 return null;
178}
179
180export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiumCookieDatabase")(
181 function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) {
182 const result = yield* Effect.gen(function* () {
183 const sql = yield* SqlClient.SqlClient;
184 const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
185 Effect.flatMap(decodeSchemaVersion),
186 Effect.map(([row]) => row.value),
187 );
188 const raw =
189 schemaVersion >= 15
190 ? yield* sql`select host_key, name, value, encrypted_value, path,
191 expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
192 samesite, top_frame_site_key from cookies`
193 : yield* sql`select host_key, name, value, encrypted_value, path,
194 expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
195 samesite, '' as top_frame_site_key from cookies`;
196 return { rows: yield* decodeCookieRows(raw), schemaVersion };
197 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })));
198
199 const cookies: ImportedCookie[] = [];
200 let undecryptable = 0;
201 const undecryptableHosts = new Set<string>();
202 for (const row of result.rows) {
203 if (row.top_frame_site_key !== "") {
204 undecryptable += 1;
205 undecryptableHosts.add(bareHost(row.host_key));
206 continue;
207 }
208 const value =
209 row.encrypted_value.length === 0
210 ? row.value
211 : decryptChromiumValue(
212 row.encrypted_value,
213 keys,
214 row.host_key,
215 result.schemaVersion,
216 platform,
217 );
218 if (value === null) {
219 undecryptable += 1;
220 undecryptableHosts.add(bareHost(row.host_key));
221 continue;
222 }
223 const secure = row.is_secure === 1;
224 const scope = cookieScope(row.host_key, row.path, secure);
225 cookies.push({
226 url: scope.url,
227 name: row.name,
228 value,
229 domain: scope.domain,
230 path: row.path,
231 secure,
232 httpOnly: row.is_httponly === 1,
233 expirationDate: toUnixSeconds(row.expires_seconds),
234 sameSite: sameSiteFromColumn(row.samesite),
235 });
236 }
237 if (
238 cookies.length === 0 &&
239 keys.cbcV11Error !== undefined &&
240 result.rows.some(
241 (row) =>
242 row.top_frame_site_key === "" &&
243 Buffer.from(row.encrypted_value.subarray(0, 3)).toString("latin1") === "v11",
244 )
245 ) {
246 return yield* keys.cbcV11Error;
247 }
248 return {
249 cookies,
250 undecryptable,
251 undecryptableHosts: [...undecryptableHosts],
252 } satisfies CookieReadResult;
253 },
254);
255
256export interface ChromiumCookieSource {
257 readonly cookieDatabasePath: string;
258 readonly keychainService: string | undefined;
259 readonly keychainAccount: string | undefined;
260 readonly linuxSecretApplication: string | undefined;
261 readonly windowsLocalStatePath?: string;
262 readonly platform: NodeJS.Platform;
263}
264
265export const readChromiumCookies = Effect.fn("ChromiumCookies.readChromiumCookies")(function* (
266 source: ChromiumCookieSource,
267): Effect.fn.Return<
268 CookieReadResult,
269 ChromiumCookieReadError,
270 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
271> {
272 const keys = yield* (
273 source.platform === "win32" && source.windowsLocalStatePath
274 ? readWindowsKey(source.windowsLocalStatePath).pipe(Effect.map((gcmV10) => ({ gcmV10 })))
275 : resolveChromiumKeys({
276 platform: source.platform,
277 keychainService: source.keychainService,
278 keychainAccount: source.keychainAccount,
279 linuxSecretApplication: source.linuxSecretApplication,
280 })
281 ).pipe(
282 Effect.mapError(
283 (cause: ChromiumKeyError) =>
284 new ChromiumCookieReadError({
285 reason: cause.reason,
286 cookieDatabasePath: source.cookieDatabasePath,
287 cause,
288 }),
289 ),
290 );
291
292 const snapshotPath = yield* snapshotCookieDatabase(source.cookieDatabasePath).pipe(
293 Effect.mapError(
294 (cause) =>
295 new ChromiumCookieReadError({
296 reason: "readFailed",
297 cookieDatabasePath: source.cookieDatabasePath,
298 cause,
299 }),
300 ),
301 );
302
303 return yield* readChromiumCookieDatabase(snapshotPath, keys, source.platform).pipe(
304 Effect.mapError(
305 (cause) =>
306 new ChromiumCookieReadError({
307 reason: isChromiumKeyError(cause) ? cause.reason : "readFailed",
308 cookieDatabasePath: source.cookieDatabasePath,
309 cause,
310 }),
311 ),
312 );
313});