Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import * as PlatformError from "effect/PlatformError";
9import { ChildProcessSpawner } from "effect/process";
10import { beforeEach, vi } from "vite-plus/test";
11
12import {
13 ChromiumKeyError,
14 decodeWindowsWrappedKey,
15 readLinuxSecret,
16 resolveChromiumKeys,
17 unwrapWindowsDpapiKey,
18} from "./ChromiumKeys.ts";
19import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts";
20
21const { getPassword } = vi.hoisted(() => ({ getPassword: vi.fn<() => string | null>() }));
22
23vi.mock("@napi-rs/keyring", () => ({
24 Entry: class {
25 getPassword = getPassword;
26 },
27}));
28
29beforeEach(() => {
30 getPassword.mockReset();
31});
32
33type CapturedCommand = {
34 readonly command: string;
35 readonly args: ReadonlyArray<string>;
36 readonly options: {
37 readonly stdin?: string;
38 readonly env?: Readonly<Record<string, string | undefined>>;
39 };
40};
41
42const layerHelper = (input: {
43 readonly stdout?: string;
44 readonly stderr?: string;
45 readonly stdoutStream?: Stream.Stream<Uint8Array>;
46 readonly stderrStream?: Stream.Stream<Uint8Array>;
47 readonly exitCode?: number;
48 readonly spawnError?: PlatformError.PlatformError;
49 readonly capture?: (command: CapturedCommand) => void;
50}) =>
51 Layer.merge(
52 Layer.succeed(LinuxBrowserSecretPath, "/bundled/browser-secret/t3-browser-secret"),
53 Layer.succeed(
54 ChildProcessSpawner.ChildProcessSpawner,
55 ChildProcessSpawner.make((command) =>
56 input.spawnError
57 ? Effect.fail(input.spawnError)
58 : Effect.succeed(
59 ChildProcessSpawner.makeHandle({
60 pid: ChildProcessSpawner.ProcessId(1),
61 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
62 isRunning: Effect.succeed(false),
63 kill: () => Effect.void,
64 unref: Effect.succeed(Effect.void),
65 stdin: Sink.drain,
66 stdout: input.stdoutStream ?? Stream.encodeText(Stream.make(input.stdout ?? "")),
67 stderr: input.stderrStream ?? Stream.encodeText(Stream.make(input.stderr ?? "")),
68 all: Stream.empty,
69 getInputFd: () => Sink.drain,
70 getOutputFd: () => Stream.empty,
71 }),
72 ).pipe(
73 Effect.tap(() => Effect.sync(() => input.capture?.(command as CapturedCommand))),
74 ),
75 ),
76 ),
77 );
78
79describe("macOS Chromium secrets", () => {
80 const request = {
81 platform: "darwin",
82 keychainService: "Chrome Safe Storage",
83 keychainAccount: "Chrome",
84 linuxSecretApplication: undefined,
85 } as const;
86 const layerNoProcesses = Layer.succeed(
87 ChildProcessSpawner.ChildProcessSpawner,
88 ChildProcessSpawner.make(() => Effect.die("must not spawn")),
89 );
90
91 it.effect("derives the cookie key from the keychain secret", () =>
92 Effect.gen(function* () {
93 getPassword.mockReturnValue("macos-secret");
94 const keys = yield* resolveChromiumKeys(request);
95 expect(keys.cbcV10?.toString("hex")).toBe("3df7306fb1eac353289565a2f6b64f74");
96 }).pipe(Effect.provide(layerNoProcesses)),
97 );
98
99 it.effect("preserves a denied keychain approval", () =>
100 Effect.gen(function* () {
101 const denied = new Error("User denied access");
102 getPassword.mockImplementation(() => {
103 throw denied;
104 });
105 const error = yield* resolveChromiumKeys(request).pipe(Effect.flip);
106 expect(error.reason).toBe("needsKeychainApproval");
107 expect(error.cause).toBe(denied);
108 }).pipe(Effect.provide(layerNoProcesses)),
109 );
110});
111
112describe("Linux Chromium secrets", () => {
113 it.effect("retains a missing helper failure alongside the keyring-free fallback", () =>
114 Effect.gen(function* () {
115 const keys = yield* resolveChromiumKeys({
116 platform: "linux",
117 keychainService: undefined,
118 keychainAccount: undefined,
119 linuxSecretApplication: "chromium",
120 });
121 expect(keys.cbcV10).toHaveLength(16);
122 expect(keys.cbcV11).toBeUndefined();
123 expect(keys.cbcV11Error?.reason).toBe("keychainUnavailable");
124 }).pipe(
125 Effect.provide(
126 layerHelper({
127 spawnError: PlatformError.systemError({
128 _tag: "NotFound",
129 module: "ChildProcess",
130 method: "spawn",
131 }),
132 }),
133 ),
134 ),
135 );
136
137 it.effect("reports an unconfigured helper without searching PATH", () =>
138 readLinuxSecret("chromium").pipe(
139 Effect.flip,
140 Effect.tap((error) => Effect.sync(() => expect(error.reason).toBe("keychainUnavailable"))),
141 Effect.provideService(
142 ChildProcessSpawner.ChildProcessSpawner,
143 ChildProcessSpawner.make(() => Effect.die("must not spawn")),
144 ),
145 Effect.provideService(LinuxBrowserSecretPath, undefined),
146 ),
147 );
148
149 it.effect("preserves trailing whitespace in the stored secret", () =>
150 Effect.gen(function* () {
151 const secret = yield* readLinuxSecret("chrome");
152 expect(secret).toBe("linux-secret \t\n");
153 }).pipe(Effect.provide(layerHelper({ stdout: "linux-secret \t\n" }))),
154 );
155
156 it.effect("drains stdout and stderr concurrently", () =>
157 Effect.gen(function* () {
158 const stderrDrainStarted = yield* Deferred.make<void>();
159 const stdout = Stream.fromEffect(Deferred.await(stderrDrainStarted)).pipe(
160 Stream.flatMap(() => Stream.encodeText(Stream.make("linux-secret"))),
161 );
162 const stderr = Stream.fromEffect(Deferred.succeed(stderrDrainStarted, undefined)).pipe(
163 Stream.drain,
164 );
165
166 const secret = yield* readLinuxSecret("chrome").pipe(
167 Effect.provide(layerHelper({ stdoutStream: stdout, stderrStream: stderr })),
168 );
169
170 expect(secret).toBe("linux-secret");
171 }),
172 );
173
174 it.effect(
175 "preserves the desktop environment and identifies denial without parsing stderr",
176 () => {
177 let captured: CapturedCommand | undefined;
178 return Effect.gen(function* () {
179 const error = yield* readLinuxSecret("brave").pipe(Effect.flip);
180 expect(error).toBeInstanceOf(ChromiumKeyError);
181 expect(error.reason).toBe("needsKeychainApproval");
182 expect(captured?.options.env?.LC_ALL).toBe("localized");
183 expect(captured?.options.env?.PATH).toBe("/synthetic/bin");
184 expect(captured?.options.env?.SESSION_MARKER).toBe("kept");
185 }).pipe(
186 Effect.provide(
187 layerHelper({
188 stderr: "Zugriff verweigert",
189 exitCode: 3,
190 capture: (value) => (captured = value),
191 }),
192 ),
193 Effect.provideService(HostProcess.Environment, {
194 PATH: "/synthetic/bin",
195 SESSION_MARKER: "kept",
196 LC_ALL: "localized",
197 }),
198 );
199 },
200 );
201});
202
203describe("Windows Chromium secrets", () => {
204 it.effect("accepts only DPAPI-wrapped non-app-bound keys", () =>
205 Effect.gen(function* () {
206 const wrapped = Buffer.from("wrapped-key");
207 const encoded = Buffer.concat([Buffer.from("DPAPI"), wrapped]).toString("base64");
208 const localState = `{"os_crypt":{"encrypted_key":"${encoded}"}}`;
209 expect(yield* decodeWindowsWrappedKey(localState)).toEqual(wrapped);
210
211 const appBound = yield* decodeWindowsWrappedKey(
212 `{"os_crypt":{"encrypted_key":"${encoded}","app_bound_encrypted_key":"present"}}`,
213 ).pipe(Effect.flip);
214 expect(appBound.reason).toBe("unsupportedPlatform");
215
216 const malformed = yield* decodeWindowsWrappedKey(
217 `{"os_crypt":{"encrypted_key":"${wrapped.toString("base64")}"}}`,
218 ).pipe(Effect.flip);
219 expect(malformed.reason).toBe("readFailed");
220 }),
221 );
222
223 it.effect("unwraps the binary key through PowerShell without placing it in argv", () => {
224 let captured: CapturedCommand | undefined;
225 const wrapped = Buffer.from("wrapped-key");
226 const key = Buffer.from("0123456789abcdef0123456789abcdef");
227 return Effect.gen(function* () {
228 expect(yield* unwrapWindowsDpapiKey(wrapped)).toEqual(key);
229 expect(captured?.command).toBe(
230 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
231 );
232 expect(captured?.args).toContain("-NonInteractive");
233 expect(captured?.args.join(" ")).not.toContain(wrapped.toString("base64"));
234 }).pipe(
235 Effect.provide(
236 layerHelper({ stdout: key.toString("base64"), capture: (value) => (captured = value) }),
237 ),
238 Effect.provideService(HostProcess.Environment, { SystemRoot: "C:\\Windows" }),
239 );
240 });
241});