fix(desktop): address the browser import review left over from the stack (#9516)

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Utkarsh Patil <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-03 16:57:10 -07:00
1 parent 8ea52c8f2f
commit 3653cb22ff
9 files changed
+385 -26

No files matched your search

@@ -206,13 +206,10 @@ export const make = Effect.gen(function* BrowserImportMake() {
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.
// Only Chromium reads a key; a Firefox import touches no keychain, and
// logging that it did would put a false security-sensitive event in the
// audit trail.
if (definition.engine === "chromium") {
if (platform === "darwin" && definition.engine === "chromium") {
// 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,
@@ -1,5 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off - Encrypts a fixture with the same
// OSCrypt primitive as Chromium.
// @effect-diagnostics nodeBuiltinImport:off - Encrypts fixtures with the same
// OSCrypt primitives the module under test decrypts.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -10,6 +10,7 @@ import {
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -25,6 +26,7 @@ import {
resolveCookieDatabase,
isSourceInstalled,
isSourceRunning,
isWindowsLockHeldError,
posixLockIsHeld,
listSourceProfiles,
sourcePathContext,
@@ -54,6 +56,23 @@ describe("Linux Chromium secret applications", () => {
});
});
const platformError = (reasonTag: string): PlatformError.PlatformError =>
({ _tag: "PlatformError", reason: { _tag: reasonTag } }) as never;
describe("Windows browser lock errors", () => {
it("treats sharing and lock violations reported as Busy as held", () => {
assert.isTrue(isWindowsLockHeldError(platformError("Busy")));
});
it("does not treat access denied as proof of an active lock", () => {
assert.isFalse(isWindowsLockHeldError(platformError("PermissionDenied")));
});
it("does not treat a missing lock file as held", () => {
assert.isFalse(isWindowsLockHeldError(platformError("NotFound")));
});
});
/** A scratch home with the source's user-data directory already created. */
const withSourceHome = Effect.fnUntraced(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -352,6 +371,20 @@ describe("isSourceInstalled", () => {
),
);
it.effect("detects a Chromium 127+ install with cookies under Network/", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const context = yield* withSourceHome();
const root = userDataDirectory(context);
yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
assert.isTrue(yield* isSourceInstalled(helium, context));
}),
),
);
it.effect("follows cookie database symlinks when detecting profiles", () =>
run(
Effect.gen(function* () {
@@ -460,6 +493,79 @@ describe("listSourceProfiles", () => {
),
);
it.effect("drops Firefox profiles that hold no cookie database", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const context = yield* withSourceHome();
const root = firefox.userDataDirectory(context)!;
yield* fileSystem.makeDirectory(root, { recursive: true });
yield* fileSystem.writeFileString(
`${root}/profiles.ini`,
`[Profile0]
Name=original
IsRelative=1
Path=Profiles/abcd.default-release
Default=1
[Profile1]
Name=empty
IsRelative=1
Path=Profiles/wxyz.empty
`,
);
yield* fileSystem.makeDirectory(`${root}/Profiles/abcd.default-release`, {
recursive: true,
});
yield* fileSystem.writeFileString(
`${root}/Profiles/abcd.default-release/cookies.sqlite`,
"db",
);
yield* fileSystem.makeDirectory(`${root}/Profiles/wxyz.empty`, { recursive: true });
assert.deepEqual(yield* listSourceProfiles(firefox, context), [
{ directory: "Profiles/abcd.default-release", name: "original" },
]);
}),
),
);
it.effect("drops empty profiles when falling back to the Profiles/ scan", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const context = yield* withSourceHome();
const root = firefox.userDataDirectory(context)!;
yield* fileSystem.makeDirectory(`${root}/Profiles/filled.default`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Profiles/filled.default/cookies.sqlite`, "db");
yield* fileSystem.makeDirectory(`${root}/Profiles/empty.default`, { recursive: true });
assert.deepEqual(yield* listSourceProfiles(firefox, context), [
{
directory: context.path.join("Profiles", "filled.default"),
name: "filled.default",
},
]);
}),
),
);
it.effect("discovers profiles with cookies under Network/ (Chromium 127+)", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const context = yield* withSourceHome();
const root = userDataDirectory(context);
yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
assert.deepEqual(yield* listSourceProfiles(helium, context), [
{ directory: "Default", name: "Default" },
]);
}),
),
);
it.effect("counts a profile's cookies without decrypting them", () =>
run(
Effect.gen(function* () {
@@ -474,6 +580,24 @@ describe("listSourceProfiles", () => {
}),
),
);
it.effect("falls through to the legacy database when Network/Cookies is a directory", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const paths = yield* withSourceHome();
const root = helium.userDataDirectory(paths);
// A folder squatting on the preferred candidate path must not shadow
// the real legacy database behind it.
yield* fileSystem.makeDirectory(`${root}/Default/Network/Cookies`, { recursive: true });
yield* writeCookieDatabase(`${root}/Default/Cookies`, 2);
const [profile] = yield* listSourceProfiles(helium, paths);
assert.equal(profile?.directory, "Default");
assert.equal(profile?.cookieCount, 2);
}),
),
);
});
describe("cookieDatabaseCandidatePaths", () => {
@@ -512,6 +636,25 @@ describe("cookieDatabaseCandidatePaths", () => {
}),
),
);
it.effect("returns only cookies.sqlite for Firefox", () =>
run(
Effect.gen(function* () {
const path = yield* Path.Path;
const context = yield* sourcePathContext.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: "/tmp/test" }),
Effect.provideService(HostProcessPlatform, "darwin"),
);
const candidates = cookieDatabaseCandidatePaths(firefox, context, "Profiles/abc.default");
assert.deepEqual(candidates, [
path.join(
"/tmp/test",
"Library/Application Support/Firefox/Profiles/abc.default/cookies.sqlite",
),
]);
}),
),
);
});
const firefox = BROWSER_IMPORT_SOURCES.find((source) => source.id === "firefox")!;
@@ -642,6 +785,41 @@ describe("listSourceProfiles Firefox fallback", () => {
);
}
it.effect("scans for profiles when profiles.ini declares only ones without cookies", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-firefox-stale-ini-",
});
const context = yield* sourcePathContext.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: home }),
Effect.provideService(HostProcessPlatform, "darwin"),
);
const root = firefox.userDataDirectory(context)!;
// `profiles.ini` names a profile that was never launched (no cookie
// database), while the real cookies sit in an undeclared one.
yield* fileSystem.makeDirectory(path.join(root, "Profiles", "stale.default"), {
recursive: true,
});
const realDirectory = path.join(root, "Profiles", "real.default");
yield* fileSystem.makeDirectory(realDirectory, { recursive: true });
yield* writeFirefoxCookieDatabase(path.join(realDirectory, "cookies.sqlite"), 3, 0);
yield* fileSystem.writeFileString(
path.join(root, "profiles.ini"),
["[Profile0]", "Name=Stale", "IsRelative=1", "Path=Profiles/stale.default"].join("\n"),
);
// Returning the empty declared list would hide the browser entirely.
assert.deepEqual(yield* listSourceProfiles(firefox, context), [
{ directory: "Profiles/real.default", name: "real.default", cookieCount: 3 },
]);
assert.isTrue(yield* isSourceInstalled(firefox, context));
}),
),
);
it.effect("counts only importable cookies for declared and fallback profiles", () =>
run(
Effect.gen(function* () {
@@ -809,6 +987,49 @@ describe("isSourceRunning for Firefox", () => {
assert.isTrue(yield* firefoxSymlinkLockIsHeld("10.0.0.7:+9999", local, alive));
}),
);
it.effect("does not treat a stale parent.lock file as a running browser", () =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
const context = yield* sourcePathContext.pipe(
// Firefox's win32 root hangs off %APPDATA%; without it the root is
// undefined and the fixture would escape the sandbox into the repo.
Effect.provideService(HostProcessEnvironment, {
HOME: home,
APPDATA: `${home}/AppData/Roaming`,
}),
Effect.provideService(HostProcessPlatform, "win32"),
);
const root = firefox.userDataDirectory(context)!;
const profile = `${root}/Profiles/gx7x7fqx.default-release`;
yield* fileSystem.makeDirectory(profile, { recursive: true });
yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
// On Windows, Firefox creates parent.lock as a regular file that
// persists after the process exits. The file is only locked while
// Firefox is running; the old stat-based check always found it.
yield* fileSystem.writeFileString(`${profile}/parent.lock`, "");
assert.isFalse(yield* isSourceRunning(firefox, context));
}),
),
);
});
describe("Windows user-data directories", () => {
it.effect("keeps app-bound Chromium forks unsupported on win32", () =>
Effect.sync(() => {
// Helium retains the older DPAPI-backed store. Other Chromium forks use
// App-Bound Encryption, so omitting win32 makes `unavailableReason`
// report `unsupportedPlatform` and keeps them out of the menu.
for (const source of BROWSER_IMPORT_SOURCES) {
if (source.engine === "chromium" && source.id !== "helium") {
assert.notInclude(source.platforms, "win32");
}
}
}),
);
});
describe("listSourceProfiles hardening", () => {
@@ -109,6 +109,10 @@ const chromiumSource = (input: {
});
export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition> = [
// No Chromium fork is importable on Windows: since Chrome 127 their cookies
// are encrypted to the browser's own identity (App-Bound Encryption), so no
// other process can read them. macOS and Linux keep working, so only the
// Windows segments are omitted.
chromiumSource({
id: "chrome",
name: "Chrome",
@@ -198,6 +202,10 @@ export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition
* and a fresh install with only `Network/Cookies` would read as not installed.
* Firefox uses `cookies.sqlite`, and its profile paths from `profiles.ini`
* may already be absolute.
*
* Chrome 96+ moved network-related files (including Cookies) into a `Network`
* subdirectory for sandboxing. The candidate list includes both locations so
* callers tolerate fresh and legacy installs alike.
*/
export const cookieDatabaseCandidatePaths = (
definition: BrowserImportSourceDefinition,
@@ -206,11 +214,18 @@ export const cookieDatabaseCandidatePaths = (
): ReadonlyArray<string> => {
const root = definition.userDataDirectory(context);
if (root === undefined) return [];
const profile = context.path.isAbsolute(profileDirectory)
const profilePath = context.path.isAbsolute(profileDirectory)
? profileDirectory
: context.path.join(root, profileDirectory);
if (definition.engine === "firefox") return [context.path.join(profile, "cookies.sqlite")];
return [context.path.join(profile, "Network", "Cookies"), context.path.join(profile, "Cookies")];
if (definition.engine === "firefox") {
return [context.path.join(profilePath, "cookies.sqlite")];
}
// Chromium: pre-96 uses `Cookies`, 96+ use `Network/Cookies`. An upgrade
// leaves the legacy file behind, so prefer the current one and fall back.
return [
context.path.join(profilePath, "Network", "Cookies"),
context.path.join(profilePath, "Cookies"),
];
};
/** The first candidate that is a regular file, or undefined when none is. */
@@ -393,16 +408,35 @@ const listSourceProfilesInDirectory = Effect.fnUntraced(function* (
Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)),
Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
);
if (declared.length > 0) return yield* withCookieCounts(definition, context, declared);
// `profiles.ini` also lists profiles the installer created but the user
// never launched, which hold no cookie database and nothing to import.
// Only keep the ones a database proves exist, like the directory scans
// below do. When none of the declared profiles has one, fall through to
// the scan rather than returning empty: `profiles.ini` can list stale or
// never-launched profiles while the cookies live in one it does not
// mention, and an empty answer here hides the browser entirely.
if (declared.length > 0) {
const found = yield* Effect.forEach(declared, (profile) =>
Effect.forEach(
cookieDatabaseCandidatePaths(definition, context, profile.directory),
(candidate) => databaseFileExists(candidate),
).pipe(Effect.map((results) => (results.some(Boolean) ? profile : undefined))),
);
const withDatabase = found.filter((profile) => profile !== undefined);
if (withDatabase.length > 0) {
return yield* withCookieCounts(definition, context, withDatabase);
}
}
// Linux keeps profile directories directly under the Firefox root. macOS
// and Windows put them in `Profiles/`.
// No usable `profiles.ini`, so fall back to scanning the directory the
// profiles actually live in, keeping only the ones a cookie database
// proves were launched.
const fallbackDirectory =
context.platform === "linux" ? root : context.path.join(root, "Profiles");
const entries = yield* fileSystem
const scanned = yield* fileSystem
.readDirectory(fallbackDirectory)
.pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
const found = yield* Effect.forEach(entries, (entry) => {
const found = yield* Effect.forEach(scanned, (entry) => {
const directory = context.platform === "linux" ? entry : context.path.join("Profiles", entry);
return resolveCookieDatabase(definition, context, directory).pipe(
Effect.map((database) => (database === undefined ? undefined : { directory, name: entry })),
@@ -739,8 +773,11 @@ export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")
const root = definition.userDataDirectory(context);
if (root === undefined) return false;
// Probe the source's own lock state rather than scanning the process table.
// Chromium exposes that through the cookie jar on Windows and through its
// user-data SingletonLock on POSIX.
// Chromium exposes its lock through the cookie jar on Windows and through a
// user-data SingletonLock on POSIX. Firefox keeps its locks inside each
// profile under three names across platforms (`lock` on macOS and Linux,
// `.parentlock` beside it, `parent.lock` on Windows). Looking for Firefox's
// at the root finds nothing and reports a running browser as importable.
if (definition.engine !== "firefox") {
if (context.platform === "win32") {
return yield* windowsChromiumCookiesAreHeld(definition, context);
@@ -781,10 +781,11 @@ 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.
// A browser that is not on this machine 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. An unsupported one is left out for the same reason — the
// blocked wizard step can't be fixed from here. 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",
+4 -1
View File
@@ -5,9 +5,12 @@
* with no newline or other framing that could change the derived cookie key. */
enum { KEY_MISSING = 2, KEY_LOCKED = 3, READ_FAILED = 4 };
/* Chromium looks its key up by attributes alone: items written by older
* libgnome-keyring builds carry no schema name, and SECRET_SCHEMA_NONE would
* refuse them. DONT_MATCH_NAME keeps the attribute match and drops the name. */
static const SecretSchema chromium_schema = {
.name = "chrome_libsecret_os_crypt_password_v2",
.flags = SECRET_SCHEMA_NONE,
.flags = SECRET_SCHEMA_DONT_MATCH_NAME,
.attributes = {{"application", SECRET_SCHEMA_ATTRIBUTE_STRING}, {NULL, 0}},
};
+1 -1
View File
@@ -11,7 +11,7 @@ GList *__wrap_secret_service_search_sync(SecretService *service, const SecretSch
g_assert_null(service);
g_assert_null(cancellable);
g_assert_cmpstr(schema->name, ==, "chrome_libsecret_os_crypt_password_v2");
g_assert_cmpint(schema->flags, ==, SECRET_SCHEMA_NONE);
g_assert_cmpint(schema->flags, ==, SECRET_SCHEMA_DONT_MATCH_NAME);
g_assert_cmpint(flags, ==, SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS);
g_assert_cmpuint(g_hash_table_size(attributes), ==, 1);
scenario = g_intern_string(g_hash_table_lookup(attributes, "application"));
+80
View File
@@ -66,6 +66,8 @@ import {
STAGE_INSTALL_ARGS,
ancestorNodeModulesPaths,
copyDirectoryPreservingSymlinks,
LinuxBrowserSecretHostError,
stageBrowserSecret,
validateWindowsPackagedPayload,
WindowsPrimaryNativeProbeError,
WindowsDesktopBuildPrerequisitesMissingError,
@@ -1207,6 +1209,84 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
);
});
it.effect("builds the Linux browser secret helper for a concrete architecture", () => {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
commands.push(command as unknown as (typeof commands)[number]);
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
// `universal` is a mac-only arch the option type still admits. The helper
// script only knows x64 and arm64, so the request maps to x64, the same
// concrete target the Linux resource monitor resolves it to.
yield* stageBrowserSecret({
repoRoot: "/repo",
stageResourcesDir: "/stage/resources",
platform: "linux",
arch: "universal",
verbose: false,
});
const helper = commands.find((command) =>
command.args.some((arg) => arg.endsWith("build-browser-secret.mjs")),
);
assert.isDefined(helper);
assert.deepStrictEqual(helper.args.slice(-4), [
"--arch",
"x64",
"--output",
"/stage/resources/browser-secret/t3-browser-secret",
]);
}).pipe(
Effect.provide(
Layer.mergeAll(
spawnerLayer,
Layer.succeed(HostProcessPlatform, "linux"),
Layer.succeed(HostProcessArchitecture, "x64"),
),
),
);
});
it.effect("refuses a Linux build on a host that cannot build the browser secret helper", () => {
const commands: Array<{ readonly command: string }> = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
commands.push(command as unknown as (typeof commands)[number]);
return Effect.succeed(mockProcess(0));
}),
);
return Effect.gen(function* () {
// The helper links against the host's libsecret and its build script is
// a no-op elsewhere, so a Linux artifact built on macOS would ship
// without it and report the keyring as unavailable on every import.
const error = yield* stageBrowserSecret({
repoRoot: "/repo",
stageResourcesDir: "/stage/resources",
platform: "linux",
arch: "x64",
verbose: false,
}).pipe(Effect.flip);
assert.instanceOf(error, LinuxBrowserSecretHostError);
assert.equal(error.hostPlatform, "darwin");
assert.include(error.message, "Linux host");
assert.lengthOf(commands, 0);
}).pipe(
Effect.provide(
Layer.mergeAll(
spawnerLayer,
Layer.succeed(HostProcessPlatform, "darwin"),
Layer.succeed(HostProcessArchitecture, "arm64"),
),
),
);
});
it.effect("skips the primary native probe for cross-architecture Windows payloads", () => {
const commands: Array<{
readonly command: string;
+21 -1
View File
@@ -447,6 +447,15 @@ const desktopIconPlatformNames = {
win: "Windows",
} satisfies Record<typeof BuildPlatform.Type, string>;
export class LinuxBrowserSecretHostError extends Schema.TaggedErrorClass<LinuxBrowserSecretHostError>()(
"LinuxBrowserSecretHostError",
{ hostPlatform: Schema.String },
) {
override get message(): string {
return `Linux desktop builds must run on a Linux host: the browser secret helper links against libsecret and cannot be built on '${this.hostPlatform}'.`;
}
}
export class DesktopIconSourceMissingError extends Schema.TaggedErrorClass<DesktopIconSourceMissingError>()(
"DesktopIconSourceMissingError",
{
@@ -2220,6 +2229,17 @@ export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (inp
readonly verbose: boolean;
}) {
if (input.platform !== "linux") return;
// The helper links against the host's libsecret, so it can only be built on
// Linux; the build script is a no-op elsewhere. A Linux artifact from
// another host would ship without it and every v11 cookie import would
// report the keyring as unavailable, so refuse rather than package that
// silently. `universal` is a mac-only arch the option type still admits;
// the helper script rejects it, so it maps to the concrete x64 the Linux
// resource monitor uses for the same request.
const hostPlatform = yield* HostProcessPlatform;
if (hostPlatform !== "linux") {
return yield* new LinuxBrowserSecretHostError({ hostPlatform });
}
const path = yield* Path.Path;
yield* runCommand(
ChildProcess.make(
@@ -2227,7 +2247,7 @@ export const stageBrowserSecret = Effect.fn("stageBrowserSecret")(function* (inp
[
path.join(input.repoRoot, "apps/desktop/scripts/build-browser-secret.mjs"),
"--arch",
input.arch,
input.arch === "arm64" ? "arm64" : "x64",
"--output",
path.join(input.stageResourcesDir, "browser-secret", "t3-browser-secret"),
],