Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
2// OSCrypt key derivation Chromium uses; Effect has no equivalent.
3/**
4 * Chromium cookie-encryption keys, per platform.
5 *
6 * Chromium calls this OSCrypt, and it works differently on each OS:
7 *
8 * - **macOS** keeps one key in the login keychain. Reading it prompts the
9 * user, which is the consent this feature is built around.
10 * - **Linux** may keep a key in libsecret/kwallet (`v11` records), or use a
11 * hardcoded `peanuts` passphrase when no keyring is available (`v10`). Both
12 * can appear in the same database, so both are derived up front and chosen
13 * per record.
14 *
15 * - **Windows** legacy Chromium stores protect a random AES key with DPAPI.
16 * App-Bound Encryption remains deliberately unsupported.
17 *
18 * @module ChromiumKeys
19 */
20import * as Keyring from "@napi-rs/keyring";
21import * as NodeCrypto from "node:crypto";
22
23import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
24
25import * as Effect from "effect/Effect";
26import * as Encoding from "effect/Encoding";
27import * as FileSystem from "effect/FileSystem";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
31import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
32
33const KEY_SALT = "saltysalt";
34const KEY_LENGTH = 16;
35/** macOS stretches the keychain secret; Linux uses a single iteration. */
36const MAC_KEY_ITERATIONS = 1003;
37const LINUX_KEY_ITERATIONS = 1;
38/** Chromium's documented fallback passphrase when no Linux keyring is present. */
39const LINUX_FALLBACK_PASSPHRASE = "peanuts";
40
41export const ChromiumKeyFailure = Schema.Literals([
42 "needsKeychainApproval",
43 "keychainItemMissing",
44 "keychainUnavailable",
45 "unsupportedPlatform",
46 /** The key store itself could not be read, as opposed to holding no key. */
47 "readFailed",
48]);
49export type ChromiumKeyFailure = typeof ChromiumKeyFailure.Type;
50
51export class ChromiumKeyError extends Schema.TaggedError<ChromiumKeyError>()("ChromiumKeyError", {
52 reason: ChromiumKeyFailure,
53 /** Kept for the log; never surfaced to the user. */
54 cause: Schema.optional(Schema.Defect()),
55}) {
56 override get message(): string {
57 return `Could not obtain the Chromium cookie key: ${this.reason}.`;
58 }
59}
60
61/**
62 * Keys to try, indexed by the record prefix they decrypt. A database can hold
63 * records written under more than one scheme, so a missing entry means those
64 * records are skipped rather than the whole import failing.
65 */
66export interface ChromiumKeyMaterial {
67 /** AES-128-CBC on macOS, and the keyring-free Linux fallback. */
68 readonly cbcV10?: Buffer;
69 /** AES-128-CBC, Linux keyring-derived. */
70 readonly cbcV11?: Buffer;
71 /** Retained so an import that needs this key can report why it is missing. */
72 readonly cbcV11Error?: ChromiumKeyError;
73 /**
74 * AES-128-CBC from an empty passphrase. Some Linux clients wrote records
75 * with it (crbug.com/1195256), so Chromium — and this import — retry with it
76 * after a record's own key fails.
77 */
78 readonly cbcEmpty?: Buffer;
79 /** AES-256-GCM key used by pre-App-Bound Chromium on Windows. */
80 readonly gcmV10?: Buffer;
81}
82
83const derive = (passphrase: string, iterations: number) =>
84 NodeCrypto.pbkdf2Sync(passphrase, KEY_SALT, iterations, KEY_LENGTH, "sha1");
85
86/**
87 * Reads the macOS OSCrypt secret from the login keychain.
88 *
89 * Uses the in-process Keychain API rather than shelling out to
90 * `/usr/bin/security`, because macOS attributes both the consent prompt and the
91 * resulting ACL entry to the binary that asks. Via the CLI the prompt says
92 * "security" and "Always Allow" grants trust to a tool every process on the
93 * machine can invoke; in-process it names this app and the grant belongs to it.
94 * (In an unsigned dev build the name is the dev binary, not the shipped app
95 * identity.)
96 *
97 * Deliberately untimed: macOS answers this with a modal, and a timeout racing
98 * the user means the prompt can be approved while nothing is left listening,
99 * which reads as "approving did nothing".
100 */
101const readKeychainSecret = Effect.fn("ChromiumKeys.readKeychainSecret")(function* (
102 service: string,
103 account: string,
104) {
105 const secret = yield* Effect.try({
106 try: () => new Keyring.Entry(service, account).getPassword(),
107 catch: (cause) => {
108 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
109 // Distinguish the causes rather than reporting "approve the prompt" for
110 // a failure approving cannot fix.
111 const missing = /no (matching )?entry|not found/i.test(message);
112 return new ChromiumKeyError({
113 reason: missing ? "keychainItemMissing" : "needsKeychainApproval",
114 cause,
115 });
116 },
117 });
118 if (secret === null || secret === "") {
119 return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
120 }
121 return secret;
122});
123
124/**
125 * The bundled helper searches Chromium's libsecret schema and application
126 * attribute, retaining the desktop's normal unlock prompt. Its exit codes
127 * distinguish a missing key, denied access, and an unavailable keyring without
128 * parsing localized error messages. Stdout is the unmodified secret.
129 */
130export const readLinuxSecret = Effect.fn("ChromiumKeys.readLinuxSecret")(function* (
131 application: string,
132) {
133 return yield* Effect.scoped(
134 Effect.gen(function* () {
135 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
136 const environment = yield* HostProcessEnvironment;
137 const helper = yield* LinuxBrowserSecretPath;
138 if (helper === undefined) {
139 return yield* new ChromiumKeyError({ reason: "keychainUnavailable" });
140 }
141 const handle = yield* spawner
142 .spawn(ChildProcess.make(helper, [application], { stdin: "ignore", env: environment }))
143 .pipe(
144 Effect.mapError(
145 (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
146 ),
147 );
148 const [secret, , exitCode] = yield* Effect.all(
149 [
150 handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
151 handle.stderr.pipe(Stream.runDrain),
152 handle.exitCode,
153 ],
154 { concurrency: "unbounded" },
155 ).pipe(
156 Effect.mapError((cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause })),
157 );
158 if (Number(exitCode) !== 0) {
159 return yield* new ChromiumKeyError({
160 reason:
161 Number(exitCode) === 2
162 ? "keychainItemMissing"
163 : Number(exitCode) === 3
164 ? "needsKeychainApproval"
165 : "keychainUnavailable",
166 });
167 }
168 if (secret === "") {
169 return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
170 }
171 return secret;
172 }),
173 );
174});
175
176const WindowsLocalState = Schema.Struct({
177 os_crypt: Schema.Struct({
178 encrypted_key: Schema.String,
179 app_bound_encrypted_key: Schema.optional(Schema.String),
180 }),
181});
182const decodeWindowsLocalState = Schema.decodeUnknownEffect(
183 Schema.fromJsonString(WindowsLocalState),
184);
185const DPAPI_PREFIX = Buffer.from("DPAPI");
186const WINDOWS_KEY_LENGTH = 32;
187const WINDOWS_DPAPI_SCRIPT =
188 "Add-Type -AssemblyName System.Security;" +
189 "$value=[Console]::In.ReadToEnd();" +
190 "$encrypted=[Convert]::FromBase64String($value);" +
191 "$plain=[Security.Cryptography.ProtectedData]::Unprotect($encrypted,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);" +
192 "[Console]::Out.Write([Convert]::ToBase64String($plain))";
193
194export const decodeWindowsWrappedKey = Effect.fn("ChromiumKeys.decodeWindowsWrappedKey")(function* (
195 contents: string,
196) {
197 const state = yield* decodeWindowsLocalState(contents).pipe(
198 Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
199 );
200 if (state.os_crypt.app_bound_encrypted_key !== undefined) {
201 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
202 }
203 const wrapped = yield* Effect.fromResult(
204 Encoding.decodeBase64(state.os_crypt.encrypted_key),
205 ).pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
206 const wrappedBuffer = Buffer.from(wrapped);
207 if (!wrappedBuffer.subarray(0, DPAPI_PREFIX.length).equals(DPAPI_PREFIX)) {
208 return yield* new ChromiumKeyError({ reason: "readFailed" });
209 }
210 return wrappedBuffer.subarray(DPAPI_PREFIX.length);
211});
212
213/** Unwraps a key with the current Windows user's DPAPI identity. */
214export const unwrapWindowsDpapiKey = Effect.fn("ChromiumKeys.unwrapWindowsDpapiKey")(function* (
215 wrapped: Buffer,
216) {
217 const environment = yield* HostProcessEnvironment;
218 return yield* Effect.scoped(
219 Effect.gen(function* () {
220 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
221 const windowsRoot = environment.SystemRoot ?? environment.WINDIR;
222 const powershell = windowsRoot
223 ? `${windowsRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
224 : "powershell.exe";
225 const handle = yield* spawner
226 .spawn(
227 ChildProcess.make(
228 powershell,
229 [
230 "-NoLogo",
231 "-NoProfile",
232 "-NonInteractive",
233 "-WindowStyle",
234 "Hidden",
235 "-Command",
236 WINDOWS_DPAPI_SCRIPT,
237 ],
238 {
239 env: environment,
240 stdin: Stream.encodeText(Stream.make(wrapped.toString("base64"))),
241 },
242 ),
243 )
244 .pipe(
245 Effect.mapError(
246 (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
247 ),
248 );
249 const [plainEncoded, , exitCode] = yield* Effect.all(
250 [
251 handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
252 handle.stderr.pipe(Stream.runDrain),
253 handle.exitCode,
254 ],
255 { concurrency: "unbounded" },
256 ).pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
257 if (Number(exitCode) !== 0) {
258 return yield* new ChromiumKeyError({ reason: "readFailed" });
259 }
260 const plain = yield* Effect.fromResult(Encoding.decodeBase64(plainEncoded)).pipe(
261 Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
262 );
263 if (plain.length !== WINDOWS_KEY_LENGTH) {
264 return yield* new ChromiumKeyError({ reason: "readFailed" });
265 }
266 return Buffer.from(plain);
267 }),
268 );
269});
270
271/** Reads and unwraps a legacy Windows Chromium key without exposing it in argv. */
272export const readWindowsKey = Effect.fn("ChromiumKeys.readWindowsKey")(function* (
273 localStatePath: string,
274) {
275 const fileSystem = yield* FileSystem.FileSystem;
276 const contents = yield* fileSystem
277 .readFileString(localStatePath)
278 .pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
279 return yield* unwrapWindowsDpapiKey(yield* decodeWindowsWrappedKey(contents));
280});
281
282export interface ChromiumKeyRequest {
283 readonly platform: NodeJS.Platform;
284 readonly keychainService: string | undefined;
285 readonly keychainAccount: string | undefined;
286 readonly linuxSecretApplication: string | undefined;
287}
288
289export const resolveChromiumKeys = Effect.fn("ChromiumKeys.resolveChromiumKeys")(function* (
290 request: ChromiumKeyRequest,
291): Effect.fn.Return<
292 ChromiumKeyMaterial,
293 ChromiumKeyError,
294 ChildProcessSpawner.ChildProcessSpawner
295> {
296 if (request.platform === "darwin") {
297 if (!request.keychainService || !request.keychainAccount) {
298 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
299 }
300 const secret = yield* readKeychainSecret(request.keychainService, request.keychainAccount);
301 return { cbcV10: derive(secret, MAC_KEY_ITERATIONS) };
302 }
303
304 if (request.platform === "linux") {
305 // The fallback passphrase always applies to `v10` records; a keyring
306 // secret, when one is reachable, additionally unlocks `v11`. Preserve its
307 // failure until the reader knows whether any cookies needed that key.
308 const keyringSecret = request.linuxSecretApplication
309 ? yield* readLinuxSecret(request.linuxSecretApplication).pipe(
310 // v10 remains importable when Secret Service is absent or does not
311 // contain a key. An explicit denial/lock/cancel remains a consent
312 // failure rather than being silently downgraded.
313 Effect.catch((error) =>
314 error.reason === "needsKeychainApproval" ? Effect.fail(error) : Effect.succeed(error),
315 ),
316 )
317 : undefined;
318 return {
319 cbcV10: derive(LINUX_FALLBACK_PASSPHRASE, LINUX_KEY_ITERATIONS),
320 ...(typeof keyringSecret === "string"
321 ? { cbcV11: derive(keyringSecret, LINUX_KEY_ITERATIONS) }
322 : keyringSecret
323 ? { cbcV11Error: keyringSecret }
324 : {}),
325 cbcEmpty: derive("", LINUX_KEY_ITERATIONS),
326 };
327 }
328
329 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
330});