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

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

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

Synced Nov 22, 22:00 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Jordan Munch O'Hare committed Oct 20, 2026 at 07:26 UTC 3819eb367a29bf52fd39a194e1453b299abe9b55
7 files changed +437 -17
apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
+259 -4
@@ -1,9 +1,14 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - The recovery fixtures use Chromium OSCrypt ciphertext.
2 +import * as NodeCrypto from "node:crypto";
3 +
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { assert, describe, it } from "@effect/vitest";
6 import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
7 import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
8 +import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 import * as Base64 from "effect/encoding/Base64";
11 +import * as Fiber from "effect/Fiber";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Path from "effect/Path";
14 import * as Layer from "effect/Layer";
@@ -11,12 +16,65 @@ import * as Option from "effect/Option";
16 import * as PlatformError from "effect/PlatformError";
17 import * as Ref from "effect/Ref";
18 import * as Schema from "effect/Schema";
19 +import * as Sink from "effect/Sink";
20 +import * as Stream from "effect/Stream";
21 +import { ChildProcessSpawner } from "effect/process";
22 +import { beforeEach, vi } from "vite-plus/test";
23
24 import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
25 +import { LinuxBrowserSecretPath } from "../preview/BrowserImport/LinuxBrowserSecret.ts";
26 import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
27 import * as DesktopConfig from "./DesktopConfig.ts";
28 import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
29 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
30 +import * as DesktopSafeStorageIdentity from "./DesktopSafeStorageIdentity.ts";
31 +
32 +const { getBetaPassword } = vi.hoisted(() => ({
33 + getBetaPassword: vi.fn<() => string | null>(),
34 +}));
35 +
36 +vi.mock("@napi-rs/keyring", () => ({
37 + Entry: class {
38 + readonly getPassword;
39 + constructor(service: string, account: string) {
40 + this.getPassword = () =>
41 + service === "T3 Code (Beta) Safe Storage" && account === "T3 Code (Beta)"
42 + ? getBetaPassword()
43 + : null;
44 + }
45 + },
46 +}));
47 +
48 +beforeEach(() => {
49 + getBetaPassword.mockReset().mockReturnValue(null);
50 +});
51 +
52 +const savedCatalog = JSON.stringify({
53 + schemaVersion: 1,
54 + targets: [
55 + { _tag: "RelayConnectionTarget", environmentId: "relay-environment", label: "Saved relay" },
56 + ],
57 + profiles: [],
58 + credentials: [],
59 + remoteDpopTokens: [],
60 + disabledEnvironmentIds: [],
61 +});
62 +
63 +const encryptBetaCatalog = (platform: NodeJS.Platform, catalog = savedCatalog) => {
64 + const key = NodeCrypto.pbkdf2Sync(
65 + "beta-secret",
66 + "saltysalt",
67 + platform === "darwin" ? 1003 : 1,
68 + 16,
69 + "sha1",
70 + );
71 + const cipher = NodeCrypto.createCipheriv("aes-128-cbc", key, Buffer.alloc(16, " "));
72 + return Buffer.concat([
73 + Buffer.from(platform === "darwin" ? "v10" : "v11"),
74 + cipher.update(catalog, "utf8"),
75 + cipher.final(),
76 + ]);
77 +};
78
79 const textDecoder = new TextDecoder();
80 const textEncoder = new TextEncoder();
@@ -28,7 +86,11 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect(
86 Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }),
87 ),
88 );
31 -function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
89 +function layerSafeStorageFor(
90 + available: boolean,
91 + failDecrypt: Ref.Ref<boolean> | null = null,
92 + currentSecret?: string,
93 +) {
94 return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
95 isEncryptionAvailable: Effect.succeed(available),
96 encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
@@ -39,6 +101,23 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
101 !decoded.startsWith("encrypted:") ||
102 (failDecrypt !== null && (yield* Ref.get(failDecrypt)))
103 ) {
104 + if (currentSecret !== undefined) {
105 + return yield* Effect.try({
106 + try: () => {
107 + const key = NodeCrypto.pbkdf2Sync(currentSecret, "saltysalt", 1003, 16, "sha1");
108 + const decipher = NodeCrypto.createDecipheriv(
109 + "aes-128-cbc",
110 + key,
111 + Buffer.alloc(16, " "),
112 + );
113 + return Buffer.concat([
114 + decipher.update(value.subarray(3)),
115 + decipher.final(),
116 + ]).toString("utf8");
117 + },
118 + catch: (cause) => new ElectronSafeStorage.ElectronSafeStorageDecryptError({ cause }),
119 + });
120 + }
121 return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
122 cause: new Error("invalid encrypted catalog"),
123 });
@@ -50,16 +129,52 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
129 } satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
130 }
131
132 +const layerLinuxKeyAccess = (lookup: Effect.Effect<string | null>) =>
133 + Layer.merge(
134 + Layer.succeed(LinuxBrowserSecretPath, "/bundled/browser-secret/t3-browser-secret"),
135 + Layer.succeed(
136 + ChildProcessSpawner.ChildProcessSpawner,
137 + ChildProcessSpawner.make((command) =>
138 + Effect.gen(function* () {
139 + const secret =
140 + command._tag === "StandardCommand" && command.args[0] === "T3 Code (Beta)"
141 + ? yield* lookup
142 + : null;
143 + return ChildProcessSpawner.makeHandle({
144 + pid: ChildProcessSpawner.ProcessId(1),
145 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(secret === null ? 2 : 0)),
146 + isRunning: Effect.succeed(false),
147 + kill: () => Effect.void,
148 + unref: Effect.succeed(Effect.void),
149 + stdin: Sink.drain,
150 + stdout: Stream.encodeText(Stream.make(secret ?? "")),
151 + stderr: Stream.empty,
152 + all: Stream.empty,
153 + getInputFd: () => Sink.drain,
154 + getOutputFd: () => Stream.empty,
155 + });
156 + }),
157 + ),
158 + ),
159 + );
160 +
161 +interface RecoveryOptions {
162 + readonly platform?: NodeJS.Platform;
163 + readonly linuxKeyLookup?: Effect.Effect<string | null>;
164 + readonly currentSecret?: string | undefined;
165 +}
166 +
167 function layerFor(
168 baseDir: string,
169 encryptionAvailable = true,
170 failDecrypt: Ref.Ref<boolean> | null = null,
171 fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
172 + recovery: RecoveryOptions = {},
173 ) {
174 const layerEnvironment = DesktopEnvironment.layer({
175 dirname: "/repo/apps/desktop/src",
176 homeDirectory: baseDir,
62 - platform: "darwin",
177 + platform: recovery.platform ?? "darwin",
178 processArch: "arm64",
179 appVersion: "1.2.3",
180 appPath: "/repo",
@@ -71,10 +186,18 @@ function layerFor(
186 Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
187 ),
188 );
74 - const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, failDecrypt);
189 + const layerSafeStorage = layerSafeStorageFor(
190 + encryptionAvailable,
191 + failDecrypt,
192 + recovery.currentSecret,
193 + );
194 const layerDependencies = Layer.mergeAll(
195 layerEnvironment,
196 layerSafeStorage,
197 + DesktopSafeStorageIdentity.layer.pipe(
198 + Layer.provide(layerEnvironment),
199 + Layer.provide(layerLinuxKeyAccess(recovery.linuxKeyLookup ?? Effect.succeed(null))),
200 + ),
201 NodeServices.layer,
202 fileSystemLayer,
203 );
@@ -91,13 +214,16 @@ function layerFor(
214 const withStore = <A, E, R>(
215 effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
216 encryptionAvailable = true,
217 + recovery: RecoveryOptions = {},
218 ) =>
219 Effect.gen(function* () {
220 const fileSystem = yield* FileSystem.FileSystem;
221 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
222 prefix: "t3-desktop-connection-catalog-test-",
223 });
100 - return yield* effect.pipe(Effect.provide(layerFor(baseDir, encryptionAvailable)));
224 + return yield* effect.pipe(
225 + Effect.provide(layerFor(baseDir, encryptionAvailable, null, NodeServices.layer, recovery)),
226 + );
227 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
228
229 describe("DesktopConnectionCatalogStore", () => {
@@ -440,4 +566,133 @@ describe("DesktopConnectionCatalogStore", () => {
566 assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
567 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
568 );
569 +
570 + const writeBetaCatalog = (
571 + platform: NodeJS.Platform,
572 + encryptedCatalog = encryptBetaCatalog(platform),
573 + ) =>
574 + Effect.gen(function* () {
575 + const path = yield* Path.Path;
576 + const environment = yield* DesktopEnvironment.DesktopEnvironment;
577 + const fileSystem = yield* FileSystem.FileSystem;
578 + const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
579 + const contents = `${JSON.stringify({
580 + version: 1,
581 + encryptedCatalog: Base64.encode(encryptedCatalog),
582 + })}\n`;
583 + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
584 + yield* fileSystem.writeFileString(catalogPath, contents);
585 + return { catalogPath, contents };
586 + });
587 +
588 + it.effect.each([
589 + { platform: "darwin" as const, currentSecret: undefined, label: "macOS" },
590 + { platform: "linux" as const, currentSecret: undefined, label: "Linux" },
591 + {
592 + platform: "darwin" as const,
593 + currentSecret: "wrong-key-494",
594 + label: "macOS with valid padding under the wrong current key",
595 + },
596 + ])(
597 + "recovers a Beta catalog on $label and reopens it without the Beta key",
598 + ({ platform, currentSecret }) =>
599 + withStore(
600 + Effect.gen(function* () {
601 + getBetaPassword.mockReturnValue("beta-secret");
602 + const fileSystem = yield* FileSystem.FileSystem;
603 + const environment = yield* DesktopEnvironment.DesktopEnvironment;
604 + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
605 + const { catalogPath, contents } = yield* writeBetaCatalog(platform);
606 +
607 + assert.deepStrictEqual(yield* store.get, Option.some(savedCatalog));
608 + assert.notEqual(yield* fileSystem.readFileString(catalogPath), contents);
609 +
610 + getBetaPassword.mockReturnValue(null);
611 + const reopened = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
612 + Effect.provide(
613 + layerFor(environment.homeDirectory, true, null, NodeServices.layer, { platform }),
614 + ),
615 + );
616 + assert.deepStrictEqual(yield* reopened.get, Option.some(savedCatalog));
617 + }),
618 + true,
619 + { platform, currentSecret, linuxKeyLookup: Effect.succeed("beta-secret") },
620 + ),
621 + );
622 +
623 + it.effect.each([
624 + // This wrong key has valid CBC padding, so decryption alone cannot validate recovery.
625 + { platform: "darwin" as const, secret: "wrong-key-494", label: "a wrong Beta key" },
626 + { platform: "linux" as const, secret: null, label: "a missing Beta key" },
627 + {
628 + platform: "darwin" as const,
629 + secret: "beta-secret",
630 + label: "unencrypted input",
631 + encryptedCatalog: Buffer.from(savedCatalog),
632 + },
633 + {
634 + platform: "linux" as const,
635 + secret: "beta-secret",
636 + label: "an invalid catalog",
637 + encryptedCatalog: encryptBetaCatalog("linux", '{"schemaVersion":1,"targets":null}'),
638 + },
639 + ])("leaves the catalog bytes intact for $label", ({ platform, secret, encryptedCatalog }) =>
640 + withStore(
641 + Effect.gen(function* () {
642 + getBetaPassword.mockReturnValue(secret);
643 + const fileSystem = yield* FileSystem.FileSystem;
644 + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
645 + const { catalogPath, contents } = yield* writeBetaCatalog(platform, encryptedCatalog);
646 +
647 + const error = yield* store.get.pipe(Effect.flip);
648 + assert.instanceOf(
649 + error,
650 + DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
651 + );
652 + assert.equal(error.operation, "decrypt-catalog");
653 + assert.equal(yield* fileSystem.readFileString(catalogPath), contents);
654 + }),
655 + true,
656 + { platform, linuxKeyLookup: Effect.succeed(secret) },
657 + ),
658 + );
659 +
660 + it.effect.each(["save", "clear"] as const)(
661 + "preserves a concurrent %s while Beta key recovery is waiting",
662 + (operation) =>
663 + Effect.gen(function* () {
664 + const lookupStarted = yield* Deferred.make<void>();
665 + const lookupReleased = yield* Deferred.make<void>();
666 + const linuxKeyLookup = Deferred.succeed(lookupStarted, undefined).pipe(
667 + Effect.andThen(Deferred.await(lookupReleased)),
668 + Effect.as("beta-secret"),
669 + );
670 + const newer = savedCatalog.replace("Saved relay", "Updated relay");
671 +
672 + yield* withStore(
673 + Effect.gen(function* () {
674 + const fileSystem = yield* FileSystem.FileSystem;
675 + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
676 + const { catalogPath } = yield* writeBetaCatalog("linux");
677 + const recovery = yield* store.get.pipe(Effect.forkChild);
678 + yield* Deferred.await(lookupStarted);
679 + if (operation === "save") {
680 + assert.isTrue(yield* store.set(newer));
681 + } else {
682 + yield* store.clear;
683 + }
684 + yield* Deferred.succeed(lookupReleased, undefined);
685 + yield* Fiber.join(recovery);
686 +
687 + assert.deepStrictEqual(
688 + yield* store.get,
689 + operation === "save" ? Option.some(newer) : Option.none(),
690 + );
691 + assert.equal(yield* fileSystem.exists(catalogPath), operation === "save");
692 + }),
693 + true,
694 + { platform: "linux", linuxKeyLookup },
695 + );
696 + }),
697 + );
698 });
apps/desktop/src/app/DesktopConnectionCatalogStore.ts
+50 -8
@@ -21,10 +21,12 @@ import * as Layer from "effect/Layer";
21 import * as Option from "effect/Option";
22 import * as Path from "effect/Path";
23 import * as Schema from "effect/Schema";
24 +import * as Semaphore from "effect/Semaphore";
25
26 import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
27 import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
28 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
29 +import * as DesktopSafeStorageIdentity from "./DesktopSafeStorageIdentity.ts";
30
31 const EncryptedConnectionCatalogDocument = Schema.Struct({
32 version: Schema.Literal(1),
@@ -45,6 +47,8 @@ const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
47 const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
48 RuntimeConnectionCatalogDocumentJson,
49 );
50 +const decodeCatalogJsonOption = Schema.decodeOption(RuntimeConnectionCatalogDocumentJson);
51 +const decodeNativeCatalogJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
52
53 const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
54 "create-temporary-file-name",
@@ -382,9 +386,11 @@ export const make = Effect.gen(function* () {
386 const fileSystem = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
389 + const safeStorageIdentity = yield* DesktopSafeStorageIdentity.DesktopSafeStorageIdentity;
390 const crypto = yield* Crypto.Crypto;
391 const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
392 const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
393 + const writeLock = yield* Semaphore.make(1);
394 const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
395 Effect.mapError(
396 (cause) =>
@@ -471,6 +477,40 @@ export const make = Effect.gen(function* () {
477 return Option.some(encoded);
478 });
479
480 + const recoverPreviousIdentityCatalog = Effect.fn(
481 + "desktop.connectionCatalogStore.recoverPreviousIdentityCatalog",
482 + )(function* (
483 + document: EncryptedConnectionCatalogDocument,
484 + encryptedCatalog: Uint8Array,
485 + cause: ElectronSafeStorage.ElectronSafeStorageDecryptError | Schema.SchemaError,
486 + ) {
487 + const recovered = Option.filter(
488 + yield* safeStorageIdentity.decryptWithPreviousName(encryptedCatalog),
489 + (catalog) => Option.isSome(decodeCatalogJsonOption(catalog)),
490 + );
491 + if (Option.isNone(recovered)) {
492 + return yield* new DesktopConnectionCatalogStoreProtectionError({
493 + operation: "decrypt-catalog",
494 + catalogPath,
495 + cause,
496 + });
497 + }
498 + // Reading the previous key can wait on a Keychain prompt, so a newer catalog
499 + // may have been saved since this one was read.
500 + yield* Effect.gen(function* () {
501 + const current = yield* readDocument(fileSystem, catalogPath);
502 + if (Option.isSome(current) && current.value.encryptedCatalog === document.encryptedCatalog) {
503 + yield* writeCatalog(recovered.value);
504 + }
505 + }).pipe(
506 + writeLock.withPermits(1),
507 + Effect.catch((error) =>
508 + Effect.logWarning("Could not re-encrypt the connection catalog.", { catalogPath, error }),
509 + ),
510 + );
511 + return recovered.value;
512 + });
513 +
514 return DesktopConnectionCatalogStore.of({
515 get: Effect.gen(function* () {
516 const document = yield* readDocument(fileSystem, catalogPath);
@@ -483,13 +523,14 @@ export const make = Effect.gen(function* () {
523 const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
524 Effect.flatMap((encryptedCatalog) =>
525 safeStorage.decryptString(encryptedCatalog).pipe(
486 - Effect.mapError(
487 - (cause) =>
488 - new DesktopConnectionCatalogStoreProtectionError({
489 - operation: "decrypt-catalog",
490 - catalogPath,
491 - cause,
492 - }),
526 + // CBC can decrypt with the wrong key without failing its padding check.
527 + Effect.tap((catalog) =>
528 + environment.platform === "darwin" || environment.platform === "linux"
529 + ? decodeNativeCatalogJson(catalog)
530 + : Effect.void,
531 + ),
532 + Effect.catch((cause) =>
533 + recoverPreviousIdentityCatalog(document.value, encryptedCatalog, cause),
534 ),
535 ),
536 ),
@@ -500,10 +541,11 @@ export const make = Effect.gen(function* () {
541 if (!(yield* encryptionAvailable)) {
542 return false;
543 }
503 - yield* writeCatalog(catalog);
544 + yield* writeCatalog(catalog).pipe(writeLock.withPermits(1));
545 return true;
546 }),
547 clear: fileSystem.remove(catalogPath, { force: true }).pipe(
548 + writeLock.withPermits(1),
549 Effect.catch((error) =>
550 Effect.logWarning("Could not clear the desktop connection catalog.", {
551 catalogPath,
apps/desktop/src/app/DesktopEnvironment.ts
+11 -1
@@ -15,7 +15,10 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
15 import * as DesktopConfig from "./DesktopConfig.ts";
16 import { resolveLinuxDesktopEntryName } from "./DesktopEarlyElectronStartup.ts";
17 import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
18 -import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
18 +import {
19 + isNightlyDesktopVersion,
20 + resolveDefaultDesktopUpdateChannel,
21 +} from "../updates/updateChannels.ts";
22 import type { OtlpProtocol } from "@t3tools/shared/observability";
23
24 export interface MakeDesktopEnvironmentInput {
@@ -110,6 +113,13 @@ export function resolveDesktopAppBranding(input: {
113 };
114 }
115
116 +// Keep Chromium's encryption identity on the names shipped before branding changed.
117 +export function resolveDesktopSafeStorageName(appVersion: string): string {
118 + return resolveDefaultDesktopUpdateChannel(appVersion) === "nightly"
119 + ? "T3 Code (Nightly)"
120 + : "T3 Code (Alpha)";
121 +}
122 +
123 function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
124 if (arch === "arm64") return "arm64";
125 if (arch === "x64") return "x64";
apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+43 -2
@@ -11,6 +11,8 @@ const {
11 hasSwitchMock,
12 registerSchemesMock,
13 setDesktopNameMock,
14 + setNameMock,
15 + appState,
16 mkdirSyncMock,
17 writeFileSyncMock,
18 copyFileSyncMock,
@@ -22,6 +24,8 @@ const {
24 hasSwitchMock: vi.fn(),
25 registerSchemesMock: vi.fn(),
26 setDesktopNameMock: vi.fn(),
27 + setNameMock: vi.fn(),
28 + appState: { version: "0.0.37", isPackaged: true },
29 mkdirSyncMock: vi.fn(),
30 writeFileSyncMock: vi.fn(),
31 copyFileSyncMock: vi.fn(),
@@ -32,8 +36,11 @@ const {
36 vi.mock("electron", () => ({
37 app: {
38 setDesktopName: setDesktopNameMock,
35 - getVersion: () => "0.0.37",
36 - isPackaged: true,
39 + setName: setNameMock,
40 + getVersion: () => appState.version,
41 + get isPackaged() {
42 + return appState.isPackaged;
43 + },
44 getAppPath: () => "/tmp/.mount_T3/resources/app.asar",
45 commandLine: {
46 appendSwitch: appendSwitchMock,
@@ -66,6 +73,9 @@ describe("DesktopPreReadyPlatform", () => {
73 hasSwitchMock.mockReset();
74 registerSchemesMock.mockReset();
75 setDesktopNameMock.mockReset();
76 + setNameMock.mockReset();
77 + appState.version = "0.0.37";
78 + appState.isPackaged = true;
79 mkdirSyncMock.mockReset();
80 writeFileSyncMock.mockReset();
81 copyFileSyncMock.mockReset();
@@ -248,6 +258,37 @@ describe("DesktopPreReadyPlatform", () => {
258 ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
259 });
260
261 + it.effect.each([
262 + { platform: "linux" as const, version: "0.1.0", isPackaged: true },
263 + { platform: "darwin" as const, version: "0.1.1-preview.20261017.3", isPackaged: false },
264 + { platform: "win32" as const, version: "0.1.0", isPackaged: true },
265 + ])(
266 + "preserves the $platform encryption identity before startup yields",
267 + ({ platform, version, isPackaged }) => {
268 + appState.version = version;
269 + appState.isPackaged = isPackaged;
270 + getSwitchValueMock.mockReturnValue("");
271 + let appName = "T3 Code (Beta)";
272 + setNameMock.mockImplementation((name: string) => {
273 + appName = name;
274 + });
275 + return Effect.scoped(
276 + Effect.gen(function* () {
277 + const nameBeforeYield = Promise.resolve().then(() => appName);
278 + yield* Layer.build(
279 + DesktopPreReadyPlatform.layer.pipe(
280 + Layer.provide(Layer.succeed(HostProcess.Platform, platform)),
281 + ),
282 + );
283 + assert.equal(
284 + yield* Effect.promise(() => nameBeforeYield),
285 + platform === "win32" ? "T3 Code (Beta)" : "T3 Code (Alpha)",
286 + );
287 + }),
288 + );
289 + },
290 + );
291 +
292 it.effect("keeps startup available when the early desktop entry cannot be written", () => {
293 getSwitchValueMock.mockReturnValue("");
294 mkdirSyncMock.mockImplementation(() => {
apps/desktop/src/app/DesktopPreReadyPlatform.ts
+6 -1
@@ -10,7 +10,7 @@ import * as Electron from "electron";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11
12 import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
13 -import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
13 +import { resolveDesktopAppBranding, resolveDesktopSafeStorageName } from "./DesktopEnvironment.ts";
14 import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
15 import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
16
@@ -54,6 +54,11 @@ export const make = Effect.gen(function* () {
54 const platform = yield* HostProcess.Platform;
55 const homeDirectory = yield* HostProcess.HomeDirectory;
56 return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
57 + // Chromium reads the safeStorage key's name before startup first yields.
58 + // DesktopAppIdentity's later rename only changes the branded app name.
59 + if (platform === "darwin" || platform === "linux") {
60 + Electron.app.setName(resolveDesktopSafeStorageName(Electron.app.getVersion()));
61 + }
62 const linuxPasswordStoreCommandLine =
63 platform === "linux"
64 ? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
apps/desktop/src/app/DesktopSafeStorageIdentity.ts new
+63
@@ -0,0 +1,63 @@
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 +import { ChildProcessSpawner } from "effect/process";
6 +
7 +import { decryptChromiumValue } from "../preview/BrowserImport/ChromiumCookies.ts";
8 +import { resolveChromiumKeys } from "../preview/BrowserImport/ChromiumKeys.ts";
9 +import * as DesktopEnvironment from "./DesktopEnvironment.ts";
10 +
11 +export class DesktopSafeStorageIdentity extends Context.Service<
12 + DesktopSafeStorageIdentity,
13 + {
14 + readonly decryptWithPreviousName: (
15 + encrypted: Uint8Array,
16 + ) => Effect.Effect<Option.Option<string>>;
17 + }
18 +>()("@t3tools/desktop/app/DesktopSafeStorageIdentity") {}
19 +
20 +const make = Effect.gen(function* () {
21 + const environment = yield* DesktopEnvironment.DesktopEnvironment;
22 + const services = yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
23 +
24 + const decryptWithPreviousName = Effect.fn("desktop.safeStorageIdentity.decryptWithPreviousName")(
25 + function* (encrypted: Uint8Array) {
26 + if (environment.platform !== "darwin" && environment.platform !== "linux") {
27 + return Option.none<string>();
28 + }
29 + if (
30 + DesktopEnvironment.resolveDesktopSafeStorageName(environment.appVersion) !==
31 + "T3 Code (Alpha)"
32 + ) {
33 + return Option.none<string>();
34 + }
35 + // Cookie imports also accept plaintext; safeStorage requires an OSCrypt prefix.
36 + const prefix = Buffer.from(encrypted.subarray(0, 3)).toString("latin1");
37 + if (prefix !== (environment.platform === "darwin" ? "v10" : "v11")) {
38 + return Option.none<string>();
39 + }
40 + const keys = yield* resolveChromiumKeys({
41 + platform: environment.platform,
42 + keychainService: "T3 Code (Beta) Safe Storage",
43 + keychainAccount: "T3 Code (Beta)",
44 + linuxSecretApplication: "T3 Code (Beta)",
45 + }).pipe(
46 + Effect.tapError((error) =>
47 + Effect.logWarning("Could not read the Beta safe storage key.", {
48 + reason: error.reason,
49 + }),
50 + ),
51 + Effect.option,
52 + );
53 + return Option.flatMapNullishOr(keys, (material) =>
54 + decryptChromiumValue(encrypted, material, "", undefined, environment.platform),
55 + );
56 + },
57 + Effect.provide(services),
58 + );
59 +
60 + return DesktopSafeStorageIdentity.of({ decryptWithPreviousName });
61 +});
62 +
63 +export const layer = Layer.effect(DesktopSafeStorageIdentity, make);
apps/desktop/src/main.ts
+5 -1
@@ -38,6 +38,7 @@ import * as DesktopAppActivation from "./app/DesktopAppActivation.ts";
38 import * as DesktopWebLinks from "./app/DesktopWebLinks.ts";
39 import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
40 import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
41 +import * as DesktopSafeStorageIdentity from "./app/DesktopSafeStorageIdentity.ts";
42 import * as DesktopClerk from "./app/DesktopClerk.ts";
43 import * as DesktopCliCommand from "./app/DesktopCliCommand.ts";
44 import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
@@ -146,7 +147,10 @@ const layerDesktopFoundation = Layer.mergeAll(
147 DesktopLegacyLocalStorage.layer,
148 DesktopAppSettings.layer,
149 DesktopClientSettings.layer,
149 - DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
150 + DesktopConnectionCatalogStore.layer.pipe(
151 + Layer.provideMerge(DesktopSavedEnvironments.layer),
152 + Layer.provide(DesktopSafeStorageIdentity.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
153 + ),
154 DesktopAssets.layer,
155 DesktopObservability.layer,
156 DesktopRendererHistory.layer,