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

BrowserImport.ts

295 lines10.8 KB

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 // IPC preserves only the message; the renderer needs its reason token for user-facing copy.
45 override get message(): string {
46 return `Importing cookies from ${this.sourceId} failed: ${this.reason}.`;
47 }
49​
50export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
51 "BrowserCookieWriteError",
52 {
53 url: Schema.String,
54 name: Schema.String,
55 cause: Schema.Defect(),
56 },
57) {
58 override get message(): string {
59 return `Could not write imported cookie ${this.name} for ${this.url}.`;
60 }
62​
63export class BrowserImport extends Context.Service<
64 BrowserImport,
65 {
66 readonly listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>>;
67 readonly importCookies: (input: {
68 readonly input: BrowserImportInput;
69 readonly scope: string;
70 readonly persistent: boolean;
71 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
72 }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
73 }
74>()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
75​
76const unavailableReason = Effect.fn("BrowserImport.unavailableReason")(function* (
77 definition: BrowserImportSourceDefinition,
78 context: BrowserImportPathContext,
79): Effect.fn.Return<
80 BrowserImportUnavailableReason | undefined,
81 never,
82 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
83> {
84 if (!definition.platforms.includes(context.platform)) return "unsupportedPlatform";
85 if (!(yield* isSourceInstalled(definition, context))) return "notInstalled";
86 if (yield* isSourceRunning(definition, context)) return "browserRunning";
87 // TCC permits stat without Full Disk Access, so a listed Safari jar may still be unreadable.
88 if (definition.engine === "safari") {
89 const jar = yield* resolveCookieDatabase(definition, context, ".");
90 if (jar !== undefined && (yield* safariAccessDenied(jar))) return "needsFullDiskAccess";
91 }
92 return undefined;
93});
94​
95const cookieHost = (url: string): string => {
96 try {
97 return new URL(url).hostname;
98 } catch {
99 return url;
100 }
101};
102​
103export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
104 session: { readonly cookies: Pick<Session["cookies"], "set" | "flushStore"> },
105 read: CookieReadResult,
106) {
107 let imported = 0;
108 let skipped = read.undecryptable;
109 const skippedDomains = new Set(read.undecryptableHosts);
110 for (const cookie of read.cookies) {
111 const written = yield* Effect.tryPromise({
112 try: () =>
113 session.cookies.set({
114 url: cookie.url,
115 name: cookie.name,
116 value: cookie.value,
117 // Electron widens any supplied domain; omit it for host-only cookies.
118 ...(cookie.domain === undefined ? {} : { domain: cookie.domain }),
119 path: cookie.path,
120 secure: cookie.secure,
121 httpOnly: cookie.httpOnly,
122 sameSite: cookie.sameSite,
123 ...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
124 }),
125 catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }),
126 }).pipe(
127 Effect.as(true),
128 Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
129 Effect.catchTags({ BrowserCookieWriteError: () => Effect.succeed(false) }),
130 );
131 if (written) {
132 imported += 1;
133 } else {
134 skipped += 1;
135 skippedDomains.add(cookieHost(cookie.url));
136 }
137 }
138 // Cookie writes settle in memory; flush to disk before reporting a durable import.
139 if (imported > 0) {
140 yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
141 Effect.tapError((error) =>
142 Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
143 ),
144 Effect.ignore,
145 );
146 }
147 return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) };
148});
149​
150/** @public */
151export const make = Effect.gen(function* BrowserImportMake() {
152 const browserSession = yield* BrowserSession.BrowserSession;
153 const platform = yield* HostProcess.Platform;
154 const executablePath = yield* HostProcess.ExecutablePath;
155 const platformServices = yield* Effect.context<
156 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
157 >();
158 const pathContext = yield* sourcePathContext;
159​
160 const listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>> = Effect.forEach(
161 BROWSER_IMPORT_SOURCES,
162 Effect.fnUntraced(function* (definition) {
163 const unavailable = yield* unavailableReason(definition, pathContext);
164 return {
165 id: definition.id,
166 name: definition.name,
167 profiles:
168 unavailable === undefined ? yield* listSourceProfiles(definition, pathContext) : [],
169 ...(unavailable === undefined ? {} : { unavailable }),
170 } satisfies BrowserImportSource;
171 }),
172 ).pipe(Effect.provide(platformServices));
173​
174 const importCookies = Effect.fn("BrowserImport.importCookies")(function* (input: {
175 readonly input: BrowserImportInput;
176 readonly scope: string;
177 readonly persistent: boolean;
178 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
179 }) {
180 const definition = BROWSER_IMPORT_SOURCES.find(
181 (candidate) => candidate.id === input.input.sourceId,
182 );
183 if (!definition) {
184 return yield* new BrowserImportFailedError({
185 sourceId: input.input.sourceId,
186 reason: "unknownSource",
187 });
188 }
189​
190 const blocked = yield* unavailableReason(definition, pathContext).pipe(
191 Effect.provide(platformServices),
192 );
193 if (blocked !== undefined) {
194 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: blocked });
195 }
196​
197 if (platform === "darwin" && definition.engine === "chromium") {
198 // macOS attributes Keychain prompts and ACL grants to the executable, which differs in dev and packaged builds.
199 yield* Effect.logInfo("Reading browser cookie key from the keychain", {
200 sourceId: definition.id,
201 executablePath,
202 });
203 }
204​
205 // IPC profile paths must match the source's listing to prevent traversal outside browser user-data.
206 const sourceProfiles = yield* listSourceProfiles(definition, pathContext).pipe(
207 Effect.provide(platformServices),
208 );
209 const requestedProfile = sourceProfiles.find(
210 (profile) => profile.directory === input.input.sourceProfileDirectory,
211 );
212 if (requestedProfile === undefined) {
213 return yield* new BrowserImportFailedError({
214 sourceId: definition.id,
215 reason: "unknownSourceProfile",
216 });
217 }
218​
219 // Re-resolve listed paths because Chromium jars may be under Network/.
220 const databasePath = yield* resolveCookieDatabase(
221 definition,
222 pathContext,
223 requestedProfile.directory,
224 ).pipe(Effect.provide(platformServices));
225 if (databasePath === undefined) {
226 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed" });
227 }
228​
229 const userDataDirectory = definition.userDataDirectory(pathContext);
230 const read: Effect.Effect<
231 CookieReadResult,
232 ChromiumCookieReadError | FirefoxCookieReadError | SafariCookieReadError,
233 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
234 > =
235 definition.engine === "safari"
236 ? readSafariCookies(databasePath).pipe(
237 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
238 )
239 : definition.engine === "firefox"
240 ? readFirefoxCookies(databasePath).pipe(
241 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
242 )
243 : readChromiumCookies({
244 cookieDatabasePath: databasePath,
245 keychainService: definition.keychainService,
246 keychainAccount: definition.keychainAccount,
247 linuxSecretApplication: definition.linuxSecretApplication,
248 ...(platform === "win32" && userDataDirectory !== undefined
249 ? {
250 windowsLocalStatePath: pathContext.path.join(userDataDirectory, "Local State"),
251 }
252 : {}),
253 platform,
254 });
255​
256 const result = yield* read.pipe(
257 Effect.scoped,
258 Effect.provide(platformServices),
259 Effect.catchTags({
260 ChromiumCookieReadError: (cause) =>
261 Effect.fail(
262 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
263 ),
264 FirefoxCookieReadError: (cause) =>
265 Effect.fail(
266 new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed", cause }),
267 ),
268 SafariCookieReadError: (cause) =>
269 Effect.fail(
270 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
271 ),
272 }),
273 );
274​
275 const session = yield* browserSession
276 .getSession(input.scope, input.persistent, input.namespace)
277 .pipe(
278 Effect.mapError(
279 (cause) =>
280 new BrowserImportFailedError({
281 sourceId: definition.id,
282 reason: "sessionUnavailable",
283 cause,
284 }),
285 ),
286 );
287​
288 // Chromium serializes writes; a rejected cookie should not prevent the others.
289 return yield* writeCookies(session, result);
290 });
291​
292 return BrowserImport.of({ listSources, importCookies });
293});
294​
295export const layer = Layer.effect(BrowserImport, make);