Skip to content
TypeScript

fix(desktop): saved connections survive the Beta rename on macOS and Linux (#20907)

Jordan Munch O'Hare3819eb367a29
diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
index a8ac69b3453..c0dc12e634f 100644
--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
@@ -1,9 +1,14 @@
+// @effect-diagnostics nodeBuiltinImport:off - The recovery fixtures use Chromium OSCrypt ciphertext.
+import * as NodeCrypto from "node:crypto";
+
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Base64 from "effect/encoding/Base64";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Layer from "effect/Layer";
@@ -11,12 +16,65 @@ import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import { ChildProcessSpawner } from "effect/process";
+import { beforeEach, vi } from "vite-plus/test";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
+import { LinuxBrowserSecretPath } from "../preview/BrowserImport/LinuxBrowserSecret.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+import * as DesktopSafeStorageIdentity from "./DesktopSafeStorageIdentity.ts";
+
+const { getBetaPassword } = vi.hoisted(() => ({
+ getBetaPassword: vi.fn<() => string | null>(),
+}));
+
+vi.mock("@napi-rs/keyring", () => ({
+ Entry: class {
+ readonly getPassword;
+ constructor(service: string, account: string) {
+ this.getPassword = () =>
+ service === "T3 Code (Beta) Safe Storage" && account === "T3 Code (Beta)"
+ ? getBetaPassword()
+ : null;
+ }
+ },
+}));
+
+beforeEach(() => {
+ getBetaPassword.mockReset().mockReturnValue(null);
+});
+
+const savedCatalog = JSON.stringify({
+ schemaVersion: 1,
+ targets: [
+ { _tag: "RelayConnectionTarget", environmentId: "relay-environment", label: "Saved relay" },
+ ],
+ profiles: [],
+ credentials: [],
+ remoteDpopTokens: [],
+ disabledEnvironmentIds: [],
+});
+
+const encryptBetaCatalog = (platform: NodeJS.Platform, catalog = savedCatalog) => {
+ const key = NodeCrypto.pbkdf2Sync(
+ "beta-secret",
+ "saltysalt",
+ platform === "darwin" ? 1003 : 1,
+ 16,
+ "sha1",
+ );
+ const cipher = NodeCrypto.createCipheriv("aes-128-cbc", key, Buffer.alloc(16, " "));
+ return Buffer.concat([
+ Buffer.from(platform === "darwin" ? "v10" : "v11"),
+ cipher.update(catalog, "utf8"),
+ cipher.final(),
+ ]);
+};
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
@@ -28,7 +86,11 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect(
Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }),
),
);
-function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
+function layerSafeStorageFor(
+ available: boolean,
+ failDecrypt: Ref.Ref<boolean> | null = null,
+ currentSecret?: string,
+) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
@@ -39,6 +101,23 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
+ if (currentSecret !== undefined) {
+ return yield* Effect.try({
+ try: () => {
+ const key = NodeCrypto.pbkdf2Sync(currentSecret, "saltysalt", 1003, 16, "sha1");
+ const decipher = NodeCrypto.createDecipheriv(
+ "aes-128-cbc",
+ key,
+ Buffer.alloc(16, " "),
+ );
+ return Buffer.concat([
+ decipher.update(value.subarray(3)),
+ decipher.final(),
+ ]).toString("utf8");
+ },
+ catch: (cause) => new ElectronSafeStorage.ElectronSafeStorageDecryptError({ cause }),
+ });
+ }
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
@@ -50,16 +129,52 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
+const layerLinuxKeyAccess = (lookup: Effect.Effect<string | null>) =>
+ Layer.merge(
+ Layer.succeed(LinuxBrowserSecretPath, "/bundled/browser-secret/t3-browser-secret"),
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) =>
+ Effect.gen(function* () {
+ const secret =
+ command._tag === "StandardCommand" && command.args[0] === "T3 Code (Beta)"
+ ? yield* lookup
+ : null;
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(secret === null ? 2 : 0)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.encodeText(Stream.make(secret ?? "")),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ });
+ }),
+ ),
+ ),
+ );
+
+interface RecoveryOptions {
+ readonly platform?: NodeJS.Platform;
+ readonly linuxKeyLookup?: Effect.Effect<string | null>;
+ readonly currentSecret?: string | undefined;
+}
+
function layerFor(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
+ recovery: RecoveryOptions = {},
) {
const layerEnvironment = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
- platform: "darwin",
+ platform: recovery.platform ?? "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
@@ -71,10 +186,18 @@ function layerFor(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
- const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, failDecrypt);
+ const layerSafeStorage = layerSafeStorageFor(
+ encryptionAvailable,
+ failDecrypt,
+ recovery.currentSecret,
+ );
const layerDependencies = Layer.mergeAll(
layerEnvironment,
layerSafeStorage,
+ DesktopSafeStorageIdentity.layer.pipe(
+ Layer.provide(layerEnvironment),
+ Layer.provide(layerLinuxKeyAccess(recovery.linuxKeyLookup ?? Effect.succeed(null))),
+ ),
NodeServices.layer,
fileSystemLayer,
);
@@ -91,13 +214,16 @@ function layerFor(
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
+ recovery: RecoveryOptions = {},
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
- return yield* effect.pipe(Effect.provide(layerFor(baseDir, encryptionAvailable)));
+ return yield* effect.pipe(
+ Effect.provide(layerFor(baseDir, encryptionAvailable, null, NodeServices.layer, recovery)),
+ );
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
@@ -440,4 +566,133 @@ describe("DesktopConnectionCatalogStore", () => {
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
+
+ const writeBetaCatalog = (
+ platform: NodeJS.Platform,
+ encryptedCatalog = encryptBetaCatalog(platform),
+ ) =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
+ const contents = `${JSON.stringify({
+ version: 1,
+ encryptedCatalog: Base64.encode(encryptedCatalog),
+ })}\n`;
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(catalogPath, contents);
+ return { catalogPath, contents };
+ });
+
+ it.effect.each([
+ { platform: "darwin" as const, currentSecret: undefined, label: "macOS" },
+ { platform: "linux" as const, currentSecret: undefined, label: "Linux" },
+ {
+ platform: "darwin" as const,
+ currentSecret: "wrong-key-494",
+ label: "macOS with valid padding under the wrong current key",
+ },
+ ])(
+ "recovers a Beta catalog on $label and reopens it without the Beta key",
+ ({ platform, currentSecret }) =>
+ withStore(
+ Effect.gen(function* () {
+ getBetaPassword.mockReturnValue("beta-secret");
+ const fileSystem = yield* FileSystem.FileSystem;
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
+ const { catalogPath, contents } = yield* writeBetaCatalog(platform);
+
+ assert.deepStrictEqual(yield* store.get, Option.some(savedCatalog));
+ assert.notEqual(yield* fileSystem.readFileString(catalogPath), contents);
+
+ getBetaPassword.mockReturnValue(null);
+ const reopened = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
+ Effect.provide(
+ layerFor(environment.homeDirectory, true, null, NodeServices.layer, { platform }),
+ ),
+ );
+ assert.deepStrictEqual(yield* reopened.get, Option.some(savedCatalog));
+ }),
+ true,
+ { platform, currentSecret, linuxKeyLookup: Effect.succeed("beta-secret") },
+ ),
+ );
+
+ it.effect.each([
+ // This wrong key has valid CBC padding, so decryption alone cannot validate recovery.
+ { platform: "darwin" as const, secret: "wrong-key-494", label: "a wrong Beta key" },
+ { platform: "linux" as const, secret: null, label: "a missing Beta key" },
+ {
+ platform: "darwin" as const,
+ secret: "beta-secret",
+ label: "unencrypted input",
+ encryptedCatalog: Buffer.from(savedCatalog),
+ },
+ {
+ platform: "linux" as const,
+ secret: "beta-secret",
+ label: "an invalid catalog",
+ encryptedCatalog: encryptBetaCatalog("linux", '{"schemaVersion":1,"targets":null}'),
+ },
+ ])("leaves the catalog bytes intact for $label", ({ platform, secret, encryptedCatalog }) =>
+ withStore(
+ Effect.gen(function* () {
+ getBetaPassword.mockReturnValue(secret);
+ const fileSystem = yield* FileSystem.FileSystem;
+ const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
+ const { catalogPath, contents } = yield* writeBetaCatalog(platform, encryptedCatalog);
+
+ const error = yield* store.get.pipe(Effect.flip);
+ assert.instanceOf(
+ error,
+ DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
+ );
+ assert.equal(error.operation, "decrypt-catalog");
+ assert.equal(yield* fileSystem.readFileString(catalogPath), contents);
+ }),
+ true,
+ { platform, linuxKeyLookup: Effect.succeed(secret) },
+ ),
+ );
+
+ it.effect.each(["save", "clear"] as const)(
+ "preserves a concurrent %s while Beta key recovery is waiting",
+ (operation) =>
+ Effect.gen(function* () {
+ const lookupStarted = yield* Deferred.make<void>();
+ const lookupReleased = yield* Deferred.make<void>();
+ const linuxKeyLookup = Deferred.succeed(lookupStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(lookupReleased)),
+ Effect.as("beta-secret"),
+ );
+ const newer = savedCatalog.replace("Saved relay", "Updated relay");
+
+ yield* withStore(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
+ const { catalogPath } = yield* writeBetaCatalog("linux");
+ const recovery = yield* store.get.pipe(Effect.forkChild);
+ yield* Deferred.await(lookupStarted);
+ if (operation === "save") {
+ assert.isTrue(yield* store.set(newer));
+ } else {
+ yield* store.clear;
+ }
+ yield* Deferred.succeed(lookupReleased, undefined);
+ yield* Fiber.join(recovery);
+
+ assert.deepStrictEqual(
+ yield* store.get,
+ operation === "save" ? Option.some(newer) : Option.none(),
+ );
+ assert.equal(yield* fileSystem.exists(catalogPath), operation === "save");
+ }),
+ true,
+ { platform: "linux", linuxKeyLookup },
+ );
+ }),
+ );
});
diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
index a9020c36d1c..35800e67865 100644
--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
@@ -21,10 +21,12 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as Semaphore from "effect/Semaphore";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+import * as DesktopSafeStorageIdentity from "./DesktopSafeStorageIdentity.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
@@ -45,6 +47,8 @@ const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
+const decodeCatalogJsonOption = Schema.decodeOption(RuntimeConnectionCatalogDocumentJson);
+const decodeNativeCatalogJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"create-temporary-file-name",
@@ -382,9 +386,11 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
+ const safeStorageIdentity = yield* DesktopSafeStorageIdentity.DesktopSafeStorageIdentity;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
+ const writeLock = yield* Semaphore.make(1);
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
@@ -471,6 +477,40 @@ export const make = Effect.gen(function* () {
return Option.some(encoded);
});
+ const recoverPreviousIdentityCatalog = Effect.fn(
+ "desktop.connectionCatalogStore.recoverPreviousIdentityCatalog",
+ )(function* (
+ document: EncryptedConnectionCatalogDocument,
+ encryptedCatalog: Uint8Array,
+ cause: ElectronSafeStorage.ElectronSafeStorageDecryptError | Schema.SchemaError,
+ ) {
+ const recovered = Option.filter(
+ yield* safeStorageIdentity.decryptWithPreviousName(encryptedCatalog),
+ (catalog) => Option.isSome(decodeCatalogJsonOption(catalog)),
+ );
+ if (Option.isNone(recovered)) {
+ return yield* new DesktopConnectionCatalogStoreProtectionError({
+ operation: "decrypt-catalog",
+ catalogPath,
+ cause,
+ });
+ }
+ // Reading the previous key can wait on a Keychain prompt, so a newer catalog
+ // may have been saved since this one was read.
+ yield* Effect.gen(function* () {
+ const current = yield* readDocument(fileSystem, catalogPath);
+ if (Option.isSome(current) && current.value.encryptedCatalog === document.encryptedCatalog) {
+ yield* writeCatalog(recovered.value);
+ }
+ }).pipe(
+ writeLock.withPermits(1),
+ Effect.catch((error) =>
+ Effect.logWarning("Could not re-encrypt the connection catalog.", { catalogPath, error }),
+ ),
+ );
+ return recovered.value;
+ });
+
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath);
@@ -483,13 +523,14 @@ export const make = Effect.gen(function* () {
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
- Effect.mapError(
- (cause) =>
- new DesktopConnectionCatalogStoreProtectionError({
- operation: "decrypt-catalog",
- catalogPath,
- cause,
- }),
+ // CBC can decrypt with the wrong key without failing its padding check.
+ Effect.tap((catalog) =>
+ environment.platform === "darwin" || environment.platform === "linux"
+ ? decodeNativeCatalogJson(catalog)
+ : Effect.void,
+ ),
+ Effect.catch((cause) =>
+ recoverPreviousIdentityCatalog(document.value, encryptedCatalog, cause),
),
),
),
@@ -500,10 +541,11 @@ export const make = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
return false;
}
- yield* writeCatalog(catalog);
+ yield* writeCatalog(catalog).pipe(writeLock.withPermits(1));
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
+ writeLock.withPermits(1),
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts
index ecf08255feb..e3509448515 100644
--- a/apps/desktop/src/app/DesktopEnvironment.ts
+++ b/apps/desktop/src/app/DesktopEnvironment.ts
@@ -15,7 +15,10 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveLinuxDesktopEntryName } from "./DesktopEarlyElectronStartup.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
-import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
+import {
+ isNightlyDesktopVersion,
+ resolveDefaultDesktopUpdateChannel,
+} from "../updates/updateChannels.ts";
import type { OtlpProtocol } from "@t3tools/shared/observability";
export interface MakeDesktopEnvironmentInput {
@@ -110,6 +113,13 @@ export function resolveDesktopAppBranding(input: {
};
}
+// Keep Chromium's encryption identity on the names shipped before branding changed.
+export function resolveDesktopSafeStorageName(appVersion: string): string {
+ return resolveDefaultDesktopUpdateChannel(appVersion) === "nightly"
+ ? "T3 Code (Nightly)"
+ : "T3 Code (Alpha)";
+}
+
function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
if (arch === "arm64") return "arm64";
if (arch === "x64") return "x64";
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
index d27251d7b2f..9c1ef0b69b9 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
@@ -11,6 +11,8 @@ const {
hasSwitchMock,
registerSchemesMock,
setDesktopNameMock,
+ setNameMock,
+ appState,
mkdirSyncMock,
writeFileSyncMock,
copyFileSyncMock,
@@ -22,6 +24,8 @@ const {
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
setDesktopNameMock: vi.fn(),
+ setNameMock: vi.fn(),
+ appState: { version: "0.0.37", isPackaged: true },
mkdirSyncMock: vi.fn(),
writeFileSyncMock: vi.fn(),
copyFileSyncMock: vi.fn(),
@@ -32,8 +36,11 @@ const {
vi.mock("electron", () => ({
app: {
setDesktopName: setDesktopNameMock,
- getVersion: () => "0.0.37",
- isPackaged: true,
+ setName: setNameMock,
+ getVersion: () => appState.version,
+ get isPackaged() {
+ return appState.isPackaged;
+ },
getAppPath: () => "/tmp/.mount_T3/resources/app.asar",
commandLine: {
appendSwitch: appendSwitchMock,
@@ -66,6 +73,9 @@ describe("DesktopPreReadyPlatform", () => {
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
setDesktopNameMock.mockReset();
+ setNameMock.mockReset();
+ appState.version = "0.0.37";
+ appState.isPackaged = true;
mkdirSyncMock.mockReset();
writeFileSyncMock.mockReset();
copyFileSyncMock.mockReset();
@@ -248,6 +258,37 @@ describe("DesktopPreReadyPlatform", () => {
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
});
+ it.effect.each([
+ { platform: "linux" as const, version: "0.1.0", isPackaged: true },
+ { platform: "darwin" as const, version: "0.1.1-preview.20261017.3", isPackaged: false },
+ { platform: "win32" as const, version: "0.1.0", isPackaged: true },
+ ])(
+ "preserves the $platform encryption identity before startup yields",
+ ({ platform, version, isPackaged }) => {
+ appState.version = version;
+ appState.isPackaged = isPackaged;
+ getSwitchValueMock.mockReturnValue("");
+ let appName = "T3 Code (Beta)";
+ setNameMock.mockImplementation((name: string) => {
+ appName = name;
+ });
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const nameBeforeYield = Promise.resolve().then(() => appName);
+ yield* Layer.build(
+ DesktopPreReadyPlatform.layer.pipe(
+ Layer.provide(Layer.succeed(HostProcess.Platform, platform)),
+ ),
+ );
+ assert.equal(
+ yield* Effect.promise(() => nameBeforeYield),
+ platform === "win32" ? "T3 Code (Beta)" : "T3 Code (Alpha)",
+ );
+ }),
+ );
+ },
+ );
+
it.effect("keeps startup available when the early desktop entry cannot be written", () => {
getSwitchValueMock.mockReturnValue("");
mkdirSyncMock.mockImplementation(() => {
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
index 58670439a52..d9ffba80197 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
@@ -10,7 +10,7 @@ import * as Electron from "electron";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
-import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
+import { resolveDesktopAppBranding, resolveDesktopSafeStorageName } from "./DesktopEnvironment.ts";
import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
@@ -54,6 +54,11 @@ export const make = Effect.gen(function* () {
const platform = yield* HostProcess.Platform;
const homeDirectory = yield* HostProcess.HomeDirectory;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
+ // Chromium reads the safeStorage key's name before startup first yields.
+ // DesktopAppIdentity's later rename only changes the branded app name.
+ if (platform === "darwin" || platform === "linux") {
+ Electron.app.setName(resolveDesktopSafeStorageName(Electron.app.getVersion()));
+ }
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
diff --git a/apps/desktop/src/app/DesktopSafeStorageIdentity.ts b/apps/desktop/src/app/DesktopSafeStorageIdentity.ts
new file mode 100644
index 00000000000..d02fdb19f65
--- /dev/null
+++ b/apps/desktop/src/app/DesktopSafeStorageIdentity.ts
@@ -0,0 +1,63 @@
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { ChildProcessSpawner } from "effect/process";
+
+import { decryptChromiumValue } from "../preview/BrowserImport/ChromiumCookies.ts";
+import { resolveChromiumKeys } from "../preview/BrowserImport/ChromiumKeys.ts";
+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+
+export class DesktopSafeStorageIdentity extends Context.Service<
+ DesktopSafeStorageIdentity,
+ {
+ readonly decryptWithPreviousName: (
+ encrypted: Uint8Array,
+ ) => Effect.Effect<Option.Option<string>>;
+ }
+>()("@t3tools/desktop/app/DesktopSafeStorageIdentity") {}
+
+const make = Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const services = yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
+
+ const decryptWithPreviousName = Effect.fn("desktop.safeStorageIdentity.decryptWithPreviousName")(
+ function* (encrypted: Uint8Array) {
+ if (environment.platform !== "darwin" && environment.platform !== "linux") {
+ return Option.none<string>();
+ }
+ if (
+ DesktopEnvironment.resolveDesktopSafeStorageName(environment.appVersion) !==
+ "T3 Code (Alpha)"
+ ) {
+ return Option.none<string>();
+ }
+ // Cookie imports also accept plaintext; safeStorage requires an OSCrypt prefix.
+ const prefix = Buffer.from(encrypted.subarray(0, 3)).toString("latin1");
+ if (prefix !== (environment.platform === "darwin" ? "v10" : "v11")) {
+ return Option.none<string>();
+ }
+ const keys = yield* resolveChromiumKeys({
+ platform: environment.platform,
+ keychainService: "T3 Code (Beta) Safe Storage",
+ keychainAccount: "T3 Code (Beta)",
+ linuxSecretApplication: "T3 Code (Beta)",
+ }).pipe(
+ Effect.tapError((error) =>
+ Effect.logWarning("Could not read the Beta safe storage key.", {
+ reason: error.reason,
+ }),
+ ),
+ Effect.option,
+ );
+ return Option.flatMapNullishOr(keys, (material) =>
+ decryptChromiumValue(encrypted, material, "", undefined, environment.platform),
+ );
+ },
+ Effect.provide(services),
+ );
+
+ return DesktopSafeStorageIdentity.of({ decryptWithPreviousName });
+});
+
+export const layer = Layer.effect(DesktopSafeStorageIdentity, make);
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 3056ce1ea26..0aac282bbf8 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -38,6 +38,7 @@ import * as DesktopAppActivation from "./app/DesktopAppActivation.ts";
import * as DesktopWebLinks from "./app/DesktopWebLinks.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
+import * as DesktopSafeStorageIdentity from "./app/DesktopSafeStorageIdentity.ts";
import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopCliCommand from "./app/DesktopCliCommand.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
@@ -146,7 +147,10 @@ const layerDesktopFoundation = Layer.mergeAll(
DesktopLegacyLocalStorage.layer,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
- DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
+ DesktopConnectionCatalogStore.layer.pipe(
+ Layer.provideMerge(DesktopSavedEnvironments.layer),
+ Layer.provide(DesktopSafeStorageIdentity.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
+ ),
DesktopAssets.layer,
DesktopObservability.layer,
DesktopRendererHistory.layer,