Skip to content

Commit 3192c55

Browse files
jeprecatedclaude
andcommitted
fix(desktop): a recovered catalog no longer overwrites a newer save
Reading the previous safe-storage key can wait on a Keychain prompt. A catalog saved during that wait was overwritten by the recovered one. Catalog writes now share a lock, and the recovery write only happens if the file still holds the catalog that was recovered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7aafded commit 3192c55

2 files changed

Lines changed: 61 additions & 13 deletions

File tree

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

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, describe, it } from "@effect/vitest";
33
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
44
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
5+
import * as Deferred from "effect/Deferred";
56
import * as Effect from "effect/Effect";
67
import * as Base64 from "effect/encoding/Base64";
8+
import * as Fiber from "effect/Fiber";
79
import * as FileSystem from "effect/FileSystem";
810
import * as Path from "effect/Path";
911
import * as Layer from "effect/Layer";
@@ -51,25 +53,26 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
5153
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
5254
}
5355

54-
const layerPreviousSafeStorageIdentity = Layer.succeed(
55-
DesktopSafeStorageIdentity.DesktopSafeStorageIdentity,
56-
{
56+
const layerPreviousSafeStorageIdentity = (previousKeyLookup: Effect.Effect<void>) =>
57+
Layer.succeed(DesktopSafeStorageIdentity.DesktopSafeStorageIdentity, {
5758
decryptWithPreviousName: (value) => {
5859
const decoded = textDecoder.decode(value);
59-
return Effect.succeed(
60-
decoded.startsWith("previous:")
61-
? Option.some(decoded.slice("previous:".length))
62-
: Option.none(),
60+
return previousKeyLookup.pipe(
61+
Effect.as(
62+
decoded.startsWith("previous:")
63+
? Option.some(decoded.slice("previous:".length))
64+
: Option.none(),
65+
),
6366
);
6467
},
65-
} satisfies DesktopSafeStorageIdentity.DesktopSafeStorageIdentity["Service"],
66-
);
68+
} satisfies DesktopSafeStorageIdentity.DesktopSafeStorageIdentity["Service"]);
6769

6870
function layerFor(
6971
baseDir: string,
7072
encryptionAvailable = true,
7173
failDecrypt: Ref.Ref<boolean> | null = null,
7274
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
75+
previousKeyLookup: Effect.Effect<void> = Effect.void,
7376
) {
7477
const layerEnvironment = DesktopEnvironment.layer({
7578
dirname: "/repo/apps/desktop/src",
@@ -90,7 +93,7 @@ function layerFor(
9093
const layerDependencies = Layer.mergeAll(
9194
layerEnvironment,
9295
layerSafeStorage,
93-
layerPreviousSafeStorageIdentity,
96+
layerPreviousSafeStorageIdentity(previousKeyLookup),
9497
NodeServices.layer,
9598
fileSystemLayer,
9699
);
@@ -489,6 +492,35 @@ describe("DesktopConnectionCatalogStore", () => {
489492
),
490493
);
491494

495+
it.effect("keeps a catalog saved while the previous key was being read", () =>
496+
Effect.gen(function* () {
497+
const fileSystem = yield* FileSystem.FileSystem;
498+
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
499+
prefix: "t3-desktop-connection-catalog-test-",
500+
});
501+
const lookupStarted = yield* Deferred.make<void>();
502+
const lookupReleased = yield* Deferred.make<void>();
503+
const previousKeyLookup = Deferred.succeed(lookupStarted, undefined).pipe(
504+
Effect.andThen(Deferred.await(lookupReleased)),
505+
);
506+
const previous = '{"schemaVersion":1,"targets":[]}';
507+
const newer = '{"schemaVersion":1,"targets":[{"newer":true}]}';
508+
509+
yield* Effect.gen(function* () {
510+
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
511+
yield* writeEncryptedCatalog(`previous:${previous}`);
512+
513+
const recovery = yield* store.get.pipe(Effect.forkChild);
514+
yield* Deferred.await(lookupStarted);
515+
assert.isTrue(yield* store.set(newer));
516+
yield* Deferred.succeed(lookupReleased, undefined);
517+
518+
assert.deepStrictEqual(yield* Fiber.join(recovery), Option.some(previous));
519+
assert.deepStrictEqual(yield* store.get, Option.some(newer));
520+
}).pipe(Effect.provide(layerFor(baseDir, true, null, NodeServices.layer, previousKeyLookup)));
521+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
522+
);
523+
492524
it.effect("keeps the catalog when the previous name yields no catalog", () =>
493525
withStore(
494526
Effect.gen(function* () {

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

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import * as Layer from "effect/Layer";
2121
import * as Option from "effect/Option";
2222
import * as Path from "effect/Path";
2323
import * as Schema from "effect/Schema";
24+
import * as Semaphore from "effect/Semaphore";
2425

2526
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
2627
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
@@ -391,6 +392,7 @@ export const make = Effect.gen(function* () {
391392
const crypto = yield* Crypto.Crypto;
392393
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
393394
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
395+
const writeLock = yield* Semaphore.make(1);
394396
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
395397
Effect.mapError(
396398
(cause) =>
@@ -482,6 +484,7 @@ export const make = Effect.gen(function* () {
482484
const recoverPreviousIdentityCatalog = Effect.fn(
483485
"desktop.connectionCatalogStore.recoverPreviousIdentityCatalog",
484486
)(function* (
487+
document: EncryptedConnectionCatalogDocument,
485488
encryptedCatalog: Uint8Array,
486489
cause: ElectronSafeStorage.ElectronSafeStorageDecryptError,
487490
) {
@@ -496,7 +499,15 @@ export const make = Effect.gen(function* () {
496499
cause,
497500
});
498501
}
499-
yield* writeCatalog(recovered.value).pipe(
502+
// Reading the previous key can wait on a Keychain prompt, so a newer catalog
503+
// may have been saved since this one was read.
504+
yield* Effect.gen(function* () {
505+
const current = yield* readDocument(fileSystem, catalogPath);
506+
if (Option.isSome(current) && current.value.encryptedCatalog === document.encryptedCatalog) {
507+
yield* writeCatalog(recovered.value);
508+
}
509+
}).pipe(
510+
writeLock.withPermits(1),
500511
Effect.catch((error) =>
501512
Effect.logWarning("Could not re-encrypt the connection catalog.", { catalogPath, error }),
502513
),
@@ -517,7 +528,11 @@ export const make = Effect.gen(function* () {
517528
Effect.flatMap((encryptedCatalog) =>
518529
safeStorage
519530
.decryptString(encryptedCatalog)
520-
.pipe(Effect.catch((cause) => recoverPreviousIdentityCatalog(encryptedCatalog, cause))),
531+
.pipe(
532+
Effect.catch((cause) =>
533+
recoverPreviousIdentityCatalog(document.value, encryptedCatalog, cause),
534+
),
535+
),
521536
),
522537
);
523538
return Option.some(decrypted);
@@ -526,10 +541,11 @@ export const make = Effect.gen(function* () {
526541
if (!(yield* encryptionAvailable)) {
527542
return false;
528543
}
529-
yield* writeCatalog(catalog);
544+
yield* writeCatalog(catalog).pipe(writeLock.withPermits(1));
530545
return true;
531546
}),
532547
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
548+
writeLock.withPermits(1),
533549
Effect.catch((error) =>
534550
Effect.logWarning("Could not clear the desktop connection catalog.", {
535551
catalogPath,

0 commit comments

Comments
 (0)