feat(desktop): import browser cookies into a profile (#7255)

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5 authored and GitHub committed 2026-09-03 16:30:20 -07:00
1 parent e01c153c18
commit 39449e53e3
27 files changed
+3913 -183

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@effect/platform-node": "catalog:",
"@napi-rs/keyring": "^1.3.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
@@ -103,4 +103,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
yield* ipc.handle(PreviewIpc.listBrowserImportSources);
yield* ipc.handle(PreviewIpc.importBrowserCookies);
});
+2
View File
@@ -64,6 +64,8 @@ export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_IMPORT_SOURCES_CHANNEL = "desktop:preview-import-sources";
export const PREVIEW_IMPORT_COOKIES_CHANNEL = "desktop:preview-import-cookies";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
@@ -12,6 +12,7 @@ import * as Schema from "effect/Schema";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as PreviewManager from "../../preview/Manager.ts";
import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
import * as PreviewIpc from "./preview.ts";
const { fromPartition } = vi.hoisted(() => ({
@@ -80,6 +81,38 @@ describe("preview IPC methods", () => {
});
});
effectIt.effect("targets imports at the same partition tuple as the renderer", () => {
const received: Array<Parameters<BrowserImport.BrowserImport["Service"]["importCookies"]>[0]> =
[];
const browserImport = BrowserImport.BrowserImport.of({
listSources: Effect.succeed([]),
importCookies: (input) =>
Effect.sync(() => {
received.push(input);
return { imported: 0, skipped: 0, skippedDomains: [] };
}),
});
const request = (environmentId: string, targetProfileId: string) =>
PreviewIpc.importBrowserCookies.handler({
environmentId,
sourceId: "helium",
sourceProfileDirectory: "Default",
targetProfileId,
});
return Effect.gen(function* () {
yield* request("a", "b");
yield* request("a::b", DEFAULT_BROWSER_PROFILE_ID);
expect(received[0]).toMatchObject(PreviewIpc.resolvePartitionScope("a", "b"));
expect(received[1]).toMatchObject(
PreviewIpc.resolvePartitionScope("a::b", DEFAULT_BROWSER_PROFILE_ID),
);
expect(received[0]?.namespace).toBe("profile");
expect(received[1]?.namespace).toBeUndefined();
}).pipe(Effect.provideService(BrowserImport.BrowserImport, browserImport));
});
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
Effect.map(
PreviewIpc.registerWebview
+43
View File
@@ -16,7 +16,10 @@ import {
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetAudioMutedInputSchema,
DesktopPreviewSetColorSchemeInputSchema,
BrowserImportResult,
BrowserImportSource,
DesktopPreviewClearDataInputSchema,
DesktopPreviewImportCookiesInputSchema,
DesktopPreviewCreateTabInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
@@ -30,6 +33,7 @@ import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
@@ -284,6 +288,45 @@ export const getPreviewConfig = DesktopIpc.makeIpcMethod({
}),
});
/**
* Registered separately from `methods`: these carry `BrowserImport` in their
* context and their own failure type, so they do not unify with the
* manager-backed handlers the shared loop iterates.
*/
export const listBrowserImportSources = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL,
payload: Schema.Void,
result: Schema.Array(BrowserImportSource),
handler: Effect.fn("desktop.ipc.preview.listBrowserImportSources")(function* () {
const browserImport = yield* BrowserImport.BrowserImport;
return yield* browserImport.listSources;
}),
});
export const importBrowserCookies = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_IMPORT_COOKIES_CHANNEL,
payload: DesktopPreviewImportCookiesInputSchema,
result: BrowserImportResult,
handler: Effect.fn("desktop.ipc.preview.importBrowserCookies")(function* ({
environmentId,
...importInput
}) {
const browserImport = yield* BrowserImport.BrowserImport;
// Derived in main from the same helper the webview config uses, so cookies
// land in exactly the partition the profile's tabs attach to.
const { scope, persistent, namespace } = resolvePartitionScope(
environmentId,
importInput.targetProfileId,
);
return yield* browserImport.importCookies({
input: importInput,
scope,
persistent,
...(namespace === undefined ? {} : { namespace }),
});
}),
});
export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema,
+4
View File
@@ -58,6 +58,7 @@ import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
@@ -149,6 +150,9 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
);
const desktopPreviewLayer = PreviewManager.layer.pipe(
// Merged rather than provided so the IPC handlers can reach the import
// service alongside the manager; both sit on the same BrowserSession.
Layer.provideMerge(BrowserImport.layer),
Layer.provideMerge(BrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
+3
View File
@@ -223,6 +223,9 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }),
openDevTools: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL),
importBrowserCookies: (input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_COOKIES_CHANNEL, input),
clearCookies: (environmentId, profileId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, { environmentId, profileId }),
clearCache: (environmentId, profileId) =>
@@ -0,0 +1,211 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as BrowserSession from "../BrowserSession.ts";
import * as BrowserImport from "./BrowserImport.ts";
import { BROWSER_IMPORT_SOURCES, sourcePaths } from "./Sources.ts";
const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
const cookie = {
url: "https://rejected.example/path",
name: "session",
value: "value",
domain: undefined,
path: "/",
secure: true,
httpOnly: true,
expirationDate: undefined,
sameSite: "lax" as const,
};
/**
* Dies if the import reaches session work: every case here covers a request
* that must be rejected before a cookie is read or written.
*/
const rejectedBeforeSession = Layer.succeed(
BrowserSession.BrowserSession,
BrowserSession.BrowserSession.of({
getPartition: () => Effect.die("getPartition must not be reached"),
isPartition: () => false,
getSession: () => Effect.die("getSession must not be reached"),
clearCookies: () => Effect.die("clearCookies must not be reached"),
clearCache: () => Effect.die("clearCache must not be reached"),
}),
);
/**
* Builds the service against a scratch home containing an installed, closed
* copy of the source browser.
*/
const withImporter = Effect.fnUntraced(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-import-" });
const environment = Layer.succeed(HostProcessEnvironment, { HOME: home });
const paths = yield* sourcePaths.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: home }),
);
yield* fileSystem.makeDirectory(`${helium.userDataDirectory(paths)}/Default`, {
recursive: true,
});
// The cookie database is what marks a source as installed, so a fixture
// without one is reported as absent before any other check runs.
yield* fileSystem.writeFileString(`${helium.userDataDirectory(paths)}/Default/Cookies`, "db");
const importer = yield* BrowserImport.BrowserImport.pipe(
Effect.provide(
BrowserImport.layer.pipe(
Layer.provide(rejectedBeforeSession),
Layer.provide(environment),
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
Layer.provide(Layer.succeed(HostProcessExecutablePath, "/Applications/T3 Code.app")),
Layer.provide(NodeServices.layer),
),
),
);
return { importer, home, paths };
});
describe("BrowserImport.importCookies", () => {
it.effect("rejects a source profile the browser never reported", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { importer, home } = yield* withImporter();
// A cookie database reachable on disk but outside the browser's
// user-data directory — the payoff a traversal would be after.
yield* fileSystem.makeDirectory(`${home}/secrets`, { recursive: true });
yield* fileSystem.writeFileString(`${home}/secrets/Cookies`, "not-a-db");
const error = yield* importer
.importCookies({
input: {
sourceId: "helium",
sourceProfileDirectory: "../../../../secrets",
targetProfileId: "default",
},
scope: "persist:t3code-preview-test",
persistent: true,
})
.pipe(Effect.flip);
assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
assert.equal(error.reason, "unknownSourceProfile");
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("refuses to import while the source browser holds its profile", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { importer, paths } = yield* withImporter();
// The lock Chromium leaves while it is running, dangling target and
// all. This must stop the import before it ever asks the keychain.
yield* fileSystem.symlink(
"host-that-does-not-exist-1234",
`${helium.userDataDirectory(paths)}/SingletonLock`,
);
const error = yield* importer
.importCookies({
input: {
sourceId: "helium",
sourceProfileDirectory: "Default",
targetProfileId: "default",
},
scope: "persist:t3code-preview-test",
persistent: true,
})
.pipe(Effect.flip);
assert.equal(error.reason, "browserRunning");
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
describe("BrowserImport.writeCookies", () => {
it.effect("counts a rejected cookie and its domain as skipped", () =>
Effect.gen(function* () {
let flushes = 0;
const result = yield* BrowserImport.writeCookies(
{
cookies: {
set: () => Promise.reject(new Error("fixture rejection")),
flushStore: () => {
flushes += 1;
return Promise.resolve();
},
},
},
{ cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
);
assert.deepEqual(result, {
imported: 0,
skipped: 1,
skippedDomains: ["rejected.example"],
});
// Nothing landed, so there is nothing to persist.
assert.equal(flushes, 0);
}),
);
it.effect("flushes the store after writing, and reports success if the flush fails", () =>
Effect.gen(function* () {
const events: Array<string> = [];
const result = yield* BrowserImport.writeCookies(
{
cookies: {
set: () => {
events.push("set");
return Promise.resolve();
},
flushStore: () => {
events.push("flush");
return Promise.reject(new Error("fixture flush failure"));
},
},
},
{ cookies: [cookie, cookie], undecryptable: 0, undecryptableHosts: [] },
);
// One flush after every write, not one per cookie; the cookies are in
// the session either way, so a failed flush is not a failed import.
assert.deepEqual(events, ["set", "set", "flush"]);
assert.deepEqual(result, { imported: 2, skipped: 0, skippedDomains: [] });
}),
);
it.effect("propagates interruption while writing a cookie", () =>
Effect.gen(function* () {
const write = BrowserImport.writeCookies(
{
cookies: {
set: () => new Promise<void>(() => {}),
flushStore: () => Promise.resolve(),
},
},
{ cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
);
const interrupted = yield* Ref.make(false);
const fiber = yield* write.pipe(
Effect.onInterrupt(() => Ref.set(interrupted, true)),
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Fiber.interrupt(fiber);
assert.isTrue(yield* Ref.get(interrupted));
}),
);
});
@@ -0,0 +1,270 @@
/**
* Browser import service - lists importable sources and writes their cookies
* into a T3 Code browser profile's Electron partition.
*
* @module BrowserImport
*/
import type {
BrowserImportInput,
BrowserImportResult,
BrowserImportSource,
BrowserImportUnavailableReason,
} from "@t3tools/contracts";
import { BrowserImportFailureReason } from "@t3tools/contracts";
import * as Context from "effect/Context";
import type { Session } from "electron";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as BrowserSession from "../BrowserSession.ts";
import { readChromiumCookies, type CookieReadResult } from "./ChromiumCookies.ts";
import {
BROWSER_IMPORT_SOURCES,
resolveCookieDatabase,
isSourceInstalled,
isSourceRunning,
listSourceProfiles,
sourcePaths,
type BrowserImportSourceDefinition,
type SourcePaths,
} from "./Sources.ts";
export class BrowserImportFailedError extends Schema.TaggedErrorClass<BrowserImportFailedError>()(
"BrowserImportFailedError",
{
sourceId: Schema.String,
reason: BrowserImportFailureReason,
/** Kept for the log; the user only ever sees the reason's copy. */
cause: Schema.optional(Schema.Defect()),
},
) {
// The reason token is part of the message on purpose: IPC flattens the error
// to its message, and the renderer maps that token back to user-facing copy.
override get message(): string {
return `Importing cookies from ${this.sourceId} failed: ${this.reason}.`;
}
}
export class BrowserCookieWriteError extends Schema.TaggedErrorClass<BrowserCookieWriteError>()(
"BrowserCookieWriteError",
{
url: Schema.String,
name: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not write imported cookie ${this.name} for ${this.url}.`;
}
}
export class BrowserImport extends Context.Service<
BrowserImport,
{
readonly listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>>;
readonly importCookies: (input: {
readonly input: BrowserImportInput;
/** Partition scope of the target profile, derived by the caller in main. */
readonly scope: string;
readonly persistent: boolean;
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
}) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
}
>()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
const unavailableReason = Effect.fn("BrowserImport.unavailableReason")(function* (
definition: BrowserImportSourceDefinition,
platform: NodeJS.Platform,
paths: SourcePaths,
): Effect.fn.Return<BrowserImportUnavailableReason | undefined, never, FileSystem.FileSystem> {
if (!definition.platforms.includes(platform)) return "unsupportedPlatform";
if (!(yield* isSourceInstalled(definition, paths))) return "notInstalled";
if (yield* isSourceRunning(definition, paths)) return "browserRunning";
return undefined;
});
/** The host a constructed cookie URL points at, for naming what was skipped. */
const cookieHost = (url: string): string => {
try {
return new URL(url).hostname;
} catch {
return url;
}
};
export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
session: { readonly cookies: Pick<Session["cookies"], "set" | "flushStore"> },
read: CookieReadResult,
) {
let imported = 0;
let skipped = read.undecryptable;
const skippedDomains = new Set(read.undecryptableHosts);
for (const cookie of read.cookies) {
const written = yield* Effect.tryPromise({
try: () =>
session.cookies.set({
url: cookie.url,
name: cookie.name,
value: cookie.value,
// Omitted for host-only cookies: Electron reads any `domain` as a
// domain cookie and re-adds the leading dot, widening its scope.
...(cookie.domain === undefined ? {} : { domain: cookie.domain }),
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
sameSite: cookie.sameSite,
...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
}),
catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }),
}).pipe(
Effect.as(true),
Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
Effect.catchTags({ BrowserCookieWriteError: () => Effect.succeed(false) }),
);
if (written) {
imported += 1;
} else {
skipped += 1;
skippedDomains.add(cookieHost(cookie.url));
}
}
// `set` resolves once the cookie is in memory; Chromium writes the store to
// disk on its own schedule. Flush before reporting "Done", so a crash right
// after does not lose what the user was just told was imported. A failed
// flush is logged rather than surfaced: the cookies are still in the
// session and land on disk at the next scheduled write.
if (imported > 0) {
yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
Effect.tapError((error) =>
Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
),
Effect.ignore,
);
}
return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) };
});
export const make = Effect.gen(function* BrowserImportMake() {
const browserSession = yield* BrowserSession.BrowserSession;
const platform = yield* HostProcessPlatform;
const executablePath = yield* HostProcessExecutablePath;
// Captured here so the service's methods stay free of a requirements
// channel: the layer is built where NodeServices is already in scope.
const platformServices = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
const paths = yield* sourcePaths;
const listSources: Effect.Effect<ReadonlyArray<BrowserImportSource>> = Effect.forEach(
BROWSER_IMPORT_SOURCES,
Effect.fnUntraced(function* (definition) {
const unavailable = yield* unavailableReason(definition, platform, paths);
return {
id: definition.id,
name: definition.name,
// Listing profiles touches the source's own files, so skip it when the
// source is unusable anyway.
profiles: unavailable === undefined ? yield* listSourceProfiles(definition, paths) : [],
...(unavailable === undefined ? {} : { unavailable }),
} satisfies BrowserImportSource;
}),
).pipe(Effect.provide(platformServices));
const importCookies = Effect.fn("BrowserImport.importCookies")(function* (input: {
readonly input: BrowserImportInput;
readonly scope: string;
readonly persistent: boolean;
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
}) {
const definition = BROWSER_IMPORT_SOURCES.find(
(candidate) => candidate.id === input.input.sourceId,
);
if (!definition) {
return yield* new BrowserImportFailedError({
sourceId: input.input.sourceId,
reason: "unknownSource",
});
}
const blocked = yield* unavailableReason(definition, platform, paths).pipe(
Effect.provide(platformServices),
);
if (blocked !== undefined) {
return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: blocked });
}
// macOS attributes the Keychain prompt and the resulting ACL grant to the
// executable that asks, so record which one that was — in a packaged build
// it is the signed app, in dev whatever binary hosts the main process.
yield* Effect.logInfo("Reading browser cookie key from the keychain", {
sourceId: definition.id,
executablePath,
});
// The profile directory arrives over IPC, so it is only honoured when the
// source itself reported it. Forwarding it unchecked would let `..`
// segments walk out of the browser's user-data directory and read any
// cookie database reachable on disk.
const sourceProfiles = yield* listSourceProfiles(definition, paths).pipe(
Effect.provide(platformServices),
);
const requestedProfile = sourceProfiles.find(
(profile) => profile.directory === input.input.sourceProfileDirectory,
);
if (requestedProfile === undefined) {
return yield* new BrowserImportFailedError({
sourceId: definition.id,
reason: "unknownSourceProfile",
});
}
// The profile was listed against a database moments ago; resolve it again
// rather than assume a path, since the live jar may sit under `Network/`.
const databasePath = yield* resolveCookieDatabase(
definition,
paths,
requestedProfile.directory,
).pipe(Effect.provide(platformServices));
if (databasePath === undefined) {
return yield* new BrowserImportFailedError({ sourceId: definition.id, reason: "readFailed" });
}
const read = yield* readChromiumCookies({
cookieDatabasePath: databasePath,
keychainService: definition.keychainService,
keychainAccount: definition.keychainAccount,
platform,
}).pipe(
Effect.scoped,
Effect.provide(platformServices),
Effect.mapError(
(cause) =>
new BrowserImportFailedError({ sourceId: definition.id, reason: cause.reason, cause }),
),
);
const session = yield* browserSession
.getSession(input.scope, input.persistent, input.namespace)
.pipe(
Effect.mapError(
(cause) =>
new BrowserImportFailedError({
sourceId: definition.id,
reason: "sessionUnavailable",
cause,
}),
),
);
// Written one at a time rather than in parallel: Chromium's cookie store
// serialises writes anyway, and a rejected cookie should only cost itself.
return yield* writeCookies(session, read);
});
return BrowserImport.of({ listSources, importCookies });
});
export const layer = Layer.effect(BrowserImport, make);
@@ -0,0 +1,379 @@
// @effect-diagnostics nodeBuiltinImport:off - Encrypts a fixture with the same
// OSCrypt primitive as Chromium.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as NodeCrypto from "node:crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Scope from "effect/Scope";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
cookieScope,
readChromiumCookieDatabase,
snapshotCookieDatabase,
} from "./ChromiumCookies.ts";
const encryptV10 = (value: string | Buffer, key: Buffer): Uint8Array => {
const cipher = NodeCrypto.createCipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
return Buffer.concat([Buffer.from("v10"), cipher.update(value), cipher.final()]);
};
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>,
) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("snapshotCookieDatabase", () => {
it.effect("includes committed WAL data in one consistent database", () =>
runNode(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-cookie-source-",
});
const source = path.join(sourceDirectory, "Cookies");
const snapshot = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL`;
yield* sql`PRAGMA wal_autocheckpoint = 0`;
yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`;
yield* sql`INSERT INTO cookies(name) VALUES (${"committed-in-wal"})`;
expect(yield* fileSystem.exists(`${source}-wal`)).toBe(true);
return yield* snapshotCookieDatabase(source);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source })));
const rows = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
return yield* sql<{ readonly name: string }>`SELECT name FROM cookies`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshot, readonly: true })));
expect(rows).toEqual([{ name: "committed-in-wal" }]);
}),
),
);
it.effect("propagates snapshot failures and removes its temporary directory", () =>
runNode(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-cookie-invalid-source-",
});
const source = path.join(sourceDirectory, "Cookies");
yield* fileSystem.writeFileString(source, "not a sqlite database");
const prefix = `t3code-cookie-failed-${process.pid}-`;
const error = yield* snapshotCookieDatabase(source, prefix).pipe(
Effect.scoped,
Effect.flip,
);
expect(error._tag).toBe("SqlError");
const temporaryEntries = yield* fileSystem.readDirectory(path.dirname(sourceDirectory));
expect(temporaryEntries.some((entry) => entry.startsWith(prefix))).toBe(false);
}),
),
);
it.effect("removes a successful snapshot when its scope closes", () =>
runNode(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-cookie-cleanup-source-",
});
const source = path.join(sourceDirectory, "Cookies");
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source })));
const snapshot = yield* snapshotCookieDatabase(source).pipe(Effect.scoped);
expect(yield* fileSystem.exists(snapshot)).toBe(false);
}),
),
);
});
describe("cookieScope", () => {
it("keeps a host-only cookie host-only", () => {
// Chromium stores a host-only cookie without a leading dot. Passing any
// `domain` to Electron makes it a domain cookie and re-adds the dot, which
// would expose the cookie to every subdomain it was never scoped to.
expect(cookieScope("example.test", "/", true)).toEqual({
url: "https://example.test/",
domain: undefined,
});
});
it("preserves a domain cookie's leading dot", () => {
expect(cookieScope(".example.test", "/app", true)).toEqual({
url: "https://example.test/app",
domain: ".example.test",
});
});
it("matches the scheme to the secure flag", () => {
expect(cookieScope("example.test", "/", false).url).toBe("http://example.test/");
});
it("brackets bare IPv6 hosts without duplicating existing brackets", () => {
expect(cookieScope("::1", "/", false)).toEqual({
url: "http://[::1]/",
domain: undefined,
});
expect(cookieScope("[::1]", "/app", true)).toEqual({
url: "https://[::1]/app",
domain: undefined,
});
});
});
describe("readChromiumCookieDatabase", () => {
it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const filename = `${directory}/Cookies`;
const key = Buffer.from("0123456789abcdef");
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value text not null)`;
yield* sql`insert into meta values ('version', 23)`;
yield* sql`
create table cookies (
host_key text not null,
name text not null,
value text not null,
encrypted_value blob not null,
path text not null,
expires_utc integer not null,
is_secure integer not null,
is_httponly integer not null,
samesite integer not null,
top_frame_site_key text not null default ''
)
`;
yield* sql`
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('plain.example', 'plain', 'stored plaintext', ${new Uint8Array()}, '/', 0, 0, 0, -1)
`;
yield* sql`
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('secure.example', 'encrypted', '', ${encryptV10("stored encrypted", key)}, '/', 0, 1, 1, 2)
`;
yield* sql`
insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)
`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
const result = yield* readChromiumCookieDatabase(filename, key, "darwin");
expect(result.undecryptable).toBe(0);
expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
{ name: "plain", value: "stored plaintext" },
{ name: "encrypted", value: "stored encrypted" },
{ name: "empty", value: "" },
]);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("enforces domain binding only for schema 24 and newer", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const filename = `${directory}/Cookies`;
const key = Buffer.from("0123456789abcdef");
const boundValue = (host: string, value: string) =>
Buffer.concat([NodeCrypto.createHash("sha256").update(host).digest(), Buffer.from(value)]);
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value text not null)`;
yield* sql`insert into meta values ('version', 24)`;
yield* sql`
create table cookies (
host_key text not null, name text not null, value text not null,
encrypted_value blob not null, path text not null, expires_utc integer not null,
is_secure integer not null, is_httponly integer not null, samesite integer not null,
top_frame_site_key text not null default ''
)
`;
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('bound.example', 'valid', '', ${encryptV10(boundValue("bound.example", "kept"), key)}, '/', 0, 1, 0, 0)`;
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('wrong.example', 'mismatch', '', ${encryptV10(boundValue("another.example", "drop"), key)}, '/', 0, 1, 0, 0)`;
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('short.example', 'short', '', ${encryptV10("short value", key)}, '/', 0, 1, 0, 0)`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
const result = yield* readChromiumCookieDatabase(filename, key, "darwin");
expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
{ name: "valid", value: "kept" },
]);
expect(result.undecryptable).toBe(2);
expect(result.undecryptableHosts).toEqual(["wrong.example", "short.example"]);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("preserves arbitrary long encrypted values from pre-24 schemas", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const filename = `${directory}/Cookies`;
const key = Buffer.from("0123456789abcdef");
const value = "x".repeat(32) + " legacy value";
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value text not null)`;
yield* sql`insert into meta values ('version', 23)`;
yield* sql`
create table cookies (
host_key text not null, name text not null, value text not null,
encrypted_value blob not null, path text not null, expires_utc integer not null,
is_secure integer not null, is_httponly integer not null, samesite integer not null,
top_frame_site_key text not null default ''
)
`;
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('legacy.example', 'legacy', '', ${encryptV10(value, key)}, '/', 0, 0, 0, 0)`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
const result = yield* readChromiumCookieDatabase(filename, key, "darwin");
expect(result.cookies[0]?.value).toBe(value);
expect(result.undecryptable).toBe(0);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("rejects a malformed text schema version", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const filename = `${directory}/Cookies`;
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value text not null)`;
yield* sql`insert into meta values ('version', 'not-a-version')`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
const error = yield* readChromiumCookieDatabase(
filename,
Buffer.from("0123456789abcdef"),
"darwin",
).pipe(Effect.flip);
expect(error._tag).toBe("SchemaError");
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("treats unversioned encrypted values as legacy plaintext only on macOS", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const filename = `${directory}/Cookies`;
const key = Buffer.from("0123456789abcdef");
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value integer not null)`;
yield* sql`insert into meta values ('version', 23)`;
yield* sql`
create table cookies (
host_key text not null, name text not null, value text not null,
encrypted_value blob not null, path text not null, expires_utc integer not null,
is_secure integer not null, is_httponly integer not null, samesite integer not null,
top_frame_site_key text not null default ''
)
`;
yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
('legacy.example', 'legacy', '', ${Buffer.from("legacy cleartext")}, '/', 0, 0, 0, 0)`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
const mac = yield* readChromiumCookieDatabase(filename, key, "darwin");
const linux = yield* readChromiumCookieDatabase(filename, key, "linux");
expect(mac.cookies[0]?.value).toBe("legacy cleartext");
expect(mac.undecryptable).toBe(0);
expect(linux.cookies).toEqual([]);
expect(linux.undecryptable).toBe(1);
expect(linux.undecryptableHosts).toEqual(["legacy.example"]);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-chromium-cookies-",
});
const legacyFilename = `${directory}/LegacyCookies`;
const chipsFilename = `${directory}/ChipsCookies`;
const key = Buffer.from("0123456789abcdef");
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value integer not null)`;
yield* sql`insert into meta values ('version', 14)`;
yield* sql`
create table cookies (
host_key text not null, name text not null, value text not null,
encrypted_value blob not null, path text not null, expires_utc integer not null,
is_secure integer not null, is_httponly integer not null, samesite integer not null
)
`;
yield* sql`insert into cookies values
('legacy.example', 'legacy', 'kept', ${new Uint8Array()}, '/', 0, 0, 0, 0)`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacyFilename })));
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`create table meta (key text primary key, value integer not null)`;
yield* sql`insert into meta values ('version', 23)`;
yield* sql`
create table cookies (
host_key text not null, name text not null, value text not null,
encrypted_value blob not null, path text not null, expires_utc integer not null,
is_secure integer not null, is_httponly integer not null, samesite integer not null,
top_frame_site_key text not null
)
`;
yield* sql`insert into cookies values
('plain.example', 'plain', 'kept', ${new Uint8Array()}, '/', 0, 0, 0, 0, '')`;
yield* sql`insert into cookies values
('partitioned.example', 'partitioned', 'must skip', ${new Uint8Array()}, '/', 0, 1, 0, 0, 'https://top.example')`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: chipsFilename })));
const legacy = yield* readChromiumCookieDatabase(legacyFilename, key, "darwin");
const chips = yield* readChromiumCookieDatabase(chipsFilename, key, "darwin");
expect(legacy.cookies.map(({ name }) => name)).toEqual(["legacy"]);
expect(legacy.undecryptable).toBe(0);
expect(chips.cookies.map(({ name }) => name)).toEqual(["plain"]);
expect(chips.undecryptable).toBe(1);
expect(chips.undecryptableHosts).toEqual(["partitioned.example"]);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -0,0 +1,409 @@
// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the
// OSCrypt primitives Chromium uses; Effect has no equivalent.
/**
* Chromium cookie extraction.
*
* Reads a Chromium-family browser's cookie database and decrypts it with the
* key the OS keychain hands us, which is the mechanism the browser itself
* uses. macOS mediates that with a per-app consent prompt, so the user
* explicitly approves T3 Code reading it.
*
* Deliberately no fallback when the keychain says no: the alternative
* techniques exist to defeat that consent, and this feature is not worth
* shipping them.
*
* @module ChromiumCookies
*/
import * as Keyring from "@napi-rs/keyring";
import * as NodeCrypto from "node:crypto";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/** macOS OSCrypt parameters. Chromium has used these since the feature landed. */
const MAC_KEY_ITERATIONS = 1003;
const MAC_KEY_SALT = "saltysalt";
const MAC_KEY_LENGTH = 16;
/** OSCrypt uses a fixed IV of 16 spaces rather than a per-record one. */
const AES_IV = Buffer.alloc(16, 0x20);
const V10_PREFIX = "v10";
export interface ChromiumCookie {
readonly url: string;
readonly name: string;
readonly value: string;
/**
* Set only for domain cookies, which Chromium stores with a leading dot.
* A host-only cookie leaves this undefined: Electron treats any `domain` it
* is given as a domain cookie and re-adds the dot, which would widen the
* cookie to every subdomain of the host it was scoped to.
*/
readonly domain: string | undefined;
readonly path: string;
readonly secure: boolean;
readonly httpOnly: boolean;
/** Seconds since the UNIX epoch, or undefined for a session cookie. */
readonly expirationDate: number | undefined;
readonly sameSite: "no_restriction" | "lax" | "strict";
}
export const ChromiumCookieReadReason = Schema.Literals([
"needsKeychainApproval",
"keychainItemMissing",
"browserRunning",
"unsupportedPlatform",
"readFailed",
]);
export type ChromiumCookieReadReason = typeof ChromiumCookieReadReason.Type;
export class ChromiumCookieReadError extends Schema.TaggedErrorClass<ChromiumCookieReadError>()(
"ChromiumCookieReadError",
{
reason: ChromiumCookieReadReason,
/**
* Which database the read was for. Without it every `readFailed` and
* keychain failure logs identically, and a user with several browsers
* installed has no way to tell which one refused.
*/
cookieDatabasePath: Schema.String,
/** Kept for the log; never surfaced to the user. */
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Could not read Chromium cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
}
}
/** Row shape of the cookie table, decoded rather than cast. */
const CookieRow = Schema.Struct({
host_key: Schema.String,
name: Schema.String,
value: Schema.String,
encrypted_value: Schema.Uint8Array,
path: Schema.String,
expires_seconds: Schema.Number,
is_secure: Schema.Number,
is_httponly: Schema.Number,
samesite: Schema.Number,
top_frame_site_key: Schema.String,
});
const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow));
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
const SchemaVersion = Schema.Union([
NonNegativeInt,
Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
]);
const decodeSchemaVersion = Schema.decodeUnknownEffect(
Schema.Tuple([Schema.Struct({ value: SchemaVersion })]),
);
/**
* Chromium stores `SameSite` as an int; unspecified (-1) behaves as Lax in
* modern Chromium, so it maps there rather than to `no_restriction`, which
* would widen the cookie's scope on import.
*/
const sameSiteFromColumn = (value: number): ChromiumCookie["sameSite"] => {
if (value === 0) return "no_restriction";
if (value === 2) return "strict";
return "lax";
};
/**
* Chromium timestamps count microseconds from 1601-01-01; Electron wants
* seconds from the UNIX epoch.
*
* The microsecond value overflows JavaScript's safe integer range, and
* `node:sqlite` refuses to narrow it, so the division happens in SQL and this
* only ever sees seconds.
*/
const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600;
const toUnixSeconds = (webkitSeconds: number): number | undefined => {
if (webkitSeconds <= 0) return undefined;
return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS;
};
/**
* Reads the OSCrypt key from the login keychain.
*
* Uses the in-process Keychain API rather than shelling out to
* `/usr/bin/security`, because the keychain attributes both the consent prompt
* and the resulting ACL entry to the binary that asks. Via the CLI the prompt
* says "security" and "Always Allow" grants trust to a tool every process on
* the machine can invoke; in-process it names this app and the grant belongs
* to it. (In an unsigned dev build the name is the dev Electron binary rather
* than the shipped app identity.)
*
* Deliberately untimed: macOS answers this with a modal, and a timeout racing
* the user means the prompt can be approved while nothing is left listening —
* which reads as "approving did nothing".
*/
const readMacKeychainPassword = Effect.fn("ChromiumCookies.readMacKeychainPassword")(function* (
service: string,
account: string,
cookieDatabasePath: string,
) {
const password = yield* Effect.try({
try: () => new Keyring.Entry(service, account).getPassword(),
catch: (cause) => {
const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
// Distinguish the causes rather than telling the user to approve a
// prompt when approving cannot fix the failure.
const missing = /no (matching )?entry|not found/i.test(message);
return new ChromiumCookieReadError({
reason: missing ? "keychainItemMissing" : "needsKeychainApproval",
cookieDatabasePath,
cause,
});
},
});
if (password === null || password === "") {
return yield* new ChromiumCookieReadError({
reason: "keychainItemMissing",
cookieDatabasePath,
});
}
return password;
});
/**
* Chromium keeps the cookie DB open with WAL. SQLite must create the snapshot
* itself so the main database and WAL are read from one transactionally
* consistent generation. Copying those files one after another can pair a
* newer database with an older WAL (or the reverse).
*
* Scoped: the temp directory is removed when the caller's scope closes.
*/
export const snapshotCookieDatabase = Effect.fn("ChromiumCookies.snapshotCookieDatabase")(
function* (cookiePath: string, tempPrefix = "t3code-cookie-import-") {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: tempPrefix });
const target = path.join(directory, "Cookies");
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`VACUUM INTO ${target}`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: cookiePath, readonly: true })));
return target;
},
);
/**
* The URL and domain Electron should register a stored row under.
*
* Chromium marks a domain cookie with a leading dot on `host_key`. Electron
* matches on a URL, so the dot comes off for that; `domain` is passed through
* only for domain cookies, because supplying it at all makes Electron treat
* the cookie as one and re-add the dot — widening a host-only cookie to every
* subdomain of the host it was scoped to, and rejecting `__Host-` cookies,
* which require it to be absent.
*/
export const cookieScope = (
hostKey: string,
path: string,
secure: boolean,
): { readonly url: string; readonly domain: string | undefined } => {
const isDomainCookie = hostKey.startsWith(".");
const host = isDomainCookie ? hostKey.slice(1) : hostKey;
const urlAuthority =
host.includes(":") && !(host.startsWith("[") && host.endsWith("]")) ? `[${host}]` : host;
return {
url: `${secure ? "https" : "http"}://${urlAuthority}${path}`,
...(isDomainCookie ? { domain: hostKey } : { domain: undefined }),
};
};
/** The host without Chromium's domain-cookie leading dot, for display. */
const bareHost = (hostKey: string): string =>
hostKey.startsWith(".") ? hostKey.slice(1) : hostKey;
const decryptValue = (
encrypted: Uint8Array,
key: Buffer,
domain: string,
schemaVersion: number,
platform: NodeJS.Platform,
): string | null => {
const buffer = Buffer.from(encrypted);
const version = buffer.subarray(0, 3).toString("latin1");
try {
let plaintext: Buffer;
if (version === V10_PREFIX) {
const decipher = NodeCrypto.createDecipheriv("aes-128-cbc", key, AES_IV);
decipher.setAutoPadding(true);
plaintext = Buffer.concat([decipher.update(buffer.subarray(3)), decipher.final()]);
} else if (platform === "darwin") {
// macOS OSCrypt explicitly treats an unversioned encrypted_value as
// legacy cleartext. This is platform-specific: Linux uses other version
// prefixes, which must not be widened into plaintext cookies.
plaintext = buffer;
} else {
return null;
}
// Cookie schema 24 requires SHA-256(host_key) at the front of every
// encrypted value. Treat a missing or mismatched binding as undecryptable;
// older schemas stored arbitrary plaintext here, including long values
// whose first 32 bytes must not be interpreted as a hash.
if (schemaVersion >= 24) {
const domainHash = NodeCrypto.createHash("sha256").update(domain).digest();
if (plaintext.length < domainHash.length || !plaintext.subarray(0, 32).equals(domainHash)) {
return null;
}
plaintext = plaintext.subarray(32);
}
return plaintext.toString("utf8");
} catch {
return null;
}
};
/** Reads and decodes one snapshotted Chromium cookie database. */
export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiumCookieDatabase")(
function* (snapshotPath: string, key: Buffer, platform: NodeJS.Platform) {
const rows = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe(
Effect.flatMap(decodeSchemaVersion),
Effect.map(([row]) => row.value),
);
// CHIPS added top_frame_site_key in schema 15. Keep the old query valid
// for earlier databases, which do not have the column at all.
const raw =
schemaVersion >= 15
? yield* sql`
select host_key, name, value, encrypted_value, path,
expires_utc / 1000000 as expires_seconds,
is_secure, is_httponly, samesite, top_frame_site_key
from cookies
`
: yield* sql`
select host_key, name, value, encrypted_value, path,
expires_utc / 1000000 as expires_seconds,
is_secure, is_httponly, samesite, '' as top_frame_site_key
from cookies
`;
return { rows: yield* decodeCookieRows(raw), schemaVersion };
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })));
const cookies: ChromiumCookie[] = [];
let undecryptable = 0;
const undecryptableHosts = new Set<string>();
for (const row of rows.rows) {
// Electron's cookies.set contract cannot represent a CHIPS partition
// key. Importing this row without one would widen it into an ordinary
// unpartitioned cookie, so count it as skipped instead.
if (row.top_frame_site_key !== "") {
undecryptable += 1;
undecryptableHosts.add(bareHost(row.host_key));
continue;
}
// Chromium stores legacy/plaintext cookies in `value` with an empty
// encrypted blob. Preserve an actually empty cookie by falling back to
// `value`, rather than treating every empty blob as the empty string.
const value =
row.encrypted_value.length === 0
? row.value
: decryptValue(row.encrypted_value, key, row.host_key, rows.schemaVersion, platform);
if (value === null) {
undecryptable += 1;
undecryptableHosts.add(bareHost(row.host_key));
continue;
}
const secure = row.is_secure === 1;
const scope = cookieScope(row.host_key, row.path, secure);
cookies.push({
url: scope.url,
name: row.name,
value,
domain: scope.domain,
path: row.path,
secure,
httpOnly: row.is_httponly === 1,
expirationDate: toUnixSeconds(row.expires_seconds),
sameSite: sameSiteFromColumn(row.samesite),
});
}
return {
cookies,
undecryptable,
undecryptableHosts: [...undecryptableHosts],
} satisfies CookieReadResult;
},
);
/**
* What a reader produces: the cookies it could recover, and how many stored
* rows it could not. The count reaches the user as part of the skipped total
* rather than disappearing.
*/
export interface CookieReadResult {
readonly cookies: ReadonlyArray<ChromiumCookie>;
readonly undecryptable: number;
/** Distinct hosts of the rows that could not be decrypted. */
readonly undecryptableHosts: ReadonlyArray<string>;
}
export interface ChromiumCookieSource {
readonly cookieDatabasePath: string;
readonly keychainService: string;
readonly keychainAccount: string;
/** Supplied by the caller from `HostProcessPlatform` rather than read here. */
readonly platform: NodeJS.Platform;
}
export const readChromiumCookies = Effect.fn("ChromiumCookies.readChromiumCookies")(function* (
source: ChromiumCookieSource,
) {
if (source.platform !== "darwin") {
// Linux (libsecret) and Windows (DPAPI, and App-Bound Encryption on
// current Chrome) each need their own key path; only macOS is implemented.
return yield* new ChromiumCookieReadError({
reason: "unsupportedPlatform",
cookieDatabasePath: source.cookieDatabasePath,
});
}
const password = yield* readMacKeychainPassword(
source.keychainService,
source.keychainAccount,
source.cookieDatabasePath,
);
const key = NodeCrypto.pbkdf2Sync(
password,
MAC_KEY_SALT,
MAC_KEY_ITERATIONS,
MAC_KEY_LENGTH,
"sha1",
);
const snapshotPath = yield* snapshotCookieDatabase(source.cookieDatabasePath).pipe(
Effect.mapError(
(cause) =>
new ChromiumCookieReadError({
reason: "readFailed",
cookieDatabasePath: source.cookieDatabasePath,
cause,
}),
),
);
return yield* readChromiumCookieDatabase(snapshotPath, key, source.platform).pipe(
Effect.mapError(
(cause) =>
new ChromiumCookieReadError({
reason: "readFailed",
cookieDatabasePath: source.cookieDatabasePath,
cause,
}),
),
);
});
@@ -0,0 +1,365 @@
// @effect-diagnostics nodeBuiltinImport:off - Builds a Chromium-shaped cookie
// table with the same native bindings the source reads.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { HostProcessEnvironment, HostProcessHostname } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Scope from "effect/Scope";
import * as NodeSqlite from "node:sqlite";
import {
BROWSER_IMPORT_SOURCES,
chromiumProcessIsAlive,
chromiumSingletonLockIsHeld,
cookieDatabaseCandidatePaths,
resolveCookieDatabase,
isSourceInstalled,
isSourceRunning,
listSourceProfiles,
sourcePaths,
} from "./Sources.ts";
const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
/** A scratch home with the source's user-data directory already created. */
const withSourceHome = Effect.fnUntraced(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-" });
const paths = yield* sourcePaths.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: home }),
);
yield* fileSystem.makeDirectory(helium.userDataDirectory(paths), { recursive: true });
return paths;
});
const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>) =>
effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
/** Writes a Chromium-shaped cookie table with `count` rows. */
const writeCookieDatabase = (file: string, count: number) =>
Effect.sync(() => {
const database = new NodeSqlite.DatabaseSync(file);
database.exec("create table cookies (host_key text, name text)");
const insert = database.prepare("insert into cookies (host_key, name) values (?, ?)");
for (let index = 0; index < count; index += 1) insert.run("example.test", `c${index}`);
database.close();
});
describe("isSourceRunning", () => {
it.effect("reads Chromium's dangling SingletonLock symlink as a running browser", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
assert.isFalse(yield* isSourceRunning(helium, paths));
// Chromium points the lock at `<host>-<pid>`, a target that never
// exists on disk. A check that follows the link reports a running
// browser as closed, letting an import read a live, mid-write database.
yield* fileSystem.symlink(
"host-that-does-not-exist-1234",
`${helium.userDataDirectory(paths)}/SingletonLock`,
);
assert.isTrue(yield* isSourceRunning(helium, paths));
}),
),
);
it.effect("uses the provided hostname to classify Chromium locks", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
yield* fileSystem.symlink(
"lock-owner-99999999",
`${helium.userDataDirectory(paths)}/SingletonLock`,
);
assert.isTrue(
yield* isSourceRunning(helium, paths).pipe(
Effect.provideService(HostProcessHostname, "another-host"),
),
);
assert.isFalse(
yield* isSourceRunning(helium, paths).pipe(
Effect.provideService(HostProcessHostname, "lock-owner"),
),
);
}),
),
);
});
describe("chromiumSingletonLockIsHeld", () => {
it.effect("ignores a positively dead PID on the current host", () =>
Effect.gen(function* () {
const checked: number[] = [];
const held = yield* chromiumSingletonLockIsHeld("current-host-4321", "current-host", (pid) =>
Effect.sync(() => {
checked.push(pid);
return false;
}),
);
assert.isFalse(held);
assert.deepEqual(checked, [4321]);
}),
);
it.effect("keeps a live PID on the current host", () =>
chromiumSingletonLockIsHeld("current-host-4321", "current-host", () =>
Effect.succeed(true),
).pipe(Effect.tap((held) => Effect.sync(() => assert.isTrue(held)))),
);
it.effect("keeps foreign-host and malformed targets without probing a PID", () =>
Effect.gen(function* () {
let probes = 0;
const probe = (_pid: number) =>
Effect.sync(() => {
probes += 1;
return false;
});
assert.isTrue(yield* chromiumSingletonLockIsHeld("another-host-4321", "current-host", probe));
assert.isTrue(
yield* chromiumSingletonLockIsHeld("current-host-no-pid", "current-host", probe),
);
assert.isTrue(yield* chromiumSingletonLockIsHeld("current-host-0", "current-host", probe));
assert.strictEqual(probes, 0);
}),
);
});
describe("chromiumProcessIsAlive", () => {
it.effect("returns false only when signal 0 reports a missing process", () =>
Effect.gen(function* () {
const missing = Object.assign(new Error("missing"), { code: "ESRCH" });
const denied = Object.assign(new Error("denied"), { code: "EPERM" });
assert.isFalse(
yield* chromiumProcessIsAlive(4321, () => {
throw missing;
}),
);
assert.isTrue(
yield* chromiumProcessIsAlive(4321, () => {
throw denied;
}),
);
assert.isTrue(
yield* chromiumProcessIsAlive(4321, () => {
throw undefined;
}),
);
assert.isTrue(
yield* chromiumProcessIsAlive(4321, () => {
throw "unknown failure";
}),
);
assert.isTrue(
yield* chromiumProcessIsAlive(4321, () => {
throw null;
}),
);
assert.isTrue(yield* chromiumProcessIsAlive(4321, () => true));
}),
);
});
describe("isSourceInstalled", () => {
it.effect("ignores a user-data directory that holds no cookie database", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
// Installers for native messaging hosts create an empty user-data
// directory for every Chromium fork they know about, so treating the
// directory as evidence lists browsers the user does not have.
yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
assert.isFalse(yield* isSourceInstalled(helium, paths));
yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
assert.isTrue(yield* isSourceInstalled(helium, paths));
// A real install whose cookies live outside `Default` still counts:
// reporting it as absent hides the source from the menu entirely.
yield* fileSystem.remove(`${root}/Default`, { recursive: true });
yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
assert.isTrue(yield* isSourceInstalled(helium, paths));
yield* fileSystem.remove(root, { recursive: true });
assert.isFalse(yield* isSourceInstalled(helium, paths));
}),
),
);
});
describe("listSourceProfiles", () => {
it.effect("ignores a profile whose Cookies entry is not a file", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
// A directory named `Cookies` would list as importable and then fail
// the SQLite open, so only a regular file counts as a database.
yield* fileSystem.makeDirectory(`${root}/Broken/Cookies`, { recursive: true });
yield* fileSystem.makeDirectory(`${root}/Real`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Real/Cookies`, "db");
assert.deepEqual(yield* listSourceProfiles(helium, paths), [
{ directory: "Real", name: "Real" },
]);
assert.isTrue(yield* isSourceInstalled(helium, paths));
}),
),
);
it.effect("discovers profiles by their cookie database when Local State is absent", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
// Assuming `Default` would report a browser whose cookies live in
// `Profile 1` as having nothing to import, and it is then hidden.
yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
assert.deepEqual(yield* listSourceProfiles(helium, paths), [
{ directory: "Profile 1", name: "Profile 1" },
]);
}),
),
);
it.effect("reads the profile names the browser shows", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
yield* fileSystem.writeFileString(
`${helium.userDataDirectory(paths)}/Local State`,
`{"profile":{"info_cache":{"Default":{"name":"You"},"Profile 2":{"name":" "}}}}`,
);
assert.deepEqual(yield* listSourceProfiles(helium, paths), [
{ directory: "Default", name: "You" },
// Blank display name falls back to the directory rather than
// rendering an empty row.
{ directory: "Profile 2", name: "Profile 2" },
]);
}),
),
);
it.effect("scans for profiles when Local State is malformed", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
yield* fileSystem.writeFileString(`${root}/Local State`, "{not-json");
yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
assert.deepEqual(yield* listSourceProfiles(helium, paths), [
{ directory: "Default", name: "Default" },
]);
}),
),
);
it.effect("reports nothing when no directory holds a cookie database", () =>
run(
Effect.gen(function* () {
const paths = yield* withSourceHome();
assert.deepEqual(yield* listSourceProfiles(helium, paths), []);
}),
),
);
it.effect("counts a profile's cookies without decrypting them", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
yield* writeCookieDatabase(`${root}/Default/Cookies`, 3);
const [profile] = yield* listSourceProfiles(helium, paths);
assert.equal(profile?.cookieCount, 3);
}),
),
);
});
describe("cookieDatabaseCandidatePaths", () => {
it.effect("prefers Network/Cookies and falls back to the legacy Cookies", () =>
run(
Effect.gen(function* () {
const paths = yield* withSourceHome();
const profile = `${paths.home}/Library/Application Support/net.imput.helium/Profile 1`;
assert.deepEqual(cookieDatabaseCandidatePaths(helium, paths, "Profile 1"), [
`${profile}/Network/Cookies`,
`${profile}/Cookies`,
]);
}),
),
);
it.effect("resolves the live Network/ jar over a leftover root Cookies", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
// Chromium 96+ keeps sessions in Network/; a root Cookies left behind
// by the move is stale and must not be the one imported.
yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "live");
yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "stale");
assert.equal(
yield* resolveCookieDatabase(helium, paths, "Default"),
`${root}/Default/Network/Cookies`,
);
// A fresh install with only the Network/ jar is installed, not hidden.
yield* fileSystem.remove(`${root}/Default/Cookies`);
assert.isTrue(yield* isSourceInstalled(helium, paths));
}),
),
);
});
describe("listSourceProfiles hardening", () => {
it.effect("drops profile directories that are not a single plain segment", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
// `Local State` is writable by anything running as the user, so a
// crafted key must not reach `cookieDatabasePath` and read a database
// outside the browser's user-data directory.
yield* fileSystem.writeFileString(
`${helium.userDataDirectory(paths)}/Local State`,
`{"profile":{"info_cache":{"Default":{"name":"You"},"../../../../secrets":{"name":"Escape"},"a/b":{"name":"Nested"},"..":{"name":"Parent"}}}}`,
);
const profiles = yield* listSourceProfiles(helium, paths);
assert.deepEqual(
profiles.map((profile) => profile.directory),
["Default"],
);
}),
),
);
});
@@ -0,0 +1,307 @@
/**
* Importable browser sources.
*
* Each entry pins its own on-disk and keychain coordinates rather than
* deriving them: Chromium forks do not agree on the convention. Helium, for
* instance, uses the keychain service "Helium Storage Key" / account "Helium"
* where Chrome and its closer relatives use "<Name> Safe Storage" / "<Name>".
*
* @module BrowserImportSources
*/
import type { BrowserImportSourceId, BrowserImportSourceProfile } from "@t3tools/contracts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { HostProcessEnvironment, HostProcessHostname } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Where a source's files live, resolved once per call rather than read from
* the ambient process so the registry stays testable.
*/
export interface SourcePaths {
readonly path: Path.Path;
readonly home: string;
}
export const sourcePaths = Effect.gen(function* () {
const path = yield* Path.Path;
const environment = yield* HostProcessEnvironment;
return { path, home: environment.HOME ?? environment.USERPROFILE ?? "" } satisfies SourcePaths;
});
export interface BrowserImportSourceDefinition {
readonly id: BrowserImportSourceId;
readonly name: string;
/** Platforms the definition's paths are valid for. */
readonly platforms: ReadonlyArray<NodeJS.Platform>;
readonly userDataDirectory: (paths: SourcePaths) => string;
readonly keychainService: string;
readonly keychainAccount: string;
}
export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition> = [
{
id: "helium",
name: "Helium",
platforms: ["darwin"],
userDataDirectory: ({ path, home }) =>
path.join(home, "Library", "Application Support", "net.imput.helium"),
keychainService: "Helium Storage Key",
keychainAccount: "Helium",
},
];
/**
* Where a profile's cookie database may live, most current first. Chromium 96
* moved the live jar to `Network/Cookies`; a root-level `Cookies` is either a
* pre-96 install or a leftover from before the move. Importing the leftover
* while sessions live in `Network/` would snapshot a stale or empty database,
* and a fresh install with only `Network/Cookies` would read as not installed.
*/
export const cookieDatabaseCandidatePaths = (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
profileDirectory: string,
): ReadonlyArray<string> => {
const profile = paths.path.join(definition.userDataDirectory(paths), profileDirectory);
return [paths.path.join(profile, "Network", "Cookies"), paths.path.join(profile, "Cookies")];
};
/** The first candidate that is a regular file, or undefined when none is. */
export const resolveCookieDatabase = Effect.fnUntraced(function* (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
profileDirectory: string,
) {
for (const candidate of cookieDatabaseCandidatePaths(definition, paths, profileDirectory)) {
if (yield* databaseFileExists(candidate)) return candidate;
}
return undefined;
});
/** Shape of the slice of Chromium's `Local State` that names its profiles. */
const LocalState = Schema.Struct({
profile: Schema.optional(
Schema.Struct({
info_cache: Schema.optional(
Schema.Record(Schema.String, Schema.Struct({ name: Schema.optional(Schema.String) })),
),
}),
),
});
const decodeLocalState = Schema.decodeUnknownEffect(Schema.fromJsonString(LocalState));
/** A single plain path segment: no separators, no `.`/`..`, not empty. */
const isSafeProfileDirectory = (directory: string): boolean =>
directory.length > 0 &&
directory !== "." &&
directory !== ".." &&
!/[\\/]/.test(directory) &&
!directory.includes("\u0000");
const CookieCountRow = Schema.Struct({ count: Schema.Number });
const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow));
/**
* How many cookies a profile holds, counted without decrypting anything — a
* bare `COUNT(*)` needs no key. Best effort: a locked, missing or non-Chromium
* database (Firefox's table is named differently, Safari's is not SQL) yields
* `undefined` rather than failing the listing.
*/
const countProfileCookies = Effect.fnUntraced(function* (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
directory: string,
): Effect.fn.Return<number | undefined, never, FileSystem.FileSystem> {
const database = yield* resolveCookieDatabase(definition, paths, directory);
if (database === undefined) return undefined;
return yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const rows = yield* sql`select count(*) as count from cookies`;
const [row] = yield* decodeCookieCount(rows);
return row?.count;
}).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
Effect.orElseSucceed(() => undefined),
);
});
const withCookieCounts = (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
profiles: ReadonlyArray<BrowserImportSourceProfile>,
) =>
Effect.forEach(profiles, (profile) =>
countProfileCookies(definition, paths, profile.directory).pipe(
Effect.map((cookieCount) =>
cookieCount === undefined ? profile : { ...profile, cookieCount },
),
),
);
/**
* Profiles the source browser knows about, read from its `Local State`.
*
* When that file is missing, unreadable or malformed, the user-data directory
* is scanned for directories that hold a cookie database. Assuming `Default`
* instead would report a browser whose cookies live in `Profile 1` as having
* nothing to import — and it is then left out of the menu entirely.
*/
export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
) {
const fileSystem = yield* FileSystem.FileSystem;
const localStatePath = paths.path.join(definition.userDataDirectory(paths), "Local State");
const root = definition.userDataDirectory(paths);
const declared = yield* fileSystem.readFileString(localStatePath).pipe(
Effect.flatMap(decodeLocalState),
Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})),
// The keys are directory names from the browser's own metadata file, which
// is writable by anything running as the user. Anything but a single plain
// segment is dropped: `..` or a path separator would otherwise be handed
// to `cookieDatabasePath` and read a database outside the user-data
// directory.
Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))),
Effect.map((entries) =>
entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })),
),
Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
);
if (declared.length > 0) return yield* withCookieCounts(definition, paths, declared);
// `Local State` is missing, unreadable or malformed. Scanning for
// directories that hold a cookie database finds the profiles anyway;
// assuming `Default` would report a browser whose cookies live in
// `Profile 1` as having nothing to import, and it is then hidden entirely.
const entries = yield* fileSystem
.readDirectory(root)
.pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
const candidates = entries.filter(isSafeProfileDirectory);
const found = yield* Effect.forEach(candidates, (directory) =>
resolveCookieDatabase(definition, paths, directory).pipe(
Effect.map((database) =>
database === undefined ? undefined : { directory, name: directory },
),
),
);
return yield* withCookieCounts(
definition,
paths,
found.filter((profile) => profile !== undefined),
);
});
/**
* Whether a cookie database candidate is a regular file. Presence alone is
* not enough: a directory at the path would list as an importable profile and
* then fail the SQLite open, so anything but a file is treated as absent.
*/
const databaseFileExists = Effect.fnUntraced(function* (path: string) {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.stat(path).pipe(
Effect.map((info) => info.type === "File"),
Effect.orElseSucceed(() => false),
);
});
type ProcessLivenessProbe = (pid: number) => Effect.Effect<boolean>;
export const chromiumProcessIsAlive = (
pid: number,
signalProcess: (pid: number, signal: 0) => unknown = process.kill.bind(process),
) =>
Effect.sync(() => {
try {
// Signal 0 performs a read-only existence/permission check.
signalProcess(pid, 0);
return true;
} catch (cause) {
// Only ESRCH positively proves the process is gone. Permission errors
// and unknown failures stay conservative so an active browser is never
// mistaken for a stale lock.
return !(
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "ESRCH"
);
}
});
const processIsAlive: ProcessLivenessProbe = (pid) => chromiumProcessIsAlive(pid);
/** Whether a Chromium `<host>-<pid>` lock target may still name its owner. */
export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* (
target: string,
currentHost: string,
isProcessAlive: ProcessLivenessProbe,
) {
const separator = target.lastIndexOf("-");
if (separator <= 0) return true;
const host = target.slice(0, separator);
const pidText = target.slice(separator + 1);
if (!/^\d+$/.test(pidText)) return true;
const pid = Number(pidText);
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
// A PID is meaningful only on this host. A foreign hostname can come from a
// shared home directory, and cannot safely be declared stale from here.
if (host !== currentHost) return true;
return yield* isProcessAlive(pid);
});
/** Whether the browser is running, which leaves its cookie DB mid-write. */
export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")(function* (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
) {
const fileSystem = yield* FileSystem.FileSystem;
const currentHost = yield* HostProcessHostname;
const lock = paths.path.join(definition.userDataDirectory(paths), "SingletonLock");
// Chromium writes a `SingletonLock` symlink for as long as an instance holds
// the profile. Its presence is a far cheaper and more targeted signal than
// scanning the process table for a name.
//
// The link points at `<host>-<pid>`, a target that never exists, and both
// `stat` and `exists` follow links — so they report every running browser as
// closed, which would let an import read a live, mid-write database.
// `readLink` is the one probe that answers for the entry itself. Chromium
// can leave this link behind after a crash, so a positively dead local PID
// is stale. Every ambiguous target or liveness result stays conservative.
return yield* fileSystem.readLink(lock).pipe(
Effect.flatMap((target) => chromiumSingletonLockIsHeld(target, currentHost, processIsAlive)),
Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
);
});
/**
* Whether the source has cookies to import.
*
* Keyed off the cookie database rather than the user-data directory, because
* that directory is not evidence the browser exists: installers for native
* messaging hosts create an empty one for every Chromium fork they know about,
* so a machine with only Chrome reports Edge, Brave, Vivaldi, Opera and Arc as
* present. The database is the thing an import actually needs, so its absence
* is the honest answer either way.
*
* Existence is checked without opening the file, which matters for Safari: TCC
* permits `stat` on the jar inside its container but refuses a read, so this
* still sees it and the user gets the Full Disk Access prompt rather than
* having Safari disappear.
*/
export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* (
definition: BrowserImportSourceDefinition,
paths: SourcePaths,
) {
const profiles = yield* listSourceProfiles(definition, paths);
const found = yield* Effect.forEach(profiles, (profile) =>
resolveCookieDatabase(definition, paths, profile.directory).pipe(
Effect.map((database) => database !== undefined),
),
);
return found.some(Boolean);
});
@@ -0,0 +1,475 @@
import type { BrowserImportSource } from "@t3tools/contracts";
import { BROWSER_IMPORT_FAILURE_COPY } from "@t3tools/contracts";
import { ArrowDownIcon, ArrowRightIcon, CheckIcon } from "lucide-react";
import { useRef, useState } from "react";
import { cn, randomUUID } from "~/lib/utils";
import { Button } from "../ui/button";
import {
Dialog,
DialogClose,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Spinner } from "../ui/spinner";
import {
initialWizardStep,
initialTargetSelection,
canCloseWizard,
isRetryableReason,
formatSkippedDomains,
outcomeToStep,
refreshedSourceProfileDirectory,
refreshedSourceStep,
resolveWizardTarget,
type ImportOutcome,
type WizardTarget,
type WizardTargetProfile,
type WizardTargetSelection,
type WizardStep,
} from "./browserImportWizard.logic";
export type { WizardTarget } from "./browserImportWizard.logic";
interface BrowserImportWizardProps {
readonly source: BrowserImportSource;
/** Captured when the wizard opens so destination copy and writes stay stable. */
readonly destinationEnvironmentName: string;
/** Existing profiles the import can go into. Incognito is excluded upstream. */
readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
/** Whether a new profile can still be created (profile cap). */
readonly canCreateProfile: boolean;
/**
* Runs the import and returns how it went. For a new target the caller only
* registers the profile once the import succeeds, so a blocked attempt never
* leaves an empty profile behind.
*/
readonly onImport: (input: {
readonly sourceProfileDirectory: string;
readonly target: WizardTarget;
}) => Promise<ImportOutcome>;
/** Re-checks the source's availability after the user quits the browser. */
readonly onRefreshSource: () => Promise<BrowserImportSource | undefined>;
readonly onClose: () => void;
}
/**
* Guides one browser's cookies into a profile.
*
* Every state the import can be in — the browser is open, a profile has to be
* chosen, the read failed — is a screen the user can move forward from, rather
* than a disabled row that only says no.
*/
export function BrowserImportWizard({
source: initialSource,
destinationEnvironmentName,
targetProfiles,
canCreateProfile,
onImport,
onRefreshSource,
onClose,
}: BrowserImportWizardProps) {
const [source, setSource] = useState(initialSource);
const [step, setStep] = useState<WizardStep>(() => initialWizardStep(initialSource));
const [sourceProfileDirectory, setSourceProfileDirectory] = useState(
() => initialSource.profiles[0]?.directory ?? "",
);
const [target, setTarget] = useState<WizardTargetSelection>(() =>
initialTargetSelection(canCreateProfile, targetProfiles),
);
const [targetError, setTargetError] = useState<string>();
// Stable across retries so a keychain re-approval lands in one profile, not
// a new one each time.
const newProfileId = useRef(`profile-${randomUUID()}`);
// A second Import click before React has left the configure screen would
// start a second run; the parent refuses it, and applying that refusal here
// would drop the wizard out of the importing step while the first write is
// still going. The ref settles synchronously where state does not.
const importInFlight = useRef(false);
const runImport = () => {
if (importInFlight.current) return;
const chosen = resolveWizardTarget(target, newProfileId.current, targetProfiles);
if (chosen === undefined) {
setTargetError("That profile is no longer available. Choose where to import these cookies.");
setStep({ step: "configure" });
return;
}
setTargetError(undefined);
importInFlight.current = true;
setStep({ step: "importing" });
void onImport({ sourceProfileDirectory, target: chosen })
.then((outcome) => setStep(outcomeToStep(outcome)))
.catch(() => setStep({ step: "blocked", reason: "readFailed" }))
.finally(() => {
importInFlight.current = false;
});
};
const recheckAfterQuit = () => {
setStep({ step: "checking" });
void onRefreshSource()
.then((refreshed) => {
if (refreshed) {
setSource(refreshed);
setSourceProfileDirectory((current) =>
refreshedSourceProfileDirectory(current, refreshed),
);
}
setStep(refreshedSourceStep(refreshed));
})
.catch(() => setStep({ step: "blocked", reason: "readFailed" }));
};
return (
<Dialog open onOpenChange={(open) => (open || !canCloseWizard(step) ? undefined : onClose())}>
<DialogPopup className="max-w-lg" showCloseButton={canCloseWizard(step)}>
{step.step === "quit" ? (
<QuitStep source={source} onCancel={onClose} onRechecked={recheckAfterQuit} />
) : step.step === "importing" ? (
<ImportingStep />
) : step.step === "checking" ? (
<CheckingStep sourceName={source.name} />
) : step.step === "done" ? (
<DoneStep
{...step}
destinationEnvironmentName={destinationEnvironmentName}
onClose={onClose}
/>
) : step.step === "blocked" ? (
<BlockedStep
source={source}
reason={step.reason}
onClose={onClose}
onRetry={isRetryableReason(step.reason) ? runImport : undefined}
/>
) : (
<ConfigureStep
source={source}
destinationEnvironmentName={destinationEnvironmentName}
targetProfiles={targetProfiles}
canCreateProfile={canCreateProfile}
sourceProfileDirectory={sourceProfileDirectory}
onSourceProfileChange={setSourceProfileDirectory}
target={target}
onTargetChange={(selection) => {
setTarget(selection);
setTargetError(undefined);
}}
targetError={targetError}
onCancel={onClose}
onImport={runImport}
/>
)}
</DialogPopup>
</Dialog>
);
}
function QuitStep({
source,
onCancel,
onRechecked,
}: {
readonly source: BrowserImportSource;
readonly onCancel: () => void;
readonly onRechecked: () => void;
}) {
return (
<>
<DialogHeader>
<DialogTitle>Quit {source.name} to import</DialogTitle>
<DialogDescription>
{source.name} is open, so its cookies can&rsquo;t be read yet. Quit it, then continue.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onCancel}>
Cancel
</Button>
<Button onClick={onRechecked}>I&rsquo;ve quit it</Button>
</DialogFooter>
</>
);
}
/** "5,065 cookies", or "no cookies", or nothing when the store is unreadable. */
function cookieCountLabel(count: number | undefined): string | undefined {
if (count === undefined) return undefined;
if (count === 0) return "no cookies";
return `${count.toLocaleString()} ${count === 1 ? "cookie" : "cookies"}`;
}
function cookieResultCount(count: number): string {
return `${count.toLocaleString()} ${count === 1 ? "cookie" : "cookies"}`;
}
type ConfigureStepProps = {
readonly source: BrowserImportSource;
readonly destinationEnvironmentName: string;
readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
readonly canCreateProfile: boolean;
readonly sourceProfileDirectory: string;
readonly onSourceProfileChange: (directory: string) => void;
readonly target: WizardTargetSelection;
readonly targetError: string | undefined;
readonly onTargetChange: (target: WizardTargetSelection) => void;
readonly onCancel: () => void;
readonly onImport: () => void;
};
function ConfigureStep({
source,
destinationEnvironmentName,
targetProfiles,
canCreateProfile,
sourceProfileDirectory,
onSourceProfileChange,
target,
targetError,
onTargetChange,
onCancel,
onImport,
}: ConfigureStepProps) {
const targetMissing =
target.kind === "existing" &&
!targetProfiles.some((profile) => profile.id === target.profileId);
// The "New profile" tile is unrendered once the cap is reached, so a target
// chosen before that leaves nothing selected in "Into" — say so, the same
// way a vanished existing target is explained.
const targetUncreatable = target.kind === "new" && !canCreateProfile;
const targetFeedback =
targetError ??
(targetMissing
? "That profile is no longer available. Choose where to import these cookies."
: targetUncreatable
? "You've reached the profile limit. Choose an existing profile to import into."
: undefined);
return (
<>
<DialogHeader>
<DialogTitle>Import from {source.name}</DialogTitle>
<DialogDescription>
Choose which cookies to import for {destinationEnvironmentName}.
</DialogDescription>
</DialogHeader>
<DialogPanel>
{/* Side by side when the dialog has room, stacked when it doesn't. */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
<section className="flex-1 space-y-2">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
From
</p>
{source.profiles.map((profile) => (
<SelectableTile
key={profile.directory}
selected={sourceProfileDirectory === profile.directory}
title={profile.name}
subtitle={cookieCountLabel(profile.cookieCount)}
onSelect={() => onSourceProfileChange(profile.directory)}
/>
))}
</section>
<div className="flex shrink-0 items-center justify-center text-muted-foreground">
<ArrowDownIcon className="size-4 sm:hidden" />
<ArrowRightIcon className="hidden size-4 sm:block" />
</div>
<section className="flex-1 space-y-2">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Into
</p>
{canCreateProfile ? (
<SelectableTile
selected={target.kind === "new"}
title="New profile"
subtitle="Created for these cookies"
onSelect={() => onTargetChange({ kind: "new" })}
/>
) : null}
{targetProfiles.map((profile) => (
<SelectableTile
key={profile.id}
selected={target.kind === "existing" && target.profileId === profile.id}
title={profile.name}
subtitle="Existing profile"
onSelect={() => onTargetChange({ kind: "existing", profileId: profile.id })}
/>
))}
</section>
</div>
{targetFeedback ? (
<p role="alert" className="mt-3 text-sm text-destructive">
{targetFeedback}
</p>
) : null}
</DialogPanel>
<DialogFooter>
<Button variant="outline" onClick={onCancel}>
Cancel
</Button>
<Button
disabled={sourceProfileDirectory === "" || targetMissing || targetUncreatable}
onClick={onImport}
>
Import
</Button>
</DialogFooter>
</>
);
}
/** One selectable option: a name, an optional detail line, and a check. */
function SelectableTile({
selected,
title,
subtitle,
onSelect,
}: {
readonly selected: boolean;
readonly title: string;
readonly subtitle?: string | undefined;
readonly onSelect: () => void;
}) {
return (
<button
type="button"
aria-pressed={selected}
onClick={onSelect}
className={cn(
"flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
selected
? "border-primary bg-primary/8"
: "border-border/60 hover:border-border hover:bg-muted/40",
)}
>
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-foreground">{title}</span>
{subtitle ? (
<span className="block truncate text-xs tabular-nums text-muted-foreground">
{subtitle}
</span>
) : null}
</span>
<span
className={cn(
"grid size-4 shrink-0 place-items-center rounded-full border",
selected ? "border-primary bg-primary text-primary-foreground" : "border-input",
)}
>
{selected ? <CheckIcon className="size-2.5" /> : null}
</span>
</button>
);
}
function ImportingStep() {
return (
<>
<DialogHeader>
<DialogTitle>Importing cookies</DialogTitle>
<DialogDescription>This may take a moment.</DialogDescription>
</DialogHeader>
<DialogPanel className="flex items-center gap-3 py-6">
<Spinner className="size-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Importing…</span>
</DialogPanel>
</>
);
}
function CheckingStep({ sourceName }: { readonly sourceName: string }) {
return (
<>
<DialogHeader>
<DialogTitle>Checking {sourceName}</DialogTitle>
<DialogDescription>Checking whether the browser has closed.</DialogDescription>
</DialogHeader>
<DialogPanel className="flex items-center gap-3 py-6">
<Spinner className="size-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Checking…</span>
</DialogPanel>
</>
);
}
function DoneStep({
imported,
skipped,
skippedDomains,
targetName,
destinationEnvironmentName,
onClose,
}: {
readonly imported: number;
readonly skipped: number;
readonly skippedDomains: ReadonlyArray<string>;
readonly targetName: string;
readonly destinationEnvironmentName: string;
readonly onClose: () => void;
}) {
return (
<>
<DialogHeader>
<DialogTitle>
{imported > 0
? `Imported ${cookieResultCount(imported)}`
: skipped > 0
? `Skipped ${cookieResultCount(skipped)}`
: "No cookies found"}
</DialogTitle>
<DialogDescription>
{imported > 0
? `Added to ${targetName} for ${destinationEnvironmentName}.${skipped > 0 ? ` ${cookieResultCount(skipped)} skipped.` : ""}`
: skipped > 0
? `No cookies were imported for ${destinationEnvironmentName}.`
: `There were no cookies to import for ${destinationEnvironmentName}.`}
</DialogDescription>
</DialogHeader>
{skippedDomains.length > 0 ? (
<DialogPanel>
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Skipped
</p>
<p className="mt-1 text-sm text-foreground">{formatSkippedDomains(skippedDomains)}</p>
</DialogPanel>
) : null}
<DialogFooter>
<DialogClose render={<Button />} onClick={onClose}>
Done
</DialogClose>
</DialogFooter>
</>
);
}
function BlockedStep({
source,
reason,
onClose,
onRetry,
}: {
readonly source: BrowserImportSource;
readonly reason: keyof typeof BROWSER_IMPORT_FAILURE_COPY;
readonly onClose: () => void;
readonly onRetry: (() => void) | undefined;
}) {
return (
<>
<DialogHeader>
<DialogTitle>Couldn&rsquo;t import from {source.name}</DialogTitle>
<DialogDescription>{BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Close
</Button>
{onRetry ? <Button onClick={onRetry}>Try again</Button> : null}
</DialogFooter>
</>
);
}
@@ -1,7 +1,11 @@
import { describe, expect, it, vi } from "vite-plus/test";
import type { EnvironmentId } from "@t3tools/contracts";
import { browserProfileRemovalAvailable, clearBrowserProfileData } from "./IntegrationsSettings";
import {
browserProfileRemovalAvailable,
clearBrowserProfileData,
importFailureReason,
} from "./IntegrationsSettings";
const environmentId = "environment-a" as EnvironmentId;
const secondEnvironmentId = "environment-b" as EnvironmentId;
@@ -72,3 +76,25 @@ describe("browserProfileRemovalAvailable", () => {
expect(browserProfileRemovalAvailable(false, true, 1)).toBe(false);
});
});
// Mirrors `BrowserImportFailedError.message`, which IPC flattens to a string
// before the renderer sees it.
const failure = (reason: string) => ({
message: `Importing cookies from safari failed: ${reason}.`,
});
describe("importFailureReason", () => {
it("recovers the reason token from the flattened message", () => {
expect(importFailureReason(failure("browserRunning"))).toBe("browserRunning");
expect(importFailureReason(failure("readFailed"))).toBe("readFailed");
// A settings write that fails after the cookies landed is its own case,
// not a read failure over a database that was in fact read.
expect(importFailureReason(failure("profileNotSaved"))).toBe("profileNotSaved");
expect(importFailureReason(failure("profileLimitReached"))).toBe("profileLimitReached");
});
it("falls back to readFailed for anything it cannot classify", () => {
expect(importFailureReason(new Error("something else entirely"))).toBe("readFailed");
expect(importFailureReason(undefined)).toBe("readFailed");
});
});
@@ -7,6 +7,7 @@
* @module IntegrationsSettings
*/
import {
BrowserImportFailureReason,
BROWSER_PROFILE_MAX_COUNT,
type BrowserLinkTarget,
type BrowserProfile,
@@ -29,21 +30,32 @@ import {
findBrowserProfile,
isBuiltInBrowserProfileId,
resolveBrowserProfiles,
type BrowserImportSource,
type PreviewAppearancePreference,
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
import { InfoIcon, Plus as PlusIcon, Trash2 as Trash2Icon } from "lucide-react";
import { useState } from "react";
import type { ReactNode } from "react";
import { InfoIcon, MoreVertical, Plus as PlusIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
import { resolveEnvironmentOptionLabel } from "~/components/BranchToolbar.logic";
import { previewBridge } from "~/components/preview/previewBridge";
import { cn, randomUUID } from "~/lib/utils";
import { useEnvironments } from "~/state/environments";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import { isElectron } from "../../env";
import { Badge } from "../ui/badge";
import {
Menu,
MenuGroup,
MenuGroupLabel,
MenuItem,
MenuPopup,
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
import { toastManager } from "../ui/toast";
import {
AlertDialog,
AlertDialogClose,
@@ -69,6 +81,7 @@ import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
getClientSettings,
persistClientSettingsUpdate,
useClientSettings,
useClientSettingsHydrated,
usePrimarySettings,
@@ -81,8 +94,9 @@ import {
SettingsRow,
SettingsSection,
} from "./settingsLayout";
import { ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import { searchableSetting } from "./settingsSearch";
import { BrowserImportWizard, type WizardTarget } from "./BrowserImportWizard";
import type { ImportOutcome } from "./browserImportWizard.logic";
const FILL_VALUE = "fill";
const RESPONSIVE_VALUE = "responsive";
@@ -133,6 +147,27 @@ const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> =
const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
/**
* IPC flattens the failure to its message, so the reason token travels inside
* it. Anything unrecognised reads as a plain read failure rather than leaking
* the raw message into a toast.
*/
/** Thrown from the post-import settings updater when the cap was hit meanwhile. */
class ProfileLimitReachedError extends Error {
constructor() {
super("Browser profile limit reached.");
this.name = "ProfileLimitReachedError";
}
}
export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {
const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
return (
BrowserImportFailureReason.literals.find((reason) => message.includes(`failed: ${reason}.`)) ??
"readFailed"
);
};
const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
if (viewport._tag === "fill") return FILL_VALUE;
if (
@@ -614,17 +649,34 @@ function DesktopOnlyBrowserDefaults({ children }: { readonly children: ReactNode
}
/**
* Create, rename, and remove browser profiles.
* Profile list, its header menu, and the import flow.
*
* Built-ins render without controls: they are synthesized rather than stored,
* so there is nothing to rename and removing them would strand every tab that
* opened under them.
* One menu creates profiles and imports into them, because the two are the
* same decision from the user's side: "I want a profile that has my Helium
* logins in it". Import targets include "New profile" so that case does not
* require creating one first and then finding a second control.
*
* Built-ins render without a rename field: they are synthesized rather than
* stored, so there is nothing to rename and removing them would strand every
* tab that opened under them.
*
* Sources are listed lazily on open: detection touches the other browser's
* files, and the answer changes while the app is running (quitting the browser
* clears `browserRunning`), so a value cached at mount would go stale.
*/
function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
const userProfiles = useClientSettings((settings) => settings.browserProfiles);
const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
const settingsHydrated = useClientSettingsHydrated();
const updateSettings = useUpdatePrimarySettings();
const { environments, isReady: environmentsReady } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
const [importSession, setImportSession] = useState<{
readonly source: BrowserImportSource;
readonly environmentId: EnvironmentId;
readonly environmentName: string;
} | null>(null);
const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
@@ -633,25 +685,36 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
environmentsReady,
environments.length,
);
const importInFlightRef = useRef(false);
const [importInFlight, setImportInFlight] = useState(false);
const profileWritesDisabled = disabled || !settingsHydrated;
const addProfile = () => {
if (!settingsHydrated) return;
const profiles = resolveBrowserProfiles(userProfiles);
// Incognito is deliberately not a row — it holds nothing to manage — so the
// default has to resolve against the list that renders. A stored
// `browserDefaultProfileId` of "incognito" would otherwise leave the section
// with no Default badge at all.
const listedProfiles = profiles.filter((profile) => profile.kind !== "incognito");
const resolvedDefaultId =
findBrowserProfile(listedProfiles, defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID;
const createProfile = (baseName: string) => {
if (!settingsHydrated || importInFlightRef.current) return undefined;
const currentProfiles = getClientSettings().browserProfiles;
if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return;
const taken = new Set(resolveBrowserProfiles(currentProfiles).map((profile) => profile.name));
let name = "New profile";
for (let index = 2; taken.has(name); index += 1) name = `New profile ${index}`;
updateSettings({
browserProfiles: [
...currentProfiles,
{ id: `profile-${randomUUID()}`, name, kind: "persistent" as const },
],
});
// Checked against the live settings, not the rendered list: two clicks
// before a re-render would otherwise both pass the disabled control.
if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return undefined;
const resolvedProfiles = resolveBrowserProfiles(currentProfiles);
const taken = new Set(resolvedProfiles.map((profile) => profile.name));
let name = baseName;
for (let index = 2; taken.has(name); index += 1) name = `${baseName} ${index}`;
const profile = { id: `profile-${randomUUID()}`, name, kind: "persistent" as const };
updateSettings({ browserProfiles: [...currentProfiles, profile] });
return profile;
};
const renameProfile = (id: string, next: string) => {
if (!settingsHydrated) return;
if (!settingsHydrated || importInFlightRef.current) return;
const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
if (name === "") return;
const currentProfiles = getClientSettings().browserProfiles;
@@ -662,8 +725,31 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
});
};
const clearProfileData = (id: string, name: string) => {
if (!settingsHydrated || importInFlightRef.current) return;
if (!previewBridge || !environmentsReady || environments.length === 0) {
toastManager.add({
type: "error",
title: `Could not clear ${name}'s data`,
description: "You're not connected to a server yet.",
});
return;
}
void clearBrowserProfileData(
previewBridge,
environments.map((environment) => environment.environmentId),
id,
)
.then(() => {
toastManager.add({ type: "success", title: `Cleared ${name}'s cookies and cache` });
})
.catch(() => {
toastManager.add({ type: "error", title: `Could not clear ${name}'s data` });
});
};
const removeProfile = async (id: string) => {
if (!settingsHydrated) return;
if (!settingsHydrated || importInFlightRef.current) return;
if (!removalAvailable) {
setProfileRemovalError("Connect to an environment before removing this profile.");
return;
@@ -695,92 +781,330 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
setProfilePendingRemoval(null);
};
// A browser that is not on this machine, or that this platform cannot import
// from at all, is left out rather than listed as a dead row: there is nothing
// to act on, and the menu is a list of things you can import from. Every
// other unavailable reason stays, since each names a step the user can take.
const importableSources = (sources ?? []).filter(
(source) =>
source.unavailable !== "notInstalled" && source.unavailable !== "unsupportedPlatform",
);
// Refreshed without blanking the last result: the menu shows the cached list
// straight away so it doesn't reflow on open, and the source list is stable
// (names only) since choosing what to import happens in the wizard, not here.
const loadSources = useCallback(() => {
if (!previewBridge) return;
void previewBridge
.listBrowserImportSources()
.then(setSources)
.catch(() => setSources((previous) => previous ?? []));
}, []);
// Loaded once so the first open is instant instead of flashing a spinner.
useEffect(() => {
loadSources();
}, [loadSources]);
// Runs one import for the wizard. A new profile is registered only once the
// import succeeds — the cookies land in its partition first — so a blocked
// attempt never leaves an empty profile behind.
const runWizardImport = async (
source: BrowserImportSource,
environmentId: EnvironmentId,
input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
): Promise<ImportOutcome> => {
if (!previewBridge) return { kind: "blocked", reason: "sessionUnavailable" };
if (!settingsHydrated) return { kind: "blocked", reason: "sessionUnavailable" };
if (
input.target.kind === "existing" &&
!resolveBrowserProfiles(getClientSettings().browserProfiles).some(
(profile) => profile.id === input.target.profileId,
)
) {
return { kind: "blocked", reason: "readFailed" };
}
if (importInFlightRef.current) return { kind: "blocked", reason: "readFailed" };
importInFlightRef.current = true;
setImportInFlight(true);
try {
const result = await previewBridge.importBrowserCookies({
environmentId,
sourceId: source.id,
sourceProfileDirectory: input.sourceProfileDirectory,
targetProfileId: input.target.profileId,
});
if (
input.target.kind === "existing" &&
!resolveBrowserProfiles(getClientSettings().browserProfiles).some(
(profile) => profile.id === input.target.profileId,
)
) {
return { kind: "blocked", reason: "readFailed" };
}
let targetName: string;
if (input.target.kind === "new") {
// Registered only when something actually came over: an import that
// found no cookies should not leave a new, empty profile behind.
if (result.imported > 0) {
try {
const persisted = await persistClientSettingsUpdate((current) => {
const existing = current.browserProfiles.find(
(profile) => profile.id === input.target.profileId,
);
if (existing) return current;
// The wizard refuses a new target at the cap, but the cap can be
// reached while the import runs; the updater sees the newest
// settings, so this is the check that holds.
if (current.browserProfiles.length >= BROWSER_PROFILE_MAX_COUNT) {
throw new ProfileLimitReachedError();
}
const taken = new Set(
resolveBrowserProfiles(current.browserProfiles).map((profile) => profile.name),
);
let name = source.name;
for (let index = 2; taken.has(name); index += 1) name = `${source.name} ${index}`;
return {
...current,
browserProfiles: [
...current.browserProfiles,
{ id: input.target.profileId, name, kind: "persistent" as const },
],
};
});
targetName =
persisted.browserProfiles.find((profile) => profile.id === input.target.profileId)
?.name ?? source.name;
} catch (cause) {
// This target id belongs only to the attempted new profile. Clear
// its partition so a failed registration cannot strand imported
// cookies behind a profile that disappears on restart.
await clearBrowserProfileData(
previewBridge,
[environmentId],
input.target.profileId,
).catch(() => undefined);
// Not a read failure: the cookies came over and were cleared again
// because the profile could not be kept. Name that, in the same
// token form `importFailureReason` recovers from a bridge error.
const reason =
cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";
throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
}
} else {
targetName = source.name;
}
} else {
targetName = input.target.name;
}
return {
kind: "imported",
imported: result.imported,
skipped: result.skipped,
skippedDomains: result.skippedDomains,
targetName,
};
} catch (cause) {
return { kind: "blocked", reason: importFailureReason(cause) };
} finally {
importInFlightRef.current = false;
setImportInFlight(false);
}
};
// Re-checks a source's availability after the user quits the browser, and
// keeps the cached list in step so the menu reflects it too.
const refreshImportSource = async (
sourceId: BrowserImportSource["id"],
): Promise<BrowserImportSource | undefined> => {
if (!previewBridge) return undefined;
try {
const latest = await previewBridge.listBrowserImportSources();
setSources(latest);
return latest.find((source) => source.id === sourceId);
} catch {
return undefined;
}
};
const atProfileLimit = userProfiles.length >= BROWSER_PROFILE_MAX_COUNT;
return (
<SettingsRow
{...searchableSetting("browser-profiles")}
description="Each profile keeps its own cookies and logins, so a tab opened under one can't see another's. Incognito discards everything when the app closes."
description="Each profile has its own cookies and logins, so you can stay signed in to different accounts at once."
control={
<Button
size="sm"
variant="outline"
disabled={profileWritesDisabled || userProfiles.length >= BROWSER_PROFILE_MAX_COUNT}
onClick={addProfile}
>
<PlusIcon />
Add profile
</Button>
<Menu onOpenChange={(open) => open && loadSources()}>
<MenuTrigger
render={
<Button
size="sm"
variant="outline"
disabled={profileWritesDisabled || importInFlight}
/>
}
>
<PlusIcon />
Add profile
</MenuTrigger>
<MenuPopup align="end" className="min-w-56">
<MenuItem
disabled={!settingsHydrated || atProfileLimit}
onClick={() => createProfile("New profile")}
>
Blank profile
</MenuItem>
{atProfileLimit ? (
<MenuItem disabled>You&rsquo;ve reached the profile limit</MenuItem>
) : null}
<MenuSeparator />
<MenuGroup>
<MenuGroupLabel>Import from</MenuGroupLabel>
{sources === null ? (
<MenuItem disabled>Looking for browsers…</MenuItem>
) : importableSources.length === 0 ? (
<MenuItem disabled>No supported browsers found</MenuItem>
) : (
// Every source is a plain row — running, needs-permission and
// ready all look the same here. The wizard picks up whatever
// state the source is in and walks the user forward from there.
<>
{importableSources.map((source) => (
<MenuItem
key={source.id}
disabled={!settingsHydrated || primaryEnvironment == null}
onClick={() => {
if (!settingsHydrated || primaryEnvironment == null) return;
setImportSession({
source,
environmentId: primaryEnvironment.environmentId,
environmentName: resolveEnvironmentOptionLabel({
isPrimary: true,
environmentId: primaryEnvironment.environmentId,
runtimeLabel: primaryEnvironment.label,
}),
});
}}
>
{source.name}
</MenuItem>
))}
{primaryEnvironment == null ? (
<MenuItem disabled>Connect to an environment to import cookies</MenuItem>
) : null}
</>
)}
</MenuGroup>
</MenuPopup>
</Menu>
}
>
{/*
Each profile is its own bounded row, and the list carries the bottom
spacing `SettingsRow` leaves to its children (`pt-3 pb-1`). Bare rows
stack on narrow viewports with a larger gap inside a row than between
rows, which reads as the remove button belonging to the profile below.
The bordered container groups rows unambiguously at any width, and
carries the bottom spacing `SettingsRow` leaves to its children
(`pt-3 pb-1`).
*/}
<div className="mt-2 space-y-1 pb-2">
{resolveBrowserProfiles(userProfiles).map((profile) => {
<div className="mt-2 mb-2 overflow-hidden rounded-lg border border-border/60">
{listedProfiles.map((profile, index) => {
const builtIn = isBuiltInBrowserProfileId(profile.id);
const isDefault = profile.id === resolvedDefaultId;
return (
<div
key={profile.id}
className={cn(
ITEM_ROW_INNER_CLASSNAME,
"rounded-lg border border-border/60 px-3 py-2",
"flex items-center gap-3 px-3 py-2",
index > 0 && "border-t border-border/60",
)}
>
{builtIn ? (
// Dimmed here rather than on the list, which is the only
// content in the row without a disabled treatment of its own:
// a wrapper-level dim would stack with the rename field's and
// the remove button's, landing them near 0.41 while every
// other disabled control in the block sits at 0.64.
<span
className={cn(
"flex min-w-0 items-center gap-2 text-sm text-foreground",
profileWritesDisabled && "opacity-64",
)}
>
{profile.name}
<Badge variant="outline">
{profile.kind === "incognito" ? "Ephemeral" : "Built-in"}
</Badge>
</span>
) : (
<DraftInput
nativeInput
size="sm"
className="w-full sm:w-64"
aria-label={`Rename ${profile.name}`}
disabled={profileWritesDisabled}
maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
value={profile.name}
onCommit={(next) => renameProfile(profile.id, next)}
/>
)}
{builtIn ? null : (
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex" {...(!removalAvailable ? { tabIndex: 0 } : {})}>
<Button
size="icon-xs"
variant="ghost-muted"
disabled={profileWritesDisabled || !removalAvailable}
aria-label={`Remove ${profile.name}`}
onClick={() => setProfilePendingRemoval(profile)}
>
<Trash2Icon />
</Button>
</span>
}
<span className="flex min-w-0 flex-1 items-center gap-2">
{builtIn ? (
// Dimmed here rather than on the table: a wrapper-level dim
// stacks with the rename field's and the row menu button's
// own, landing them near 0.41 while every other disabled
// control in the block sits at 0.64.
<span
className={cn(
"truncate text-sm text-foreground",
profileWritesDisabled && "opacity-64",
)}
>
{profile.name}
</span>
) : (
<DraftInput
nativeInput
size="sm"
className="w-full max-w-56"
aria-label={`Rename ${profile.name}`}
disabled={profileWritesDisabled || importInFlight}
maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
value={profile.name}
onCommit={(next) => renameProfile(profile.id, next)}
/>
<TooltipPopup side="top">
{removalAvailable
? "Remove profile and its data"
: "Connect to an environment to remove this profile"}
</TooltipPopup>
</Tooltip>
)}
)}
{/*
Dimmed with the rest of the row: a `Badge` has no disabled
treatment of its own, so a solid `bg-primary` pill would
otherwise sit at full strength beside a name, rename field
and menu button that are all at 0.64.
*/}
{isDefault ? (
<Badge className={cn(profileWritesDisabled && "opacity-64")}>Default</Badge>
) : null}
</span>
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="ghost-muted"
disabled={profileWritesDisabled || importInFlight}
aria-label={`${profile.name} options`}
/>
}
>
<MoreVertical />
</MenuTrigger>
<MenuPopup align="end" className="min-w-44">
<MenuItem
disabled={!settingsHydrated || isDefault}
onClick={() => {
if (settingsHydrated) {
updateSettings({ browserDefaultProfileId: profile.id });
}
}}
>
Set as default
</MenuItem>
<MenuItem
disabled={!settingsHydrated || !removalAvailable}
onClick={() => clearProfileData(profile.id, profile.name)}
>
Clear cookies and cache
</MenuItem>
{builtIn ? null : (
<MenuItem
variant="destructive"
disabled={!settingsHydrated || !removalAvailable}
onClick={() => {
if (settingsHydrated) setProfilePendingRemoval(profile);
}}
>
Remove profile and data
</MenuItem>
)}
{!removalAvailable ? (
<>
<MenuSeparator />
<MenuItem disabled>
{environmentsReady
? "Connect to an environment to clear profile data"
: "Checking environments…"}
</MenuItem>
</>
) : null}
</MenuPopup>
</Menu>
</div>
);
})}
@@ -798,8 +1122,8 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
<AlertDialogHeader>
<AlertDialogTitle>Remove “{profilePendingRemoval?.name}”?</AlertDialogTitle>
<AlertDialogDescription>
Its cookies, logins, and cache are deleted with it. Tabs already open in this profile
stay open until you close them.
Its cookies and logins are deleted. Tabs already open in this profile stay open until
you close them.
</AlertDialogDescription>
{profileRemovalError ? (
<p aria-live="polite" className="text-sm text-destructive">
@@ -833,86 +1157,29 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
{importSession ? (
<BrowserImportWizard
source={importSession.source}
destinationEnvironmentName={importSession.environmentName}
targetProfiles={listedProfiles.map((profile) => ({ id: profile.id, name: profile.name }))}
canCreateProfile={settingsHydrated && !atProfileLimit}
onImport={(input) =>
runWizardImport(importSession.source, importSession.environmentId, input)
}
onRefreshSource={() => refreshImportSource(importSession.source.id)}
onClose={() => setImportSession(null)}
/>
) : null}
</SettingsRow>
);
}
function BrowserDefaultProfileSetting({ disabled }: { readonly disabled: boolean }) {
const userProfiles = useClientSettings((settings) => settings.browserProfiles);
const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
const settingsHydrated = useClientSettingsHydrated();
const updateSettings = useUpdatePrimarySettings();
const profileWritesDisabled = disabled || !settingsHydrated;
// Incognito is deliberately absent: as a default it would open every tab
// into storage that is discarded on close.
const profiles = resolveBrowserProfiles(userProfiles).filter(
(profile) => profile.kind !== "incognito",
);
const selected = findBrowserProfile(profiles, defaultProfileId) ?? profiles[0];
return (
<SettingsRow
{...searchableSetting("browser-default-profile")}
description="Profile new browser tabs open under, including tabs an agent opens."
resetAction={
!profileWritesDisabled && defaultProfileId !== DEFAULT_BROWSER_PROFILE_ID ? (
<SettingResetButton
label="default browser profile"
onClick={() => {
if (settingsHydrated) {
updateSettings({ browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID });
}
}}
/>
) : null
}
control={
<Select
disabled={profileWritesDisabled}
value={selected?.id ?? DEFAULT_BROWSER_PROFILE_ID}
onValueChange={(value) => {
if (settingsHydrated && value !== null) {
updateSettings({ browserDefaultProfileId: value });
}
}}
>
<SelectTrigger size="sm" className="w-full sm:w-44" aria-label="Default browser profile">
<SelectValue>{selected?.name ?? "Default"}</SelectValue>
</SelectTrigger>
{/*
Capped and truncated like the tab menu's profile list: names are
user-supplied and run to 48 characters, which would otherwise
widen the popup to fit the longest one. The cap goes on the glass
shell (`popupClassName`), and the list fills that shell so it is
never narrower than the trigger it opens from — the same floor
every other settings select keeps. `ItemText` renders a block, so
the label must be a block too for `truncate` to apply.
*/}
<SelectPopup
align="end"
alignItemWithTrigger={false}
popupClassName="max-w-64"
className="w-full"
>
{profiles.map((profile) => (
<SelectItem hideIndicator key={profile.id} value={profile.id}>
<span className="block min-w-0 truncate">{profile.name}</span>
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
);
}
export function IntegrationsSettingsPanel() {
// Client-local preview defaults are editable only where the preview exists.
const previewDefaultsDisabled = !isElectron;
const previewDefaults = (
<>
<BrowserProfilesSetting disabled={previewDefaultsDisabled} />
<BrowserDefaultProfileSetting disabled={previewDefaultsDisabled} />
<BrowserViewportSetting disabled={previewDefaultsDisabled} />
<BrowserZoomSetting disabled={previewDefaultsDisabled} />
<BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vite-plus/test";
import type { BrowserImportSource } from "@t3tools/contracts";
import {
canCloseWizard,
initialWizardStep,
initialTargetSelection,
isRetryableReason,
formatSkippedDomains,
outcomeToStep,
refreshedSourceProfileDirectory,
refreshedSourceStep,
resolveWizardTarget,
} from "./browserImportWizard.logic";
describe("wizard target selection", () => {
it("treats an existing profile whose id is new as an existing target", () => {
const profiles = [{ id: "new", name: "Existing new" }];
const selection = initialTargetSelection(false, profiles);
expect(selection).toEqual({ kind: "existing", profileId: "new" });
expect(resolveWizardTarget(selection, "generated", profiles)).toEqual({
kind: "existing",
profileId: "new",
name: "Existing new",
});
});
it("rejects an existing target that is no longer listed", () => {
expect(
resolveWizardTarget({ kind: "existing", profileId: "removed" }, "generated", [
{ id: "default", name: "Default" },
]),
).toBeUndefined();
});
});
const source = (over: Partial<BrowserImportSource> = {}): BrowserImportSource => ({
id: "helium",
name: "Helium",
profiles: [{ directory: "Default", name: "You" }],
...over,
});
describe("initialWizardStep", () => {
it("opens on the quit screen when the browser is running", () => {
expect(initialWizardStep(source({ unavailable: "browserRunning" }))).toEqual({ step: "quit" });
});
it("opens on configure when the source is ready", () => {
expect(initialWizardStep(source())).toEqual({ step: "configure" });
});
it("blocks on a reason nothing local can fix", () => {
expect(initialWizardStep(source({ unavailable: "unsupportedPlatform" }))).toEqual({
step: "blocked",
reason: "unsupportedPlatform",
});
});
it("blocks a ready source that reports no importable profiles", () => {
expect(initialWizardStep(source({ profiles: [] }))).toEqual({
step: "blocked",
reason: "unknownSourceProfile",
});
});
it("handles source availability before checking its profiles", () => {
expect(
initialWizardStep(source({ profiles: [], unavailable: "needsKeychainApproval" })),
).toEqual({ step: "blocked", reason: "needsKeychainApproval" });
});
});
describe("canCloseWizard", () => {
it("keeps the wizard open while an import writes its target profile", () => {
expect(canCloseWizard({ step: "importing" })).toBe(false);
expect(canCloseWizard({ step: "configure" })).toBe(true);
expect(canCloseWizard({ step: "blocked", reason: "readFailed" })).toBe(true);
});
});
describe("outcomeToStep", () => {
it("lands on done after a successful import", () => {
expect(
outcomeToStep({
kind: "imported",
imported: 12,
skipped: 3,
skippedDomains: ["example.com"],
targetName: "Work",
}),
).toEqual({
step: "done",
imported: 12,
skipped: 3,
skippedDomains: ["example.com"],
targetName: "Work",
});
});
it("routes a reopened browser back to the quit screen", () => {
expect(outcomeToStep({ kind: "blocked", reason: "browserRunning" })).toEqual({ step: "quit" });
});
it("surfaces every other failure on the blocked screen", () => {
expect(outcomeToStep({ kind: "blocked", reason: "readFailed" })).toEqual({
step: "blocked",
reason: "readFailed",
});
});
});
describe("refreshedSourceStep", () => {
it("moves to configure once a quit browser frees its cookies", () => {
expect(refreshedSourceStep(source())).toEqual({ step: "configure" });
});
it("stays on quit while the browser is still running", () => {
expect(refreshedSourceStep(source({ unavailable: "browserRunning" }))).toEqual({
step: "quit",
});
});
it("blocks when the source vanished from the list", () => {
expect(refreshedSourceStep(undefined)).toEqual({ step: "blocked", reason: "unknownSource" });
});
it("blocks when the refreshed source has no profiles", () => {
expect(refreshedSourceStep(source({ profiles: [] }))).toEqual({
step: "blocked",
reason: "unknownSourceProfile",
});
});
});
describe("refreshedSourceProfileDirectory", () => {
const refreshed = source({
profiles: [
{ directory: "Default", name: "Personal" },
{ directory: "Profile 2", name: "Work" },
],
});
it("preserves a selected non-first profile after the browser quits", () => {
expect(refreshedSourceProfileDirectory("Profile 2", refreshed)).toBe("Profile 2");
});
it("falls back only when the old profile vanished and clears an empty result", () => {
expect(refreshedSourceProfileDirectory("Removed", refreshed)).toBe("Default");
expect(refreshedSourceProfileDirectory("Removed", source({ profiles: [] }))).toBe("");
});
});
describe("isRetryableReason", () => {
it("offers a retry for failures a second attempt can clear", () => {
expect(isRetryableReason("needsKeychainApproval")).toBe(true);
expect(isRetryableReason("readFailed")).toBe(true);
});
it("does not offer a retry for a permanent failure", () => {
expect(isRetryableReason("unsupportedPlatform")).toBe(false);
expect(isRetryableReason("unknownSourceProfile")).toBe(false);
// Retrying the same new-profile import cannot lower the profile count.
expect(isRetryableReason("profileLimitReached")).toBe(false);
});
it("offers a retry once the user has signed in to create the missing key", () => {
// The blocked copy tells the user to sign in and retry, so the screen
// has to offer the retry it asks for.
expect(isRetryableReason("keychainItemMissing")).toBe(true);
});
it("offers a retry when the cookies landed but the new profile was not saved", () => {
expect(isRetryableReason("profileNotSaved")).toBe(true);
});
});
describe("formatSkippedDomains", () => {
it("joins a short list naturally", () => {
expect(formatSkippedDomains([])).toBe("");
expect(formatSkippedDomains(["a.com"])).toBe("a.com");
expect(formatSkippedDomains(["a.com", "b.com"])).toBe("a.com and b.com");
expect(formatSkippedDomains(["a.com", "b.com", "c.com"])).toBe("a.com, b.com and c.com");
});
it("summarizes a long list", () => {
expect(formatSkippedDomains(["a.com", "b.com", "c.com", "d.com", "e.com"])).toBe(
"a.com, b.com, c.com and 2 more",
);
});
});
@@ -0,0 +1,154 @@
import type { BrowserImportFailureReason, BrowserImportSource } from "@t3tools/contracts";
export interface WizardTargetProfile {
readonly id: string;
readonly name: string;
}
export type WizardTarget =
| { readonly kind: "new"; readonly profileId: string }
| { readonly kind: "existing"; readonly profileId: string; readonly name: string };
export type WizardTargetSelection =
| { readonly kind: "new" }
| { readonly kind: "existing"; readonly profileId: string };
export function initialTargetSelection(
canCreateProfile: boolean,
targetProfiles: ReadonlyArray<WizardTargetProfile>,
): WizardTargetSelection {
if (canCreateProfile) return { kind: "new" };
const first = targetProfiles[0];
return first ? { kind: "existing", profileId: first.id } : { kind: "new" };
}
export function resolveWizardTarget(
selection: WizardTargetSelection,
newProfileId: string,
targetProfiles: ReadonlyArray<WizardTargetProfile>,
): WizardTarget | undefined {
if (selection.kind === "new") return { kind: "new", profileId: newProfileId };
const profile = targetProfiles.find((candidate) => candidate.id === selection.profileId);
if (profile === undefined) return undefined;
return {
kind: "existing",
profileId: selection.profileId,
name: profile.name,
};
}
/**
* What the import wizard produces once it has actually tried to import. The
* parent runs the import and classifies the result; the wizard only reacts to
* it, which keeps the step transitions pure and testable.
*/
export type ImportOutcome =
| {
readonly kind: "imported";
readonly imported: number;
readonly skipped: number;
readonly skippedDomains: ReadonlyArray<string>;
readonly targetName: string;
}
| { readonly kind: "blocked"; readonly reason: BrowserImportFailureReason };
/**
* The wizard's screens. Every one is a place the user can act from — there are
* no dead ends. `blocked` covers the reasons no local step recovers.
*/
export type WizardStep =
| { readonly step: "quit" }
| { readonly step: "configure" }
| { readonly step: "checking" }
| { readonly step: "importing" }
| {
readonly step: "done";
readonly imported: number;
readonly skipped: number;
readonly skippedDomains: ReadonlyArray<string>;
readonly targetName: string;
}
| { readonly step: "blocked"; readonly reason: BrowserImportFailureReason };
/** The import owns its target partition until the write finishes. */
export function canCloseWizard(step: WizardStep): boolean {
return step.step !== "importing";
}
/**
* Where the wizard opens for a source. A running browser is the one thing we
* know up front, from the source listing; everything else is discovered by
* trying, so the wizard starts by letting the user choose what to import.
*/
export function initialWizardStep(source: BrowserImportSource): WizardStep {
if (source.unavailable === "browserRunning") return { step: "quit" };
if (source.unavailable !== undefined) return { step: "blocked", reason: source.unavailable };
if (source.profiles.length === 0) return { step: "blocked", reason: "unknownSourceProfile" };
return { step: "configure" };
}
/** Where an attempted import lands the wizard, by how it turned out. */
export function outcomeToStep(outcome: ImportOutcome): WizardStep {
if (outcome.kind === "imported") {
return {
step: "done",
imported: outcome.imported,
skipped: outcome.skipped,
skippedDomains: outcome.skippedDomains,
targetName: outcome.targetName,
};
}
// A browser that reopened mid-import routes back to the quit screen; every
// other failure surfaces on the blocked screen, which offers a retry when
// one could help.
if (outcome.reason === "browserRunning") return { step: "quit" };
return { step: "blocked", reason: outcome.reason };
}
/** Where a fresh availability check lands the wizard after the user quits. */
export function refreshedSourceStep(source: BrowserImportSource | undefined): WizardStep {
if (source === undefined) return { step: "blocked", reason: "unknownSource" };
return initialWizardStep(source);
}
/** Preserve the chosen source profile when a post-quit refresh still lists it. */
export function refreshedSourceProfileDirectory(
currentDirectory: string,
source: BrowserImportSource,
): string {
if (source.profiles.some((profile) => profile.directory === currentDirectory)) {
return currentDirectory;
}
return source.profiles[0]?.directory ?? "";
}
/**
* Whether retrying could clear a failure. The keychain prompt can be approved
* on a second try, a missing key appears once the user signs in to the
* browser (which is what its copy asks for), and a read or session error may
* be transient; an unsupported browser will not change, so it gets no retry
* button.
*/
export function isRetryableReason(reason: BrowserImportFailureReason): boolean {
switch (reason) {
case "needsKeychainApproval":
case "keychainItemMissing":
case "readFailed":
case "sessionUnavailable":
case "profileNotSaved":
return true;
default:
return false;
}
}
/**
* Names the sites whose cookies were skipped: "example.com and google.com",
* or "a, b, c and 4 more" past a few, so the line stays short.
*/
export function formatSkippedDomains(domains: ReadonlyArray<string>): string {
if (domains.length === 0) return "";
if (domains.length === 1) return domains[0]!;
if (domains.length <= 3) return `${domains.slice(0, -1).join(", ")} and ${domains.at(-1)}`;
return `${domains.slice(0, 3).join(", ")} and ${domains.length - 3} more`;
}
@@ -217,4 +217,12 @@ describe("searchSettings", () => {
});
expect(searchSettings("external links")[0]).toMatchObject({ id: "browser-link-target" });
});
it("finds the default browser profile action in the profiles list", () => {
expect(searchSettings("default profile")[0]).toMatchObject({
id: "browser-default-profile",
to: "/settings/integrations",
targetId: "browser-profiles",
});
});
});
@@ -347,7 +347,7 @@ export const SETTINGS_SEARCH_ITEMS = [
id: "browser-default-profile",
title: "Default browser profile",
to: "/settings/integrations",
targetId: "browser",
targetId: "browser-profiles",
},
{
id: "browser-default-viewport",
+152 -2
View File
@@ -4,9 +4,159 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import { describe, expect, it } from "vite-plus/test";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { mergeEnvironmentSettings, resolveEnvironmentIdentificationMode } from "./useSettings";
import {
__resetClientSettingsPersistenceForTests,
__setClientSettingsForTests,
getClientSettings,
mergeEnvironmentSettings,
persistClientSettingsPatch,
persistClientSettingsUpdate,
resolveEnvironmentIdentificationMode,
} from "./useSettings";
beforeEach(() => {
__resetClientSettingsPersistenceForTests();
});
describe("persistClientSettingsUpdate", () => {
it("publishes the update only after persistence succeeds", async () => {
let finishPersistence!: () => void;
const persistence = new Promise<void>((resolve) => {
finishPersistence = resolve;
});
const setClientSettings = vi.fn(() => persistence);
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
const pending = persistClientSettingsUpdate(
(current) => ({
...current,
timestampFormat: "12-hour",
}),
setClientSettings,
);
expect(getClientSettings().timestampFormat).toBe(DEFAULT_CLIENT_SETTINGS.timestampFormat);
finishPersistence();
await expect(pending).resolves.toMatchObject({ timestampFormat: "12-hour" });
expect(getClientSettings().timestampFormat).toBe("12-hour");
});
it("keeps the current snapshot and propagates persistence failure", async () => {
const failure = new Error("disk full");
const setClientSettings = vi.fn().mockRejectedValue(failure);
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
await expect(
persistClientSettingsUpdate(
(current) => ({ ...current, timestampFormat: "12-hour" }),
setClientSettings,
),
).rejects.toBe(failure);
expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
});
it("preserves an optimistic write made while an awaited update persists", async () => {
let finishFirstPersistence!: () => void;
let durableSettings = DEFAULT_CLIENT_SETTINGS;
const firstPersistence = new Promise<void>((resolve) => {
finishFirstPersistence = resolve;
});
const persist = vi
.fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
.mockImplementationOnce((settings) =>
firstPersistence.then(() => {
durableSettings = settings;
}),
)
.mockImplementation(async (settings) => {
durableSettings = settings;
});
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
const importedProfile = { id: "profile-import", name: "Imported", kind: "persistent" as const };
const pending = persistClientSettingsUpdate(
(current) => ({
...current,
browserProfiles: [...current.browserProfiles, importedProfile],
}),
persist,
);
await Promise.resolve();
persistClientSettingsPatch({ wordWrap: false }, persist);
finishFirstPersistence();
await pending;
await Promise.resolve();
expect(persist).toHaveBeenCalledTimes(3);
expect(persist.mock.calls[1]?.[0]).toMatchObject({
wordWrap: false,
});
expect(persist.mock.calls[1]?.[0].browserProfiles).toContainEqual(importedProfile);
expect(durableSettings.wordWrap).toBe(false);
expect(durableSettings.browserProfiles).toContainEqual(importedProfile);
expect(getClientSettings().wordWrap).toBe(false);
expect(getClientSettings().browserProfiles).toContainEqual(importedProfile);
});
it("orders an awaited update after an older optimistic write", async () => {
let finishOldWrite!: () => void;
let durableSettings = DEFAULT_CLIENT_SETTINGS;
const oldWrite = new Promise<void>((resolve) => {
finishOldWrite = resolve;
});
const persist = vi
.fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
.mockImplementationOnce((settings) =>
oldWrite.then(() => {
durableSettings = settings;
}),
)
.mockImplementation(async (settings) => {
durableSettings = settings;
});
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
persistClientSettingsPatch({ wordWrap: false }, persist);
const importedProfile = { id: "profile-import", name: "Imported", kind: "persistent" as const };
const registration = persistClientSettingsUpdate(
(current) => ({
...current,
browserProfiles: [...current.browserProfiles, importedProfile],
}),
persist,
);
await Promise.resolve();
expect(persist).toHaveBeenCalledTimes(1);
finishOldWrite();
await registration;
expect(persist).toHaveBeenCalledTimes(2);
expect(durableSettings.wordWrap).toBe(false);
expect(durableSettings.browserProfiles).toContainEqual(importedProfile);
});
it("continues the queue after a rejected write", async () => {
const failure = new Error("disk full");
const persist = vi
.fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
.mockRejectedValueOnce(failure)
.mockResolvedValue(undefined);
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
await expect(
persistClientSettingsUpdate(
(current) => ({ ...current, timestampFormat: "12-hour" }),
persist,
),
).rejects.toBe(failure);
await expect(
persistClientSettingsUpdate((current) => ({ ...current, wordWrap: false }), persist),
).resolves.toMatchObject({ wordWrap: false });
});
});
describe("resolveEnvironmentIdentificationMode", () => {
it("keeps identification hidden until client settings hydrate", () => {
+64 -14
View File
@@ -57,6 +57,7 @@ let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
let clientSettingsHydrated = false;
let clientSettingsHydrationPromise: Promise<void> | null = null;
let clientSettingsHydrationGeneration = 0;
let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
function emitClientSettingsChange() {
for (const listener of clientSettingsListeners) {
@@ -147,16 +148,54 @@ async function hydrateClientSettings(): Promise<void> {
return clientSettingsHydrationPromise;
}
function persistClientSettings(settings: ClientSettings): void {
replaceClientSettingsSnapshot(settings);
void ensureLocalApi()
.persistence.setClientSettings(settings)
.catch((error) => {
const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
ensureLocalApi().persistence.setClientSettings(settings);
function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
const result = clientSettingsPersistenceQueue.then(work);
clientSettingsPersistenceQueue = result.then(
() => undefined,
() => undefined,
);
return result;
}
export function persistClientSettingsPatch(
patch: ClientSettingsPatch,
persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
): void {
replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
void enqueueClientSettingsPersistence(() => persist(getClientSettingsSnapshot())).catch(
(error) => {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
operation: "persist",
...safeErrorLogAttributes(error),
});
});
},
);
}
/**
* Persists a client-settings update before publishing it to the in-memory
* snapshot. If another settings write lands while persistence is pending, the
* updater is reapplied to that newer snapshot and persisted again so neither
* change is lost.
*/
export async function persistClientSettingsUpdate(
update: (current: ClientSettings) => ClientSettings,
persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
): Promise<ClientSettings> {
return enqueueClientSettingsPersistence(async () => {
for (;;) {
const current = getClientSettingsSnapshot();
const next = update(current);
await persist(next);
if (getClientSettingsSnapshot() === current) {
replaceClientSettingsSnapshot(next);
return next;
}
}
});
}
// ── Key sets for routing patches ─────────────────────────────────────
@@ -396,10 +435,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
}
}
if (Object.keys(clientPatch).length > 0) {
persistClientSettings({
...getClientSettingsSnapshot(),
...clientPatch,
});
persistClientSettingsPatch(clientPatch);
}
},
[environmentId, persistServerSettings, sharedSettingsSyncTargetIds],
@@ -472,9 +508,23 @@ export function useUpdatePrimarySettings() {
export function useUpdateClientSettings() {
return useCallback((patch: ClientSettingsPatch) => {
persistClientSettings({
...getClientSettingsSnapshot(),
...patch,
});
persistClientSettingsPatch(patch);
}, []);
}
export function __resetClientSettingsPersistenceForTests(): void {
clientSettingsHydrationGeneration += 1;
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
clientSettingsHydrated = false;
clientSettingsHydrationPromise = null;
clientSettingsPersistenceQueue = Promise.resolve();
clientSettingsListeners.clear();
clientSettingsHydrationListeners.clear();
}
export function __setClientSettingsForTests(settings: ClientSettings): void {
clientSettingsHydrationGeneration += 1;
clientSettingsSnapshot = settings;
clientSettingsHydrated = true;
clientSettingsHydrationPromise = null;
}
+150
View File
@@ -0,0 +1,150 @@
/**
* Browser import - pulling cookies from a browser already installed on the
* machine into a T3 Code browser profile.
*
* Only cookies are imported. They carry the logged-in sessions, which is what
* makes an imported profile useful; saved passwords are deliberately out of
* scope because Electron exposes no password store to put them in.
*
* Availability is per source and per platform, and the reasons are modelled
* explicitly: some are a permission the user can grant, one is a limitation
* no amount of consent works around. The UI needs to tell those apart.
*
* @module BrowserImport
*/
import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
import { BrowserProfileId } from "./browserProfile.ts";
export const BROWSER_IMPORT_SOURCE_IDS = ["helium"] as const;
export const BrowserImportSourceId = Schema.Literals(BROWSER_IMPORT_SOURCE_IDS);
export type BrowserImportSourceId = typeof BrowserImportSourceId.Type;
/**
* Why a detected source cannot be imported right now.
*
* `needsKeychainApproval` and `browserRunning` are recoverable — the user
* grants access or quits the browser. `unsupportedPlatform` is not: it covers
* cases like Chrome on Windows, whose App-Bound Encryption is designed to stop
* exactly this, and which we will not work around.
*/
export const BrowserImportUnavailableReason = Schema.Literals([
"notInstalled",
"needsKeychainApproval",
"keychainItemMissing",
"browserRunning",
"unsupportedPlatform",
]);
export type BrowserImportUnavailableReason = typeof BrowserImportUnavailableReason.Type;
/**
* Why an import that was actually attempted failed.
*
* A superset of the unavailable reasons: a source can pass the pre-flight
* check and still fail, most often because the user declined the keychain
* prompt the read triggers.
*/
export const BrowserImportFailureReason = Schema.Literals([
...BrowserImportUnavailableReason.literals,
/** No source registered under the requested id. */
"unknownSource",
/** The requested profile directory is not one the source reported. */
"unknownSourceProfile",
/** The target profile's Electron session could not be opened. */
"sessionUnavailable",
/**
* The cookies were written, but the new profile could not be saved to
* settings, so its partition was cleared again rather than left orphaned.
*/
"profileNotSaved",
/**
* The cookies were written, but the profile count reached its cap while the
* import ran, so the new profile was not saved and its partition was cleared.
*/
"profileLimitReached",
/** Anything else: a corrupt database, a failed decrypt, a vanished file. */
"readFailed",
]);
export type BrowserImportFailureReason = typeof BrowserImportFailureReason.Type;
/** A profile inside the source browser, e.g. Chromium's "Default" directory. */
export const BrowserImportSourceProfile = Schema.Struct({
/** Directory name under the source's user-data dir. */
directory: TrimmedNonEmptyString,
/** The name the source browser shows for it. */
name: TrimmedNonEmptyString,
/**
* How many cookies the profile holds. Counted without decrypting, so it is
* cheap; absent when the store could not be read yet (Safari before Full
* Disk Access is granted).
*/
cookieCount: Schema.optional(Schema.Int),
});
export type BrowserImportSourceProfile = typeof BrowserImportSourceProfile.Type;
export const BrowserImportSource = Schema.Struct({
id: BrowserImportSourceId,
name: TrimmedNonEmptyString,
profiles: Schema.Array(BrowserImportSourceProfile),
/** Absent when the source is importable. */
unavailable: Schema.optional(BrowserImportUnavailableReason),
});
export type BrowserImportSource = typeof BrowserImportSource.Type;
export const BrowserImportInput = Schema.Struct({
sourceId: BrowserImportSourceId,
sourceProfileDirectory: TrimmedNonEmptyString,
/** T3 Code profile the cookies are written into. */
targetProfileId: BrowserProfileId,
});
export type BrowserImportInput = typeof BrowserImportInput.Type;
/** IPC payload: the import input plus the environment the partition belongs to. */
export const DesktopPreviewImportCookiesInputSchema = Schema.Struct({
environmentId: TrimmedNonEmptyString,
sourceId: BrowserImportSourceId,
sourceProfileDirectory: TrimmedNonEmptyString,
targetProfileId: BrowserProfileId,
});
export const BrowserImportResult = Schema.Struct({
/** Cookies successfully written into the target partition. */
imported: Schema.Int,
/**
* Cookies read but not written — expired, rejected as malformed, or held
* under a key we could not use. Surfaced rather than hidden so a
* mostly-failed import doesn't look like a success.
*/
skipped: Schema.Int,
/**
* The distinct hosts those skipped cookies belonged to, so the user can be
* told what didn't come over rather than just how many. Capped, since a
* broken key can skip thousands across many sites.
*/
skippedDomains: Schema.Array(Schema.String),
});
export type BrowserImportResult = typeof BrowserImportResult.Type;
export const BROWSER_IMPORT_UNAVAILABLE_COPY: Readonly<
Record<BrowserImportUnavailableReason, string>
> = {
notInstalled: "Not installed on this machine.",
needsKeychainApproval: "Needs Keychain access to read its cookies.",
keychainItemMissing:
"No encryption key in your Keychain — sign in to that browser once, then retry.",
browserRunning: "Quit the browser first so its cookie database can be read.",
unsupportedPlatform: "Importing from this browser isn't possible on this platform.",
};
/** What to tell the user when an attempted import fails. */
export const BROWSER_IMPORT_FAILURE_COPY: Readonly<Record<BrowserImportFailureReason, string>> = {
...BROWSER_IMPORT_UNAVAILABLE_COPY,
unknownSource: "That browser is no longer available to import from.",
unknownSourceProfile: "That browser profile no longer exists.",
sessionUnavailable: "The target profile could not be opened.",
profileNotSaved: "The cookies were imported, but the new profile couldn't be saved. Try again.",
profileLimitReached:
"You've reached the profile limit. Delete a profile or import into an existing one.",
readFailed: "The browser's cookie database could not be read.",
};
+1
View File
@@ -29,6 +29,7 @@ export * from "./project.ts";
export * from "./filesystem.ts";
export * from "./assets.ts";
export * from "./review.ts";
export * from "./browserImport.ts";
export * from "./browserProfile.ts";
export * from "./preview.ts";
export * from "./previewAutomation.ts";
+13
View File
@@ -89,6 +89,11 @@ import type {
} from "./orchestration.ts";
import { EnvironmentId } from "./baseSchemas.ts";
import { BrowserProfileId } from "./browserProfile.ts";
import type {
BrowserImportResult,
BrowserImportSource,
BrowserImportSourceId,
} from "./browserImport.ts";
import { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } from "./auth.ts";
import { AdvertisedEndpoint } from "./remoteAccess.ts";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
@@ -1190,6 +1195,14 @@ export interface DesktopPreviewBridge {
environmentId: EnvironmentId,
profileId?: string,
) => Promise<DesktopPreviewWebviewConfig>;
/** Browsers on this machine whose cookies can be imported. */
listBrowserImportSources: () => Promise<ReadonlyArray<BrowserImportSource>>;
importBrowserCookies: (input: {
readonly environmentId: EnvironmentId;
readonly sourceId: BrowserImportSourceId;
readonly sourceProfileDirectory: string;
readonly targetProfileId: string;
}) => Promise<BrowserImportResult>;
setAnnotationTheme: (theme: DesktopPreviewAnnotationTheme) => Promise<void>;
/**
* Activate the in-page element picker for the given tab. Resolves with
+135
View File
@@ -139,6 +139,9 @@ importers:
'@effect/platform-node':
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])
'@napi-rs/keyring':
specifier: ^1.3.0
version: 1.3.0
'@t3tools/client-runtime':
specifier: workspace:*
version: link:../../packages/client-runtime
@@ -3177,6 +3180,87 @@ packages:
resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==}
engines: {node: '>=18'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-pl76hJvdYUBn6I24bXiOBMA9nbDapo3I5B+f3OorjDU4dUMSypXeKbOVehJe8fhgTiH24flMyTS3aAIy43xegQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-YcJtEV5LA3cvA4z3BurgxH5IhTsW1JfIvcAAcqcecwk06Si9F9NqkxbZVIfDwQ8oRHgaBmT3zZJnLAotCrVahw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-vlLf31TGhfRAaxLDBhg8b89ss0HHD/lyNmL5F3UjSaz5CUXElsJmKYq9fqA/B+cZKUEUcLHHGhF0I/CqcFdaVw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [freebsd]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-KiWdMMu/Inz/bHHIAGrnF7r54FZDYXuHO6UFF/rhIrshUsxbMG1Rl9lEymNtqqsVo927G0VYcb02FzWQ3iBQRQ==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-eyKGpY40lm9Jvs1aD294XRH4y7+TlJM0YVAryZeXA6TX0mb4gMkxVXwSQv7MCwgah7raeUd0dKUb4BPAYIgcMg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-iIK6JWHXAJqDrEyLY3TmswwloVyt2vj+04TZnew+uSJ9gnDO8EwRbp3/iw3LpWaXiDO7VomGO6y8I0Id8uBZSw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-/PGqrwn6EwgtK6vccASSXJRfOSP4vN1F4ASsIQ+7MdrK6hNvAJ1FZPrIuD5gGGdxezo3F++To2Wq7DbuGIeuNQ==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-2PDK1WKWTu9lBGq9VvNEkSlQD3O7YwVpmnyN2M3cy4v7NJ/8gDMd9GXv3G+FVXN13uhp4gnnPBS+ScefmEeD2A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oJ2HkX8YUo46QBkn0pG+HuIKQNqr523q6vBobCn+P95s4C4K6/kLBqHY/1bg5J4ap31DzsznhnFKcfBNBsjCnw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-tOd3c/uAaeoE4ycVlmAdSvygz0Zt3zdca6Y7gokBeIbaRDWpjDIUOpU3MvML59XAaqyuKGsVVu0F/DZb1lHPmw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-sPSqeAFZMGqP1R++M2JTza7GQJJ/TpCo6JU6Vcd4jnebvOaEDs9b7eipakU1PJdSvhpC2yXMCNRk9gXfrhuwHQ==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-4DnCWXwDc0HRKwyRlG5y0VhKZW2tNRQfKKfyj6IX/KWfDNyq9hn4n+GL1auyDcOO/v8PwnhmYo2+rOOqCkvvOg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-WrOw/bcXm0f9qHkumlT1QlArXSTWqaY9sunsDpOk+yCCorCKMxvWT/a3xko4EYHVdeZoh00yI2TydXn6eyICDA==}
engines: {node: '>= 10'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==}
peerDependencies:
@@ -13169,6 +13253,57 @@ snapshots:
strict-event-emitter: 0.5.1
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optionalDependencies:
'@napi-rs/keyring-darwin-arm64': 1.3.0
'@napi-rs/keyring-darwin-x64': 1.3.0
'@napi-rs/keyring-freebsd-x64': 1.3.0
'@napi-rs/keyring-linux-arm-gnueabihf': 1.3.0
'@napi-rs/keyring-linux-arm64-gnu': 1.3.0
'@napi-rs/keyring-linux-arm64-musl': 1.3.0
'@napi-rs/keyring-linux-riscv64-gnu': 1.3.0
'@napi-rs/keyring-linux-x64-gnu': 1.3.0
'@napi-rs/keyring-linux-x64-musl': 1.3.0
'@napi-rs/keyring-win32-arm64-msvc': 1.3.0
'@napi-rs/keyring-win32-ia32-msvc': 1.3.0
'@napi-rs/keyring-win32-x64-msvc': 1.3.0
'@napi-rs/[email protected](@emnapi/[email protected])(@emnapi/[email protected])':
dependencies:
'@emnapi/core': 1.10.0
+80
View File
@@ -200,6 +200,22 @@ export class MacPasskeySigningConfigurationResolutionError extends Schema.Tagged
}
}
export class KeyringNativePackageMissingError extends Schema.TaggedErrorClass<KeyringNativePackageMissingError>()(
"KeyringNativePackageMissingError",
{
packageName: Schema.String,
binaryFileName: Schema.String,
packageEntryPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Keyring native package is missing: ${this.packageName}`;
}
}
export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()(
"ClerkPasskeyNativePackageMissingError",
{
@@ -1343,6 +1359,69 @@ export function resolveClerkPasskeyNativeArtifacts(
return [];
}
export function resolveKeyringNativeArtifacts(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): readonly ClerkPasskeyNativeArtifact[] {
const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
if (platform === "mac") {
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-darwin-${architecture}`,
binaryFileName: `keyring.darwin-${architecture}.node`,
}));
}
if (platform === "win") {
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-win32-${architecture}-msvc`,
binaryFileName: `keyring.win32-${architecture}-msvc.node`,
}));
}
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-linux-${architecture}-gnu`,
binaryFileName: `keyring.linux-${architecture}-gnu.node`,
}));
}
/**
* Same nesting problem as the Clerk passkey binaries: pnpm keeps the platform
* package under `@napi-rs/keyring`, electron-builder only retains collected
* top-level dependencies, and the generated loader checks for a sibling
* `keyring.<platform>.node` before falling back to the package. Staging the
* binary beside `index.js` lets that first branch win.
*/
const stageKeyringNativeBinaries = Effect.fn("stageKeyringNativeBinaries")(function* (
stageAppDir: string,
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const packageEntryPath = yield* fs.realPath(
path.join(stageAppDir, "node_modules", "@napi-rs", "keyring", "index.js"),
);
const packageDir = path.dirname(packageEntryPath);
const packageRequire = NodeModule.createRequire(packageEntryPath);
for (const artifact of resolveKeyringNativeArtifacts(platform, arch)) {
const sourcePath = yield* Effect.try({
try: () => packageRequire.resolve(`${artifact.packageName}/${artifact.binaryFileName}`),
catch: (cause) =>
new KeyringNativePackageMissingError({
packageName: artifact.packageName,
binaryFileName: artifact.binaryFileName,
packageEntryPath,
platform,
arch,
cause,
}),
});
yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
}
});
// pnpm nests the architecture package under @clerk/electron-passkeys, while electron-builder only
// retains collected top-level dependencies. The SDK loader checks beside index.js first, so stage
// the binary there and let electron-builder's native-addon handling unpack it from the ASAR.
@@ -3554,6 +3633,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
{ label: "vp install --prod", verbose: options.verbose },
);
yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);
yield* stageKeyringNativeBinaries(stageAppDir, options.platform, options.arch);
// WSL is Windows-only, so only the Windows artifact carries the server
// sidecar (which embeds the Linux node-pty prebuild); other platforms