Open History to see the last commit
1import type {
2 BrowserImportInput,
3 BrowserImportResult,
4 BrowserImportSource,
5 BrowserImportUnavailableReason,
6} from "@t3tools/contracts";
7import { BrowserImportFailureReason } from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import type { Session } from "electron";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15import * as Scope from "effect/Scope";
16import { ChildProcessSpawner } from "effect/process";
17
18import * as HostProcess from "@t3tools/shared/HostProcess";
19
20import * as BrowserSession from "../BrowserSession.ts";
21import { ChromiumCookieReadError, readChromiumCookies } from "./ChromiumCookies.ts";
22import type { CookieReadResult } from "./CookieDatabase.ts";
23import { FirefoxCookieReadError, readFirefoxCookies } from "./FirefoxCookies.ts";
24import { readSafariCookies, safariAccessDenied, SafariCookieReadError } from "./SafariCookies.ts";
25import {
26 BROWSER_IMPORT_SOURCES,
27 resolveCookieDatabase,
28 isSourceInstalled,
29 isSourceRunning,
30 listSourceProfiles,
31 sourcePathContext,
32 type BrowserImportPathContext,
33 type BrowserImportSourceDefinition,
34} from "./Sources.ts";
35
36export class BrowserImportFailedError extends Schema.TaggedError<BrowserImportFailedError>()(
37 "BrowserImportFailedError",
38 {
39 sourceId: Schema.String,
40 reason: BrowserImportFailureReason,
41 cause: Schema.optional(Schema.Defect()),
42 },
43) {
44 // The reason token is part of the message on purpose: IPC flattens the error
45 // to its message, and the renderer maps that token back to user-facing copy.
46 override get message(): string {
47 return `Importing cookies from ${this.sourceId} failed: ${this.reason}.`;
48 }
49}
50
51export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
52 "BrowserCookieWriteError",
53 {
54 url: Schema.String,
55 name: Schema.String,
56 cause: Schema.Defect(),
57 },
58) {
59 override get message(): string {
60 return `Could not write imported cookie ${this.name} for ${this.url}.`;
61 }
62}
63
64export class BrowserImport extends Context.Service<
65 BrowserImport,
66 {
67 readonly listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>>;
68 readonly importCookies: (input: {
69 readonly input: BrowserImportInput;
70 readonly scope: string;
71 readonly persistent: boolean;
72 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
73 }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
74 }
75>()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
76
77const unavailableReason = Effect.fn("BrowserImport.unavailableReason")(function* (
78 definition: BrowserImportSourceDefinition,
79 context: BrowserImportPathContext,
80): Effect.fn.Return<
81 BrowserImportUnavailableReason | undefined,
82 never,
83 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
84> {
85 if (!definition.platforms.includes(context.platform)) return "unsupportedPlatform";
86 if (!(yield* isSourceInstalled(definition, context))) return "notInstalled";
87 if (yield* isSourceRunning(definition, context)) return "browserRunning";
88 // Safari's jar is found by `stat`, which TCC permits without Full Disk Access
89 // — so a Safari that lists as ready may still refuse the read.
90 if (definition.engine === "safari") {
91 const jar = yield* resolveCookieDatabase(definition, context, ".");
92 if (jar !== undefined && (yield* safariAccessDenied(jar))) return "needsFullDiskAccess";
93 }
94 return undefined;
95});
96
97const cookieHost = (url: string): string => {
98 try {
99 return new URL(url).hostname;
100 } catch {
101 return url;
102 }
103};
104
105export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
106 session: { readonly cookies: Pick<Session["cookies"], "set" | "flushStore"> },
107 read: CookieReadResult,
108) {
109 let imported = 0;
110 let skipped = read.undecryptable;
111 const skippedDomains = new Set(read.undecryptableHosts);
112 for (const cookie of read.cookies) {
113 const written = yield* Effect.tryPromise({
114 try: () =>
115 session.cookies.set({
116 url: cookie.url,
117 name: cookie.name,
118 value: cookie.value,
119 // Omitted for host-only cookies: Electron reads any `domain` as a
120 // domain cookie and re-adds the leading dot, widening its scope.
121 ...(cookie.domain === undefined ? {} : { domain: cookie.domain }),
122 path: cookie.path,
123 secure: cookie.secure,
124 httpOnly: cookie.httpOnly,
125 sameSite: cookie.sameSite,
126 ...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
127 }),
128 catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }),
129 }).pipe(
130 Effect.as(true),
131 Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
132 Effect.catchTags({ BrowserCookieWriteError: () => Effect.succeed(false) }),
133 );
134 if (written) {
135 imported += 1;
136 } else {
137 skipped += 1;
138 skippedDomains.add(cookieHost(cookie.url));
139 }
140 }
141 // `set` resolves once the cookie is in memory; Chromium writes the store to
142 // disk on its own schedule. Flush before reporting "Done", so a crash right
143 // after does not lose what the user was just told was imported.
144 if (imported > 0) {
145 yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
146 Effect.tapError((error) =>
147 Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
148 ),
149 Effect.ignore,
150 );
151 }
152 return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) };
153});
154
155/** @public Service construction is part of the canonical Effect module API. */
156export const make = Effect.gen(function* BrowserImportMake() {
157 const browserSession = yield* BrowserSession.BrowserSession;
158 const platform = yield* HostProcess.Platform;
159 const executablePath = yield* HostProcess.ExecutablePath;
160 const platformServices = yield* Effect.context<
161 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
162 >();
163 const pathContext = yield* sourcePathContext;
164
165 const listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>> = Effect.forEach(
166 BROWSER_IMPORT_SOURCES,
167 Effect.fnUntraced(function* (definition) {
168 const unavailable = yield* unavailableReason(definition, pathContext);
169 return {
170 id: definition.id,
171 name: definition.name,
172 profiles:
173 unavailable === undefined ? yield* listSourceProfiles(definition, pathContext) : [],
174 ...(unavailable === undefined ? {} : { unavailable }),
175 } satisfies BrowserImportSource;
176 }),
177 ).pipe(Effect.provide(platformServices));
178
179 const importCookies = Effect.fn("BrowserImport.importCookies")(function* (input: {
180 readonly input: BrowserImportInput;
181 readonly scope: string;
182 readonly persistent: boolean;
183 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
184 }) {
185 const definition = BROWSER_IMPORT_SOURCES.find(
186 (candidate) => candidate.id === input.input.sourceId,
187 );
188 if (!definition) {
189 return yield* new BrowserImportFailedError({
190 sourceId: input.input.sourceId,
191 reason: "unknownSource",
192 });
193 }
194
195 const blocked = yield* unavailableReason(definition, pathContext).pipe(
196 Effect.provide(platformServices),
197 );
198 if (blocked !== undefined) {
199 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: blocked });
200 }
201
202 if (platform === "darwin" && definition.engine === "chromium") {
203 // macOS attributes the Keychain prompt and the resulting ACL grant to the
204 // executable that asks, so record which one that was — in a packaged build
205 // it is the signed app, in dev whatever binary hosts the main process.
206 yield* Effect.logInfo("Reading browser cookie key from the keychain", {
207 sourceId: definition.id,
208 executablePath,
209 });
210 }
211
212 // The profile directory arrives over IPC, so it is only honoured when the
213 // source itself reported it. Forwarding it unchecked would let `..`
214 // segments walk out of the browser's user-data directory and read any
215 // cookie database reachable on disk.
216 const sourceProfiles = yield* listSourceProfiles(definition, pathContext).pipe(
217 Effect.provide(platformServices),
218 );
219 const requestedProfile = sourceProfiles.find(
220 (profile) => profile.directory === input.input.sourceProfileDirectory,
221 );
222 if (requestedProfile === undefined) {
223 return yield* new BrowserImportFailedError({
224 sourceId: definition.id,
225 reason: "unknownSourceProfile",
226 });
227 }
228
229 // The profile was listed against a database moments ago; resolve it again
230 // rather than assume a path, since a Chromium jar may sit under `Network/`.
231 const databasePath = yield* resolveCookieDatabase(
232 definition,
233 pathContext,
234 requestedProfile.directory,
235 ).pipe(Effect.provide(platformServices));
236 if (databasePath === undefined) {
237 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed" });
238 }
239
240 const userDataDirectory = definition.userDataDirectory(pathContext);
241 const read: Effect.Effect<
242 CookieReadResult,
243 ChromiumCookieReadError | FirefoxCookieReadError | SafariCookieReadError,
244 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
245 > =
246 definition.engine === "safari"
247 ? readSafariCookies(databasePath).pipe(
248 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
249 )
250 : definition.engine === "firefox"
251 ? readFirefoxCookies(databasePath).pipe(
252 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
253 )
254 : readChromiumCookies({
255 cookieDatabasePath: databasePath,
256 keychainService: definition.keychainService,
257 keychainAccount: definition.keychainAccount,
258 linuxSecretApplication: definition.linuxSecretApplication,
259 ...(platform === "win32" && userDataDirectory !== undefined
260 ? {
261 windowsLocalStatePath: pathContext.path.join(userDataDirectory, "Local State"),
262 }
263 : {}),
264 platform,
265 });
266
267 const result = yield* read.pipe(
268 Effect.scoped,
269 Effect.provide(platformServices),
270 Effect.catchTags({
271 ChromiumCookieReadError: (cause) =>
272 Effect.fail(
273 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
274 ),
275 FirefoxCookieReadError: (cause) =>
276 Effect.fail(
277 new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed", cause }),
278 ),
279 SafariCookieReadError: (cause) =>
280 Effect.fail(
281 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
282 ),
283 }),
284 );
285
286 const session = yield* browserSession
287 .getSession(input.scope, input.persistent, input.namespace)
288 .pipe(
289 Effect.mapError(
290 (cause) =>
291 new BrowserImportFailedError({
292 sourceId: definition.id,
293 reason: "sessionUnavailable",
294 cause,
295 }),
296 ),
297 );
298
299 // Written one at a time rather than in parallel: Chromium's cookie store
300 // serialises writes anyway, and a rejected cookie should only cost itself.
301 return yield* writeCookies(session, result);
302 });
303
304 return BrowserImport.of({ listSources, importCookies });
305});
306
307export const layer = Layer.effect(BrowserImport, make);