@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 355 lines 13 KB
Raw
1 import type {
2 BrowserImportInput,
3 BrowserImportResult,
4 BrowserImportSource,
5 BrowserImportUnavailableReason,
6 } from "@t3tools/contracts";
7 import {
8 BrowserImportFailureReason,
9 type ManagedPolicyDocument,
10 managedPolicyDeniedMessage,
11 } from "@t3tools/contracts";
12 import * as Context from "effect/Context";
13 import type { Session } from "electron";
14 import * as Effect from "effect/Effect";
15 import * as FileSystem from "effect/FileSystem";
16 import * as Layer from "effect/Layer";
17 import * as Path from "effect/Path";
18 import * as Schema from "effect/Schema";
19 import * as Scope from "effect/Scope";
20 import { ChildProcessSpawner } from "effect/process";
21
22 import * as HostProcess from "@t3tools/shared/HostProcess";
23 import type { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
24
25 import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
26 import * as BrowserSession from "../BrowserSession.ts";
27 import { ChromiumCookieReadError, readChromiumCookies } from "./ChromiumCookies.ts";
28 import type { CookieReadResult } from "./CookieDatabase.ts";
29 import { FirefoxCookieReadError, readFirefoxCookies } from "./FirefoxCookies.ts";
30 import { readSafariCookies, safariAccessDenied, SafariCookieReadError } from "./SafariCookies.ts";
31 import {
32 BROWSER_IMPORT_SOURCES,
33 resolveCookieDatabase,
34 isSourceInstalled,
35 isSourceRunning,
36 listSourceProfiles,
37 sourcePathContext,
38 type BrowserImportPathContext,
39 type BrowserImportSourceDefinition,
40 } from "./Sources.ts";
41
42 export class BrowserImportFailedError extends Schema.TaggedError<BrowserImportFailedError>()(
43 "BrowserImportFailedError",
44 {
45 sourceId: Schema.String,
46 reason: BrowserImportFailureReason,
47 cause: Schema.optional(Schema.Defect()),
48 },
49 ) {
50 // IPC preserves only the message; the renderer needs its reason token for user-facing copy.
51 override get message(): string {
52 return `Importing cookies from ${this.sourceId} failed: ${this.reason}.`;
53 }
54 }
55
56 /** An administrator's policy forbids the import, or the policy file could not be checked. */
57 export class BrowserImportPolicyError extends Schema.TaggedError<BrowserImportPolicyError>()(
58 "BrowserImportPolicyError",
59 {
60 policyPath: Schema.String,
61 /** Absent when the policy could not be read or decoded. */
62 organization: Schema.optional(Schema.String),
63 cause: Schema.optional(Schema.Defect()),
64 },
65 ) {
66 override get message(): string {
67 return this.organization === undefined
68 ? `The managed policy at ${this.policyPath} could not be read, so importing browser cookies is not allowed.`
69 : managedPolicyDeniedMessage(this.organization, "importing browser cookies");
70 }
71 }
72
73 /**
74 * A policy that cannot be read or decoded denies the import: cookies are credentials, and the
75 * server refuses to start on the same policy anyway.
76 */
77 export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(function* <R>(
78 readPolicy: Effect.Effect<
79 { readonly source: string; readonly document: ManagedPolicyDocument } | undefined,
80 ManagedPolicyFileError,
81 R
82 >,
83 ) {
84 const policy = yield* readPolicy.pipe(
85 Effect.mapError((cause) => new BrowserImportPolicyError({ policyPath: cause.path, cause })),
86 );
87 if (policy?.document.limits?.browserCookieImport === false) {
88 return yield* new BrowserImportPolicyError({
89 policyPath: policy.source,
90 organization: policy.document.organization,
91 });
92 }
93 });
94
95 class BrowserCookieFlushError extends Schema.TaggedError<BrowserCookieFlushError>()(
96 "BrowserCookieFlushError",
97 { cause: Schema.Defect() },
98 ) {
99 override get message(): string {
100 return "Imported cookies could not be flushed to disk.";
101 }
102 }
103
104 export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
105 "BrowserCookieWriteError",
106 {
107 url: Schema.String,
108 cookieName: Schema.String,
109 cause: Schema.Defect(),
110 },
111 ) {
112 override get message(): string {
113 return `Could not write imported cookie ${this.cookieName} for ${this.url}.`;
114 }
115 }
116
117 export class BrowserImport extends Context.Service<
118 BrowserImport,
119 {
120 readonly listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>>;
121 readonly importCookies: (input: {
122 readonly input: BrowserImportInput;
123 readonly scope: string;
124 readonly persistent: boolean;
125 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
126 }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError | BrowserImportPolicyError>;
127 }
128 >()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
129
130 const unavailableReason = Effect.fn("BrowserImport.unavailableReason")(function* (
131 definition: BrowserImportSourceDefinition,
132 context: BrowserImportPathContext,
133 ): Effect.fn.Return<
134 BrowserImportUnavailableReason | undefined,
135 never,
136 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
137 > {
138 if (!definition.platforms.includes(context.platform)) return "unsupportedPlatform";
139 if (!(yield* isSourceInstalled(definition, context))) return "notInstalled";
140 if (yield* isSourceRunning(definition, context)) return "browserRunning";
141 // TCC permits stat without Full Disk Access, so a listed Safari jar may still be unreadable.
142 if (definition.engine === "safari") {
143 const jar = yield* resolveCookieDatabase(definition, context, ".");
144 if (jar !== undefined && (yield* safariAccessDenied(jar))) return "needsFullDiskAccess";
145 }
146 return undefined;
147 });
148
149 const cookieHost = (url: string): string => {
150 try {
151 return new URL(url).hostname;
152 } catch {
153 return url;
154 }
155 };
156
157 export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
158 session: { readonly cookies: Pick<Session["cookies"], "set" | "flushStore"> },
159 read: CookieReadResult,
160 ) {
161 let imported = 0;
162 let skipped = read.undecryptable;
163 const skippedDomains = new Set(read.undecryptableHosts);
164 for (const cookie of read.cookies) {
165 const written = yield* Effect.tryPromise({
166 try: () =>
167 session.cookies.set({
168 url: cookie.url,
169 name: cookie.name,
170 value: cookie.value,
171 // Electron widens any supplied domain; omit it for host-only cookies.
172 ...(cookie.domain === undefined ? {} : { domain: cookie.domain }),
173 path: cookie.path,
174 secure: cookie.secure,
175 httpOnly: cookie.httpOnly,
176 sameSite: cookie.sameSite,
177 ...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
178 }),
179 catch: (cause) =>
180 new BrowserCookieWriteError({ url: cookie.url, cookieName: cookie.name, cause }),
181 }).pipe(
182 Effect.as(true),
183 Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
184 Effect.catchTags({ BrowserCookieWriteError: () => Effect.succeed(false) }),
185 );
186 if (written) {
187 imported += 1;
188 } else {
189 skipped += 1;
190 skippedDomains.add(cookieHost(cookie.url));
191 }
192 }
193 // Cookie writes settle in memory; flush to disk before reporting a durable import.
194 if (imported > 0) {
195 yield* Effect.tryPromise({
196 try: () => session.cookies.flushStore(),
197 catch: (cause) => new BrowserCookieFlushError({ cause }),
198 }).pipe(
199 Effect.tapError((error) =>
200 Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
201 ),
202 Effect.ignore,
203 );
204 }
205 return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) };
206 });
207
208 /** @public */
209 export const make = Effect.gen(function* BrowserImportMake() {
210 const browserSession = yield* BrowserSession.BrowserSession;
211 const managedPolicy = yield* DesktopManagedPolicy.DesktopManagedPolicy;
212 const platform = yield* HostProcess.Platform;
213 const executablePath = yield* HostProcess.ExecutablePath;
214 const platformServices = yield* Effect.context<
215 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
216 >();
217 const pathContext = yield* sourcePathContext;
218
219 const listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>> = Effect.forEach(
220 BROWSER_IMPORT_SOURCES,
221 Effect.fnUntraced(function* (definition) {
222 const unavailable = yield* unavailableReason(definition, pathContext);
223 return {
224 id: definition.id,
225 name: definition.name,
226 profiles:
227 unavailable === undefined ? yield* listSourceProfiles(definition, pathContext) : [],
228 ...(unavailable === undefined ? {} : { unavailable }),
229 } satisfies BrowserImportSource;
230 }),
231 ).pipe(Effect.provide(platformServices));
232
233 const importCookies = Effect.fn("BrowserImport.importCookies")(function* (input: {
234 readonly input: BrowserImportInput;
235 readonly scope: string;
236 readonly persistent: boolean;
237 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
238 }) {
239 yield* checkBrowserImportPolicy(managedPolicy.read);
240 const definition = BROWSER_IMPORT_SOURCES.find(
241 (candidate) => candidate.id === input.input.sourceId,
242 );
243 if (!definition) {
244 return yield* new BrowserImportFailedError({
245 sourceId: input.input.sourceId,
246 reason: "unknownSource",
247 });
248 }
249
250 const blocked = yield* unavailableReason(definition, pathContext).pipe(
251 Effect.provide(platformServices),
252 );
253 if (blocked !== undefined) {
254 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: blocked });
255 }
256
257 if (platform === "darwin" && definition.engine === "chromium") {
258 // macOS attributes Keychain prompts and ACL grants to the executable, which differs in dev and packaged builds.
259 yield* Effect.logInfo("Reading browser cookie key from the keychain", {
260 sourceId: definition.id,
261 executablePath,
262 });
263 }
264
265 // IPC profile paths must match the source's listing to prevent traversal outside browser user-data.
266 const sourceProfiles = yield* listSourceProfiles(definition, pathContext).pipe(
267 Effect.provide(platformServices),
268 );
269 const requestedProfile = sourceProfiles.find(
270 (profile) => profile.directory === input.input.sourceProfileDirectory,
271 );
272 if (requestedProfile === undefined) {
273 return yield* new BrowserImportFailedError({
274 sourceId: definition.id,
275 reason: "unknownSourceProfile",
276 });
277 }
278
279 // Re-resolve listed paths because Chromium jars may be under Network/.
280 const databasePath = yield* resolveCookieDatabase(
281 definition,
282 pathContext,
283 requestedProfile.directory,
284 ).pipe(Effect.provide(platformServices));
285 if (databasePath === undefined) {
286 return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed" });
287 }
288
289 const userDataDirectory = definition.userDataDirectory(pathContext);
290 const read: Effect.Effect<
291 CookieReadResult,
292 ChromiumCookieReadError | FirefoxCookieReadError | SafariCookieReadError,
293 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
294 > =
295 definition.engine === "safari"
296 ? readSafariCookies(databasePath).pipe(
297 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
298 )
299 : definition.engine === "firefox"
300 ? readFirefoxCookies(databasePath).pipe(
301 Effect.map((cookies) => ({ cookies, undecryptable: 0, undecryptableHosts: [] })),
302 )
303 : readChromiumCookies({
304 cookieDatabasePath: databasePath,
305 keychainService: definition.keychainService,
306 keychainAccount: definition.keychainAccount,
307 linuxSecretApplication: definition.linuxSecretApplication,
308 ...(platform === "win32" && userDataDirectory !== undefined
309 ? {
310 windowsLocalStatePath: pathContext.path.join(userDataDirectory, "Local State"),
311 }
312 : {}),
313 platform,
314 });
315
316 const result = yield* read.pipe(
317 Effect.scoped,
318 Effect.provide(platformServices),
319 Effect.catchTags({
320 ChromiumCookieReadError: (cause) =>
321 Effect.fail(
322 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
323 ),
324 FirefoxCookieReadError: (cause) =>
325 Effect.fail(
326 new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed", cause }),
327 ),
328 SafariCookieReadError: (cause) =>
329 Effect.fail(
330 new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
331 ),
332 }),
333 );
334
335 const session = yield* browserSession
336 .getSession(input.scope, input.persistent, input.namespace)
337 .pipe(
338 Effect.mapError(
339 (cause) =>
340 new BrowserImportFailedError({
341 sourceId: definition.id,
342 reason: "sessionUnavailable",
343 cause,
344 }),
345 ),
346 );
347
348 // Chromium serializes writes; a rejected cookie should not prevent the others.
349 return yield* writeCookies(session, result);
350 });
351
352 return BrowserImport.of({ listSources, importCookies });
353 });
354
355 export const layer = Layer.effect(BrowserImport, make);