Skip to content

Commit 84496fa

Browse files
committed
fix(desktop): macOS Keychain consent no longer freezes startup
Use native async safeStorage only on macOS and avoid Keychain access for an empty legacy registry. Select local runtime crypto identity before async startup, and give its catalog, Chromium profile, and Clerk tokens the same isolation boundary. Preserve packaged identities and non-macOS storage behavior.
1 parent 07cb902 commit 84496fa

12 files changed

Lines changed: 403 additions & 21 deletions

‎apps/desktop/src/app/DesktopClerk.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ const layerDesktopClerk = (
6262
isDevelopment,
6363
appDataDirectory: "/tmp/app-data",
6464
platform,
65+
isPackaged: true,
66+
dirname: "/app",
6567
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
6668

6769
const electronApp = {

‎apps/desktop/src/app/DesktopClerk.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Context from "effect/Context";
55
import * as Effect from "effect/Effect";
66
import * as Layer from "effect/Layer";
77
import * as Option from "effect/Option";
8+
import * as Path from "effect/Path";
89
import * as Schema from "effect/Schema";
910
import * as Scope from "effect/Scope";
1011

@@ -18,6 +19,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
1819
import * as ElectronApp from "../electron/ElectronApp.ts";
1920
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
2021
import * as ElectronWindow from "../electron/ElectronWindow.ts";
22+
import { resolveEarlyMacKeychainName } from "./DesktopEarlyElectronStartup.ts";
2123
import * as DesktopUserData from "./DesktopUserData.ts";
2224
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
2325
import * as DesktopWebLinks from "./DesktopWebLinks.ts";
@@ -99,14 +101,28 @@ export const make = Effect.gen(function* () {
99101
const environment = yield* DesktopEnvironment.DesktopEnvironment;
100102
const electronApp = yield* ElectronApp.ElectronApp;
101103
const shell = yield* ElectronShell.ElectronShell;
104+
const path = yield* Path.Path;
105+
const localMacKeychainName = resolveEarlyMacKeychainName({
106+
platform: environment.platform,
107+
isPackaged: environment.isPackaged,
108+
runtimeDirectory: environment.dirname,
109+
isDevelopment: environment.isDevelopment,
110+
});
111+
const tokenDirectory =
112+
localMacKeychainName === null
113+
? environment.stateDir
114+
: path.join(environment.stateDir, "local-keychains", localMacKeychainName);
102115

103116
// Must not yield: the bridge registers a scheme Electron rejects once ready.
104117
const userDataPath = yield* DesktopUserData.resolveUserDataPath(environment);
105118
yield* electronApp.setPath("userData", userDataPath);
119+
if (localMacKeychainName !== null) {
120+
yield* electronApp.setPath("sessionData", userDataPath);
121+
}
106122

107123
const bridge = yield* Effect.acquireRelease(
108124
Effect.try({
109-
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
125+
try: () => createDesktopClerkBridge(tokenDirectory, environment.isDevelopment),
110126
catch: (cause) =>
111127
new DesktopClerkBridgeInitializationError({
112128
stateDir: environment.stateDir,

‎apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts‎

Lines changed: 70 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,16 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect(
2828
Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }),
2929
),
3030
);
31-
function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
31+
type EncryptionAvailability =
32+
| boolean
33+
| Effect.Effect<boolean, ElectronSafeStorage.ElectronSafeStorageAvailabilityError>;
34+
35+
function layerSafeStorageFor(
36+
available: EncryptionAvailability,
37+
failDecrypt: Ref.Ref<boolean> | null = null,
38+
) {
3239
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
33-
isEncryptionAvailable: Effect.succeed(available),
40+
isEncryptionAvailable: typeof available === "boolean" ? Effect.succeed(available) : available,
3441
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
3542
decryptString: (value) => {
3643
return Effect.gen(function* () {
@@ -52,9 +59,14 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
5259

5360
function layerFor(
5461
baseDir: string,
55-
encryptionAvailable = true,
62+
encryptionAvailable: EncryptionAvailability = true,
5663
failDecrypt: Ref.Ref<boolean> | null = null,
5764
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
65+
runtime: {
66+
readonly dirname?: string;
67+
readonly platform?: NodeJS.Platform;
68+
readonly isPackaged?: boolean;
69+
} = {},
5870
) {
5971
const layerEnvironment = DesktopEnvironment.layer({
6072
dirname: "/repo/apps/desktop/src",
@@ -66,6 +78,7 @@ function layerFor(
6678
isPackaged: true,
6779
resourcesPath: "/missing/resources",
6880
runningUnderArm64Translation: false,
81+
...runtime,
6982
}).pipe(
7083
Layer.provide(
7184
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
@@ -90,7 +103,7 @@ function layerFor(
90103

91104
const withStore = <A, E, R>(
92105
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
93-
encryptionAvailable = true,
106+
encryptionAvailable: EncryptionAvailability = true,
94107
) =>
95108
Effect.gen(function* () {
96109
const fileSystem = yield* FileSystem.FileSystem;
@@ -101,6 +114,59 @@ const withStore = <A, E, R>(
101114
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
102115

103116
describe("DesktopConnectionCatalogStore", () => {
117+
it.effect("isolates local macOS catalogs sharing a home and leaves legacy data untouched", () =>
118+
Effect.gen(function* () {
119+
const fileSystem = yield* FileSystem.FileSystem;
120+
const path = yield* Path.Path;
121+
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
122+
prefix: "t3-local-keychain-catalog-test-",
123+
});
124+
const makeStore = (dirname: string) =>
125+
DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
126+
Effect.provide(
127+
layerFor(baseDir, true, null, NodeServices.layer, { dirname, isPackaged: false }),
128+
),
129+
);
130+
const sharedPath = path.join(baseDir, "userdata", "connection-catalog.json");
131+
const legacyPath = path.join(baseDir, "userdata", "saved-environments.json");
132+
yield* fileSystem.makeDirectory(path.dirname(sharedPath), { recursive: true });
133+
yield* fileSystem.writeFileString(sharedPath, "unreadable shared ciphertext");
134+
yield* fileSystem.writeFileString(legacyPath, "unreadable shared registry");
135+
const a = yield* makeStore("/repo/a/apps/desktop/dist-electron");
136+
const b = yield* makeStore("/repo/b/apps/desktop/dist-electron");
137+
assert.deepStrictEqual(yield* a.get, Option.none());
138+
assert.isTrue(yield* a.set("catalog A"));
139+
assert.deepStrictEqual(yield* b.get, Option.none());
140+
assert.isTrue(yield* b.set("catalog B"));
141+
assert.deepStrictEqual(yield* a.get, Option.some("catalog A"));
142+
assert.deepStrictEqual(yield* b.get, Option.some("catalog B"));
143+
yield* b.clear;
144+
assert.deepStrictEqual(yield* a.get, Option.some("catalog A"));
145+
assert.deepStrictEqual(yield* b.get, Option.none());
146+
assert.equal(yield* fileSystem.readFileString(sharedPath), "unreadable shared ciphertext");
147+
assert.equal(yield* fileSystem.readFileString(legacyPath), "unreadable shared registry");
148+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
149+
);
150+
151+
it.effect("reads a fresh profile without accessing Keychain", () => {
152+
const cause = new ElectronSafeStorage.ElectronSafeStorageAvailabilityError({
153+
cause: new Error("Keychain requires consent"),
154+
});
155+
return withStore(
156+
Effect.gen(function* () {
157+
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
158+
assert.deepStrictEqual(yield* store.get, Option.none());
159+
const error = yield* Effect.flip(store.set("{}"));
160+
assert.instanceOf(
161+
error,
162+
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
163+
);
164+
assert.strictEqual(error.cause, cause);
165+
}),
166+
Effect.fail(cause),
167+
);
168+
});
169+
104170
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
105171
withStore(
106172
Effect.gen(function* () {

‎apps/desktop/src/app/DesktopConnectionCatalogStore.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import * as Schema from "effect/Schema";
2525
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
2626
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
2727
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
28+
import { resolveEarlyMacKeychainName } from "./DesktopEarlyElectronStartup.ts";
2829

2930
const EncryptedConnectionCatalogDocument = Schema.Struct({
3031
version: Schema.Literal(1),
@@ -384,7 +385,21 @@ export const make = Effect.gen(function* () {
384385
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
385386
const crypto = yield* Crypto.Crypto;
386387
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
387-
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
388+
const localMacKeychainName = resolveEarlyMacKeychainName({
389+
platform: environment.platform,
390+
isPackaged: environment.isPackaged,
391+
runtimeDirectory: environment.dirname,
392+
isDevelopment: environment.isDevelopment,
393+
});
394+
const catalogPath =
395+
localMacKeychainName === null
396+
? path.join(environment.stateDir, "connection-catalog.json")
397+
: path.join(
398+
environment.stateDir,
399+
"local-keychains",
400+
localMacKeychainName,
401+
"connection-catalog.json",
402+
);
388403
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
389404
Effect.mapError(
390405
(cause) =>
@@ -431,9 +446,8 @@ export const make = Effect.gen(function* () {
431446
});
432447

433448
const migrateLegacyCatalog = Effect.gen(function* () {
434-
if (!(yield* encryptionAvailable)) {
435-
return Option.none<string>();
436-
}
449+
// Shared legacy credentials belong to the old key, not this runtime's isolated key.
450+
if (localMacKeychainName !== null) return Option.none<string>();
437451
const records = yield* savedEnvironments.getRegistry.pipe(
438452
Effect.mapError(
439453
(cause) =>
@@ -447,6 +461,9 @@ export const make = Effect.gen(function* () {
447461
if (records.length === 0) {
448462
return Option.none<string>();
449463
}
464+
if (!(yield* encryptionAvailable)) {
465+
return Option.none<string>();
466+
}
450467
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
451468
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
452469
Effect.mapError(

‎apps/desktop/src/app/DesktopEarlyElectronStartup.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as NodePath from "node:path";
33
import { assert, describe, it } from "@effect/vitest";
44

55
import {
6+
resolveEarlyMacKeychainName,
67
resolveEarlyLinuxElectronOptions,
78
resolveEarlyLinuxPasswordStorePreference,
89
resolveLinuxDisableFeaturesSwitch,
@@ -11,6 +12,52 @@ import {
1112
describe("DesktopEarlyElectronStartup", () => {
1213
const joinPath = NodePath.posix.join;
1314

15+
it("isolates local macOS Keychain names by normalized runtime path and launch mode", () => {
16+
const input = {
17+
platform: "darwin",
18+
isPackaged: false,
19+
runtimeDirectory: "/repo/worktree/apps/desktop/dist-electron",
20+
isDevelopment: true,
21+
} as const;
22+
const name = resolveEarlyMacKeychainName(input);
23+
assert.match(name!, /^T3 Code Dev [a-f0-9]{12}$/);
24+
assert.equal(
25+
resolveEarlyMacKeychainName({
26+
...input,
27+
runtimeDirectory: "/repo/worktree/apps/desktop/./dist-electron/",
28+
}),
29+
name,
30+
);
31+
assert.notEqual(
32+
resolveEarlyMacKeychainName({ ...input, runtimeDirectory: "/other/dist-electron" }),
33+
name,
34+
);
35+
assert.notEqual(resolveEarlyMacKeychainName({ ...input, isDevelopment: false }), name);
36+
});
37+
38+
it("preserves packaged and non-macOS Keychain identities", () => {
39+
for (const platform of ["darwin", "linux", "win32"] as const) {
40+
assert.isNull(
41+
resolveEarlyMacKeychainName({
42+
platform,
43+
isPackaged: true,
44+
runtimeDirectory: "/app",
45+
isDevelopment: false,
46+
}),
47+
);
48+
if (platform !== "darwin") {
49+
assert.isNull(
50+
resolveEarlyMacKeychainName({
51+
platform,
52+
isPackaged: false,
53+
runtimeDirectory: "/repo",
54+
isDevelopment: true,
55+
}),
56+
);
57+
}
58+
}
59+
});
60+
1461
it("reads the persisted linux password-store preference before Electron is ready", () => {
1562
const preference = resolveEarlyLinuxPasswordStorePreference({
1663
env: { T3CODE_HOME: "/home/user/.t3-test" },

‎apps/desktop/src/app/DesktopEarlyElectronStartup.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import { fromLenientJson } from "@t3tools/shared/schemaJson";
2+
// @effect-diagnostics-next-line nodeBuiltinImport:off - Crypto identity must be selected synchronously before Electron starts its main loop.
3+
import * as NodeCrypto from "node:crypto";
4+
// @effect-diagnostics-next-line nodeBuiltinImport:off - Normalize the local runtime path before hashing its identity.
5+
import * as NodePath from "node:path";
26
import * as Option from "effect/Option";
37
import * as Schema from "effect/Schema";
48

@@ -15,6 +19,20 @@ import {
1519
type JoinPath,
1620
} from "./DesktopStatePaths.ts";
1721

22+
export function resolveEarlyMacKeychainName(input: {
23+
readonly platform: NodeJS.Platform;
24+
readonly isPackaged: boolean;
25+
readonly runtimeDirectory: string;
26+
readonly isDevelopment: boolean;
27+
}): string | null {
28+
if (input.platform !== "darwin" || input.isPackaged) return null;
29+
const suffix = NodeCrypto.createHash("sha256")
30+
.update(NodePath.resolve(input.runtimeDirectory))
31+
.digest("hex")
32+
.slice(0, 12);
33+
return `T3 Code ${input.isDevelopment ? "Dev" : "Local"} ${suffix}`;
34+
}
35+
1836
interface EarlyDesktopSettingsInput {
1937
readonly env: NodeJS.ProcessEnv;
2038
readonly homeDirectory: string;

‎apps/desktop/src/app/DesktopPreReadyFileSystem.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ const resolveWindowsUserData = (appDataDirectory: string) =>
1414
appDataDirectory,
1515
isDevelopment: false,
1616
platform: "win32",
17+
isPackaged: true,
18+
dirname: "/app",
1719
}).pipe(Effect.provide(DesktopPreReadyFileSystem.layer));
1820

1921
it.layer(NodeServices.layer)("DesktopPreReadyFileSystem", (it) => {

‎apps/desktop/src/app/DesktopUserData.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,38 @@ import * as PlatformError from "effect/PlatformError";
77

88
import { resolveUserDataPath } from "./DesktopUserData.ts";
99

10+
it.effect.each([true, false])(
11+
"isolates local macOS browser profiles without copying shared data (development: %s)",
12+
(isDevelopment) =>
13+
Effect.gen(function* () {
14+
const fs = yield* FileSystem.FileSystem;
15+
const path = yield* Path.Path;
16+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mac-profile-" });
17+
const legacy = path.join(directory, isDevelopment ? "T3 Code (Dev)" : "t3code-v2");
18+
yield* fs.makeDirectory(legacy, { recursive: true });
19+
yield* fs.writeFileString(path.join(legacy, "Cookies"), "shared encrypted cookies");
20+
const input = {
21+
appDataDirectory: directory,
22+
platform: "darwin",
23+
isPackaged: false,
24+
isDevelopment,
25+
} as const;
26+
const a = yield* resolveUserDataPath({ ...input, dirname: "/runtime/a" });
27+
const b = yield* resolveUserDataPath({ ...input, dirname: "/runtime/b" });
28+
assert.notEqual(a, b);
29+
assert.notEqual(a, legacy);
30+
yield* fs.makeDirectory(a, { recursive: true });
31+
yield* fs.writeFileString(path.join(a, "Cookies"), "runtime A cookies");
32+
assert.isFalse(yield* fs.exists(path.join(b, "Cookies")));
33+
assert.equal(yield* resolveUserDataPath({ ...input, dirname: "/runtime/a/./" }), a);
34+
assert.equal(yield* fs.readFileString(path.join(a, "Cookies")), "runtime A cookies");
35+
assert.equal(
36+
yield* fs.readFileString(path.join(legacy, "Cookies")),
37+
"shared encrypted cookies",
38+
);
39+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
40+
);
41+
1042
it.effect("identifies a failed source read and preserves its cause", () => {
1143
const sourceState = "/profiles/t3code/Local State";
1244
const cause = PlatformError.systemError({
@@ -20,6 +52,8 @@ it.effect("identifies a failed source read and preserves its cause", () => {
2052
appDataDirectory: "/profiles",
2153
isDevelopment: false,
2254
platform: "win32",
55+
isPackaged: true,
56+
dirname: "/app",
2357
}).pipe(Effect.flip);
2458
assert.equal(error.operation, "read");
2559
assert.equal(error.resourcePath, sourceState);
@@ -55,6 +89,8 @@ it.effect.each(["t3code", "T3 Code (Alpha)"])(
5589
appDataDirectory: directory,
5690
isDevelopment: false,
5791
platform: "win32",
92+
isPackaged: true,
93+
dirname: "/app",
5894
});
5995
assert.equal(yield* fs.readFileString(path.join(destination, "Local State")), state);
6096
assert.equal(yield* fs.readFileString(path.join(source, "Local State")), state);
@@ -64,6 +100,8 @@ it.effect.each(["t3code", "T3 Code (Alpha)"])(
64100
appDataDirectory: directory,
65101
isDevelopment: false,
66102
platform: "win32",
103+
isPackaged: true,
104+
dirname: "/app",
67105
});
68106
assert.equal(
69107
yield* fs.readFileString(path.join(destination, "Local State")),

0 commit comments

Comments
 (0)