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

ChromiumKeys.ts

295 lines10.9 KB

1// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
2// OSCrypt key derivation Chromium uses; Effect has no equivalent.
3import * as NodeCrypto from "node:crypto";
4​
5import * as HostProcess from "@t3tools/shared/HostProcess";
6​
7import * as Effect from "effect/Effect";
8import * as Base64 from "effect/encoding/Base64";
9import * as FileSystem from "effect/FileSystem";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/process";
13import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
14​
15const KEY_SALT = "saltysalt";
16const KEY_LENGTH = 16;
17/** macOS stretches the keychain secret; Linux uses a single iteration. */
18const MAC_KEY_ITERATIONS = 1003;
19const LINUX_KEY_ITERATIONS = 1;
20/** Chromium's documented fallback passphrase when no Linux keyring is present. */
21const LINUX_FALLBACK_PASSPHRASE = "peanuts";
22​
23export const ChromiumKeyFailure = Schema.Literals([
24 "needsKeychainApproval",
25 "keychainItemMissing",
26 "keychainUnavailable",
27 "unsupportedPlatform",
28 "readFailed",
29]);
30export type ChromiumKeyFailure = typeof ChromiumKeyFailure.Type;
31​
32export class ChromiumKeyError extends Schema.TaggedError<ChromiumKeyError>()("ChromiumKeyError", {
33 reason: ChromiumKeyFailure,
34 cause: Schema.optional(Schema.Defect()),
35}) {
36 override get message(): string {
37 return `Could not obtain the Chromium cookie key: ${this.reason}.`;
38 }
40​
41export interface ChromiumKeyMaterial {
42 readonly cbcV10?: Buffer;
43 readonly cbcV11?: Buffer;
44 readonly cbcV11Error?: ChromiumKeyError;
45 /**
46 * AES-128-CBC from an empty passphrase. Some Linux clients wrote records
47 * with it (crbug.com/1195256), so Chromium — and this import — retry with it
48 * after a record's own key fails.
49 */
50 readonly cbcEmpty?: Buffer;
51 readonly gcmV10?: Buffer;
53​
54const derive = (passphrase: string, iterations: number) =>
55 NodeCrypto.pbkdf2Sync(passphrase, KEY_SALT, iterations, KEY_LENGTH, "sha1");
56​
57/**
58 * Via the CLI the prompt says "security" and "Always Allow" grants trust to a
59 * tool every process on the machine can invoke; in-process it names this app
60 * and the grant belongs to it.
61 *
62 * Deliberately untimed: macOS answers this with a modal, and a timeout racing
63 * the user means the prompt can be approved while nothing is left listening,
64 * which reads as "approving did nothing".
65 */
66const readKeychainSecret = Effect.fn("ChromiumKeys.readKeychainSecret")(function* (
67 service: string,
68 account: string,
69) {
70 // Only macOS cookie imports need this binding; loading it at startup can
71 // prevent the desktop from opening on platforms that never use it.
72 const Keyring = yield* Effect.tryPromise({
73 try: () => import("@napi-rs/keyring"),
74 catch: (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
75 });
76 const secret = yield* Effect.try({
77 try: () => new Keyring.Entry(service, account).getPassword(),
78 catch: (cause) => {
79 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
80 const missing = /no (matching )?entry|not found/i.test(message);
81 return new ChromiumKeyError({
82 reason: missing ? "keychainItemMissing" : "needsKeychainApproval",
83 cause,
84 });
85 },
86 });
87 if (secret === null || secret === "") {
88 return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
89 }
90 return secret;
91});
92​
93/**
94 * Its exit codes distinguish a missing key, denied access, and an unavailable
95 * keyring without parsing localized error messages.
96 */
97export const readLinuxSecret = Effect.fn("ChromiumKeys.readLinuxSecret")(function* (
98 application: string,
99) {
100 return yield* Effect.scoped(
101 Effect.gen(function* () {
102 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
103 const environment = yield* HostProcess.Environment;
104 const helper = yield* LinuxBrowserSecretPath;
105 if (helper === undefined) {
106 return yield* new ChromiumKeyError({ reason: "keychainUnavailable" });
107 }
108 const handle = yield* spawner
109 .spawn(ChildProcess.make(helper, [application], { stdin: "ignore", env: environment }))
110 .pipe(
111 Effect.mapError(
112 (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
113 ),
114 );
115 const [secret, , exitCode] = yield* Effect.all(
116 [
117 handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
118 handle.stderr.pipe(Stream.runDrain),
119 handle.exitCode,
120 ],
121 { concurrency: "unbounded" },
122 ).pipe(
123 Effect.mapError((cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause })),
124 );
125 if (Number(exitCode) !== 0) {
126 return yield* new ChromiumKeyError({
127 reason:
128 Number(exitCode) === 2
129 ? "keychainItemMissing"
130 : Number(exitCode) === 3
131 ? "needsKeychainApproval"
132 : "keychainUnavailable",
133 });
134 }
135 if (secret === "") {
136 return yield* new ChromiumKeyError({ reason: "keychainItemMissing" });
137 }
138 return secret;
139 }),
140 );
141});
142​
143const WindowsLocalState = Schema.Struct({
144 os_crypt: Schema.Struct({
145 encrypted_key: Schema.String,
146 app_bound_encrypted_key: Schema.optional(Schema.String),
147 }),
148});
149const decodeWindowsLocalState = Schema.decodeUnknownEffect(
150 Schema.fromJsonString(WindowsLocalState),
151);
152const DPAPI_PREFIX = Buffer.from("DPAPI");
153const WINDOWS_KEY_LENGTH = 32;
154const WINDOWS_DPAPI_SCRIPT =
155 "Add-Type -AssemblyName System.Security;" +
156 "$value=[Console]::In.ReadToEnd();" +
157 "$encrypted=[Convert]::FromBase64String($value);" +
158 "$plain=[Security.Cryptography.ProtectedData]::Unprotect($encrypted,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);" +
159 "[Console]::Out.Write([Convert]::ToBase64String($plain))";
160​
161export const decodeWindowsWrappedKey = Effect.fn("ChromiumKeys.decodeWindowsWrappedKey")(function* (
162 contents: string,
163) {
164 const state = yield* decodeWindowsLocalState(contents).pipe(
165 Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
166 );
167 if (state.os_crypt.app_bound_encrypted_key !== undefined) {
168 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
169 }
170 const wrapped = yield* Effect.fromResult(Base64.decode(state.os_crypt.encrypted_key)).pipe(
171 Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
172 );
173 const wrappedBuffer = Buffer.from(wrapped);
174 if (!wrappedBuffer.subarray(0, DPAPI_PREFIX.length).equals(DPAPI_PREFIX)) {
175 return yield* new ChromiumKeyError({ reason: "readFailed" });
176 }
177 return wrappedBuffer.subarray(DPAPI_PREFIX.length);
178});
179​
180export const unwrapWindowsDpapiKey = Effect.fn("ChromiumKeys.unwrapWindowsDpapiKey")(function* (
181 wrapped: Buffer,
182) {
183 const environment = yield* HostProcess.Environment;
184 return yield* Effect.scoped(
185 Effect.gen(function* () {
186 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
187 const windowsRoot = environment.SystemRoot ?? environment.WINDIR;
188 const powershell = windowsRoot
189 ? `${windowsRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
190 : "powershell.exe";
191 const handle = yield* spawner
192 .spawn(
193 ChildProcess.make(
194 powershell,
195 [
196 "-NoLogo",
197 "-NoProfile",
198 "-NonInteractive",
199 "-WindowStyle",
200 "Hidden",
201 "-Command",
202 WINDOWS_DPAPI_SCRIPT,
203 ],
204 {
205 env: environment,
206 stdin: Stream.encodeText(Stream.make(wrapped.toString("base64"))),
207 },
208 ),
209 )
210 .pipe(
211 Effect.mapError(
212 (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }),
213 ),
214 );
215 const [plainEncoded, , exitCode] = yield* Effect.all(
216 [
217 handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
218 handle.stderr.pipe(Stream.runDrain),
219 handle.exitCode,
220 ],
221 { concurrency: "unbounded" },
222 ).pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
223 if (Number(exitCode) !== 0) {
224 return yield* new ChromiumKeyError({ reason: "readFailed" });
225 }
226 const plain = yield* Effect.fromResult(Base64.decode(plainEncoded)).pipe(
227 Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })),
228 );
229 if (plain.length !== WINDOWS_KEY_LENGTH) {
230 return yield* new ChromiumKeyError({ reason: "readFailed" });
231 }
232 return Buffer.from(plain);
233 }),
234 );
235});
236​
237export const readWindowsKey = Effect.fn("ChromiumKeys.readWindowsKey")(function* (
238 localStatePath: string,
239) {
240 const fileSystem = yield* FileSystem.FileSystem;
241 const contents = yield* fileSystem
242 .readFileString(localStatePath)
243 .pipe(Effect.mapError((cause) => new ChromiumKeyError({ reason: "readFailed", cause })));
244 return yield* unwrapWindowsDpapiKey(yield* decodeWindowsWrappedKey(contents));
245});
246​
247export interface ChromiumKeyRequest {
248 readonly platform: NodeJS.Platform;
249 readonly keychainService: string | undefined;
250 readonly keychainAccount: string | undefined;
251 readonly linuxSecretApplication: string | undefined;
253​
254export const resolveChromiumKeys = Effect.fn("ChromiumKeys.resolveChromiumKeys")(function* (
255 request: ChromiumKeyRequest,
256): Effect.fn.Return<
257 ChromiumKeyMaterial,
258 ChromiumKeyError,
259 ChildProcessSpawner.ChildProcessSpawner
260> {
261 if (request.platform === "darwin") {
262 if (!request.keychainService || !request.keychainAccount) {
263 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
264 }
265 const secret = yield* readKeychainSecret(request.keychainService, request.keychainAccount);
266 return { cbcV10: derive(secret, MAC_KEY_ITERATIONS) };
267 }
268​
269 if (request.platform === "linux") {
270 // The fallback passphrase always applies to `v10` records; a keyring
271 // secret, when one is reachable, additionally unlocks `v11`.
272 const keyringSecret = request.linuxSecretApplication
273 ? yield* readLinuxSecret(request.linuxSecretApplication).pipe(
274 // v10 remains importable when Secret Service is absent or does not
275 // contain a key. An explicit denial/lock/cancel remains a consent
276 // failure rather than being silently downgraded.
277 Effect.catchIf(
278 (error) => error.reason !== "needsKeychainApproval",
279 (error) => Effect.succeed(error),
280 ),
281 )
282 : undefined;
283 return {
284 cbcV10: derive(LINUX_FALLBACK_PASSPHRASE, LINUX_KEY_ITERATIONS),
285 ...(typeof keyringSecret === "string"
286 ? { cbcV11: derive(keyringSecret, LINUX_KEY_ITERATIONS) }
287 : keyringSecret
288 ? { cbcV11Error: keyringSecret }
289 : {}),
290 cbcEmpty: derive("", LINUX_KEY_ITERATIONS),
291 };
292 }
293​
294 return yield* new ChromiumKeyError({ reason: "unsupportedPlatform" });
295});