Skip to content

Commit 3419cf1

Browse files
Merge remote-tracking branch 'origin/main' into l69-18633
2 parents b20ada6 + 44f977f commit 3419cf1

149 files changed

Lines changed: 9332 additions & 978 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,8 @@ export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances"
153153
const instances = yield* pool.list;
154154
yield* Effect.forEach(
155155
instances,
156-
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
156+
// Exceeds the backend's 30s graceful termination and output drain budget.
157+
(instance) => instance.stop({ timeout: Duration.seconds(45) }),
157158
{ concurrency: "unbounded" },
158159
);
159160
},

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

Lines changed: 259 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,80 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - The recovery fixtures use Chromium OSCrypt ciphertext.
2+
import * as NodeCrypto from "node:crypto";
3+
14
import * as NodeServices from "@effect/platform-node/NodeServices";
25
import { assert, describe, it } from "@effect/vitest";
36
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
47
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
8+
import * as Deferred from "effect/Deferred";
59
import * as Effect from "effect/Effect";
610
import * as Base64 from "effect/encoding/Base64";
11+
import * as Fiber from "effect/Fiber";
712
import * as FileSystem from "effect/FileSystem";
813
import * as Path from "effect/Path";
914
import * as Layer from "effect/Layer";
1015
import * as Option from "effect/Option";
1116
import * as PlatformError from "effect/PlatformError";
1217
import * as Ref from "effect/Ref";
1318
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";
1423

1524
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
25+
import { LinuxBrowserSecretPath } from "../preview/BrowserImport/LinuxBrowserSecret.ts";
1626
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
1727
import * as DesktopConfig from "./DesktopConfig.ts";
1828
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
1929
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+
};
2078

2179
const textDecoder = new TextDecoder();
2280
const textEncoder = new TextEncoder();
@@ -28,7 +86,11 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect(
2886
Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }),
2987
),
3088
);
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+
) {
3294
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
3395
isEncryptionAvailable: Effect.succeed(available),
3496
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
@@ -39,6 +101,23 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
39101
!decoded.startsWith("encrypted:") ||
40102
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
41103
) {
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+
}
42121
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
43122
cause: new Error("invalid encrypted catalog"),
44123
});
@@ -50,16 +129,52 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref<boolean> |
50129
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
51130
}
52131

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+
53167
function layerFor(
54168
baseDir: string,
55169
encryptionAvailable = true,
56170
failDecrypt: Ref.Ref<boolean> | null = null,
57171
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
172+
recovery: RecoveryOptions = {},
58173
) {
59174
const layerEnvironment = DesktopEnvironment.layer({
60175
dirname: "/repo/apps/desktop/src",
61176
homeDirectory: baseDir,
62-
platform: "darwin",
177+
platform: recovery.platform ?? "darwin",
63178
processArch: "arm64",
64179
appVersion: "1.2.3",
65180
appPath: "/repo",
@@ -71,10 +186,18 @@ function layerFor(
71186
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
72187
),
73188
);
74-
const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, failDecrypt);
189+
const layerSafeStorage = layerSafeStorageFor(
190+
encryptionAvailable,
191+
failDecrypt,
192+
recovery.currentSecret,
193+
);
75194
const layerDependencies = Layer.mergeAll(
76195
layerEnvironment,
77196
layerSafeStorage,
197+
DesktopSafeStorageIdentity.layer.pipe(
198+
Layer.provide(layerEnvironment),
199+
Layer.provide(layerLinuxKeyAccess(recovery.linuxKeyLookup ?? Effect.succeed(null))),
200+
),
78201
NodeServices.layer,
79202
fileSystemLayer,
80203
);
@@ -91,13 +214,16 @@ function layerFor(
91214
const withStore = <A, E, R>(
92215
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
93216
encryptionAvailable = true,
217+
recovery: RecoveryOptions = {},
94218
) =>
95219
Effect.gen(function* () {
96220
const fileSystem = yield* FileSystem.FileSystem;
97221
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
98222
prefix: "t3-desktop-connection-catalog-test-",
99223
});
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+
);
101227
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
102228

103229
describe("DesktopConnectionCatalogStore", () => {
@@ -440,4 +566,133 @@ describe("DesktopConnectionCatalogStore", () => {
440566
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
441567
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
442568
);
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+
);
443698
});

0 commit comments

Comments
 (0)