Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChromiumKeys.ts

333 lines12.8 KB

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