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

main
ts 542 lines 17.1 KB
Raw
1 import {
2 BearerConnectionCredential,
3 BearerConnectionProfile,
4 BearerConnectionTarget,
5 RelayConnectionTarget,
6 SshConnectionProfile,
7 SshConnectionTarget,
8 } from "@t3tools/client-runtime/connection";
9 import {
10 ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
11 type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
12 } from "@t3tools/client-runtime/platform";
13 import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
14 import { fromLenientJson } from "@t3tools/shared/schemaJson";
15 import * as Context from "effect/Context";
16 import * as SecureRandom from "effect/crypto/SecureRandom";
17 import * as Effect from "effect/Effect";
18 import * as Clock from "effect/Clock";
19 import * as Base64 from "effect/encoding/Base64";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Layer from "effect/Layer";
22 import * as Option from "effect/Option";
23 import * as Path from "effect/Path";
24 import * as Schema from "effect/Schema";
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
30 const EncryptedConnectionCatalogDocument = Schema.Struct({
31 version: Schema.Literal(1),
32 encryptedCatalog: Schema.String,
33 });
34 type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
35
36 const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
37 const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
38 EncryptedConnectionCatalogDocumentJson,
39 );
40 const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
41 EncryptedConnectionCatalogDocumentJson,
42 );
43 const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
44 RuntimeConnectionCatalogDocument,
45 );
46 const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
47 RuntimeConnectionCatalogDocumentJson,
48 );
49 const decodeRuntimeConnectionCatalogDocumentJson = Schema.decodeEffect(
50 RuntimeConnectionCatalogDocumentJson,
51 );
52
53 const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
54 "create-temporary-file-name",
55 "encode-document",
56 "create-directory",
57 "write-temporary-file",
58 "replace-catalog-file",
59 "keep-unreadable-catalog",
60 ]);
61
62 const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
63 "read-legacy-registry",
64 "read-legacy-secret",
65 "encode-catalog",
66 "persist-catalog",
67 ]);
68
69 const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
70 "check-encryption-availability",
71 "encrypt-catalog",
72 "decrypt-catalog",
73 ]);
74
75 export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedError<DesktopConnectionCatalogStoreWriteError>()(
76 "DesktopConnectionCatalogStoreWriteError",
77 {
78 operation: DesktopConnectionCatalogStoreWriteOperation,
79 path: Schema.String,
80 cause: Schema.Defect(),
81 },
82 ) {
83 override get message(): string {
84 return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
85 }
86 }
87
88 export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedError<DesktopConnectionCatalogStoreDecodeError>()(
89 "DesktopConnectionCatalogStoreDecodeError",
90 {
91 resource: Schema.Literal("encryptedCatalog"),
92 catalogPath: Schema.String,
93 cause: Schema.Defect(),
94 },
95 ) {
96 override get message(): string {
97 return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
98 }
99 }
100
101 export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedError<DesktopConnectionCatalogStoreReadError>()(
102 "DesktopConnectionCatalogStoreReadError",
103 {
104 catalogPath: Schema.String,
105 cause: Schema.Defect(),
106 },
107 ) {
108 override get message(): string {
109 return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
110 }
111 }
112
113 export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedError<DesktopConnectionCatalogStoreDocumentDecodeError>()(
114 "DesktopConnectionCatalogStoreDocumentDecodeError",
115 {
116 catalogPath: Schema.String,
117 cause: Schema.Defect(),
118 },
119 ) {
120 override get message(): string {
121 return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
122 }
123 }
124
125 export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedError<DesktopConnectionCatalogStoreMigrationError>()(
126 "DesktopConnectionCatalogStoreMigrationError",
127 {
128 operation: DesktopConnectionCatalogStoreMigrationOperation,
129 catalogPath: Schema.String,
130 environmentId: Schema.optionalKey(Schema.String),
131 cause: Schema.Defect(),
132 },
133 ) {
134 override get message(): string {
135 const environment =
136 this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
137 return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
138 }
139 }
140
141 export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedError<DesktopConnectionCatalogStoreProtectionError>()(
142 "DesktopConnectionCatalogStoreProtectionError",
143 {
144 operation: DesktopConnectionCatalogStoreProtectionOperation,
145 catalogPath: Schema.String,
146 cause: Schema.Defect(),
147 },
148 ) {
149 override get message(): string {
150 return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
151 }
152 }
153
154 export class DesktopConnectionCatalogStore extends Context.Service<
155 DesktopConnectionCatalogStore,
156 {
157 readonly get: Effect.Effect<
158 Option.Option<string>,
159 | DesktopConnectionCatalogStoreReadError
160 | DesktopConnectionCatalogStoreDocumentDecodeError
161 | DesktopConnectionCatalogStoreDecodeError
162 | DesktopConnectionCatalogStoreMigrationError
163 | DesktopConnectionCatalogStoreProtectionError
164 >;
165 readonly set: (
166 catalog: string,
167 ) => Effect.Effect<
168 boolean,
169 DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
170 >;
171 }
172 >()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
173
174 function decodeSecretBytes(
175 catalogPath: string,
176 encoded: string,
177 ): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
178 return Effect.fromResult(Base64.decode(encoded)).pipe(
179 Effect.mapError(
180 (cause) =>
181 new DesktopConnectionCatalogStoreDecodeError({
182 resource: "encryptedCatalog",
183 catalogPath,
184 cause,
185 }),
186 ),
187 );
188 }
189
190 const readDocument = (
191 fileSystem: FileSystem.FileSystem,
192 catalogPath: string,
193 ): Effect.Effect<
194 Option.Option<EncryptedConnectionCatalogDocument>,
195 DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
196 > =>
197 fileSystem.readFileString(catalogPath).pipe(
198 Effect.catch((error) =>
199 error.reason._tag === "NotFound"
200 ? Effect.succeed<string | null>(null)
201 : Effect.fail(
202 new DesktopConnectionCatalogStoreReadError({
203 catalogPath,
204 cause: error,
205 }),
206 ),
207 ),
208 Effect.flatMap((raw) =>
209 raw === null
210 ? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
211 : decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
212 Effect.asSome,
213 Effect.mapError(
214 (cause) =>
215 new DesktopConnectionCatalogStoreDocumentDecodeError({
216 catalogPath,
217 cause,
218 }),
219 ),
220 ),
221 ),
222 );
223
224 const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
225 readonly fileSystem: FileSystem.FileSystem;
226 readonly path: Path.Path;
227 readonly catalogPath: string;
228 readonly document: EncryptedConnectionCatalogDocument;
229 readonly suffix: string;
230 }): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
231 const directory = input.path.dirname(input.catalogPath);
232 const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
233 const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
234 Effect.mapError(
235 (cause) =>
236 new DesktopConnectionCatalogStoreWriteError({
237 operation: "encode-document",
238 path: input.catalogPath,
239 cause,
240 }),
241 ),
242 );
243 yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
244 Effect.mapError(
245 (cause) =>
246 new DesktopConnectionCatalogStoreWriteError({
247 operation: "create-directory",
248 path: directory,
249 cause,
250 }),
251 ),
252 );
253 yield* Effect.gen(function* () {
254 yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
255 Effect.mapError(
256 (cause) =>
257 new DesktopConnectionCatalogStoreWriteError({
258 operation: "write-temporary-file",
259 path: tempPath,
260 cause,
261 }),
262 ),
263 );
264 yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
265 Effect.mapError(
266 (cause) =>
267 new DesktopConnectionCatalogStoreWriteError({
268 operation: "replace-catalog-file",
269 path: input.catalogPath,
270 cause,
271 }),
272 ),
273 );
274 }).pipe(
275 Effect.ensuring(
276 input.fileSystem.remove(tempPath, { force: true }).pipe(
277 Effect.catch((error) =>
278 Effect.logWarning("Could not remove a temporary connection catalog file.", {
279 tempPath,
280 error,
281 }),
282 ),
283 ),
284 ),
285 );
286 });
287
288 function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
289 return `${prefix}:${environmentId}`;
290 }
291
292 const migrateSavedEnvironmentRecords = Effect.fn(
293 "desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
294 )(function* (
295 records: readonly PersistedSavedEnvironmentRecord[],
296 savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
297 catalogPath: string,
298 ): Effect.fn.Return<
299 RuntimeConnectionCatalogDocumentType,
300 DesktopConnectionCatalogStoreMigrationError
301 > {
302 const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
303 const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
304 const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
305
306 for (const record of records) {
307 if (record.relayManaged !== undefined) {
308 targets.push(
309 new RelayConnectionTarget({
310 environmentId: record.environmentId,
311 label: record.label,
312 }),
313 );
314 continue;
315 }
316
317 if (record.desktopSsh !== undefined) {
318 const id = connectionId("ssh", record.environmentId);
319 targets.push(
320 new SshConnectionTarget({
321 environmentId: record.environmentId,
322 label: record.label,
323 connectionId: id,
324 }),
325 );
326 profiles.push(
327 new SshConnectionProfile({
328 connectionId: id,
329 environmentId: record.environmentId,
330 label: record.label,
331 target: record.desktopSsh,
332 }),
333 );
334 continue;
335 }
336
337 const id = connectionId("bearer", record.environmentId);
338 targets.push(
339 new BearerConnectionTarget({
340 environmentId: record.environmentId,
341 label: record.label,
342 connectionId: id,
343 }),
344 );
345 profiles.push(
346 new BearerConnectionProfile({
347 connectionId: id,
348 environmentId: record.environmentId,
349 label: record.label,
350 httpBaseUrl: record.httpBaseUrl,
351 wsBaseUrl: record.wsBaseUrl,
352 }),
353 );
354 const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
355 Effect.mapError(
356 (cause) =>
357 new DesktopConnectionCatalogStoreMigrationError({
358 operation: "read-legacy-secret",
359 catalogPath,
360 environmentId: record.environmentId,
361 cause,
362 }),
363 ),
364 );
365 if (Option.isSome(token)) {
366 credentials.push({
367 connectionId: id,
368 credential: new BearerConnectionCredential({ token: token.value }),
369 });
370 }
371 }
372
373 return {
374 schemaVersion: 1,
375 targets,
376 profiles,
377 credentials,
378 remoteDpopTokens: [],
379 disabledEnvironmentIds: [],
380 };
381 });
382
383 /** @public */
384 export const make = Effect.gen(function* () {
385 const environment = yield* DesktopEnvironment.DesktopEnvironment;
386 const fileSystem = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
389 const random = yield* SecureRandom.SecureRandom;
390 const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
391 const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
392 const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
393 Effect.mapError(
394 (cause) =>
395 new DesktopConnectionCatalogStoreProtectionError({
396 operation: "check-encryption-availability",
397 catalogPath,
398 cause,
399 }),
400 ),
401 );
402
403 const decryptDocument = (document: EncryptedConnectionCatalogDocument) =>
404 decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe(
405 Effect.flatMap((encryptedCatalog) =>
406 safeStorage.decryptString(encryptedCatalog).pipe(
407 Effect.mapError(
408 (cause) =>
409 new DesktopConnectionCatalogStoreProtectionError({
410 operation: "decrypt-catalog",
411 catalogPath,
412 cause,
413 }),
414 ),
415 ),
416 ),
417 );
418
419 // A catalog this build cannot decrypt or decode may still hold another build's saved
420 // environments and credentials, so a save copies it aside instead of destroying it.
421 const keepUnreadableCatalog = Effect.gen(function* () {
422 const readable = yield* readDocument(fileSystem, catalogPath).pipe(
423 Effect.flatMap(
424 Option.match({
425 onNone: () => Effect.succeed(true),
426 onSome: (document) =>
427 decryptDocument(document).pipe(
428 Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson),
429 Effect.as(true),
430 ),
431 }),
432 ),
433 Effect.orElseSucceed(() => false),
434 );
435 if (readable) {
436 return;
437 }
438 const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`;
439 yield* fileSystem.copyFile(catalogPath, keptPath).pipe(
440 Effect.mapError(
441 (cause) =>
442 new DesktopConnectionCatalogStoreWriteError({
443 operation: "keep-unreadable-catalog",
444 path: keptPath,
445 cause,
446 }),
447 ),
448 );
449 yield* Effect.logWarning("Kept an unreadable connection catalog before replacing it.", {
450 keptPath,
451 });
452 });
453
454 const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
455 catalog: string,
456 ) {
457 const encryptedCatalog = Base64.encode(
458 yield* safeStorage.encryptString(catalog).pipe(
459 Effect.mapError(
460 (cause) =>
461 new DesktopConnectionCatalogStoreProtectionError({
462 operation: "encrypt-catalog",
463 catalogPath,
464 cause,
465 }),
466 ),
467 ),
468 );
469 const suffix = (yield* random.uuidV4()).replace(/-/g, "");
470 yield* writeDocument({
471 fileSystem,
472 path,
473 catalogPath,
474 document: { version: 1, encryptedCatalog },
475 suffix,
476 });
477 });
478
479 const migrateLegacyCatalog = Effect.gen(function* () {
480 if (!(yield* encryptionAvailable)) {
481 return Option.none<string>();
482 }
483 const records = yield* savedEnvironments.getRegistry.pipe(
484 Effect.mapError(
485 (cause) =>
486 new DesktopConnectionCatalogStoreMigrationError({
487 operation: "read-legacy-registry",
488 catalogPath,
489 cause,
490 }),
491 ),
492 );
493 if (records.length === 0) {
494 return Option.none<string>();
495 }
496 const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
497 const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
498 Effect.mapError(
499 (cause) =>
500 new DesktopConnectionCatalogStoreMigrationError({
501 operation: "encode-catalog",
502 catalogPath,
503 cause,
504 }),
505 ),
506 );
507 yield* writeCatalog(encoded).pipe(
508 Effect.mapError(
509 (cause) =>
510 new DesktopConnectionCatalogStoreMigrationError({
511 operation: "persist-catalog",
512 catalogPath,
513 cause,
514 }),
515 ),
516 );
517 return Option.some(encoded);
518 });
519
520 return DesktopConnectionCatalogStore.of({
521 get: Effect.gen(function* () {
522 const document = yield* readDocument(fileSystem, catalogPath);
523 if (Option.isNone(document)) {
524 return yield* migrateLegacyCatalog;
525 }
526 if (!(yield* encryptionAvailable)) {
527 return Option.none<string>();
528 }
529 return Option.some(yield* decryptDocument(document.value));
530 }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
531 set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
532 if (!(yield* encryptionAvailable)) {
533 return false;
534 }
535 yield* keepUnreadableCatalog;
536 yield* writeCatalog(catalog);
537 return true;
538 }),
539 });
540 });
541
542 export const layer = Layer.effect(DesktopConnectionCatalogStore, make);