Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopConnectionCatalogStore.ts

560 lines18.1 KB

1import {
2 BearerConnectionCredential,
3 BearerConnectionProfile,
4 BearerConnectionTarget,
5 RelayConnectionTarget,
6 SshConnectionProfile,
7 SshConnectionTarget,
8} from "@t3tools/client-runtime/connection";
9import {
10 ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
11 type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
12} from "@t3tools/client-runtime/platform";
13import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
14import { fromLenientJson } from "@t3tools/shared/schemaJson";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as Effect from "effect/Effect";
18import * as Base64 from "effect/encoding/Base64";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Schema from "effect/Schema";
24import * as Semaphore from "effect/Semaphore";
25​
26import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
27import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
28import * as DesktopEnvironment from "./DesktopEnvironment.ts";
29import * as DesktopSafeStorageIdentity from "./DesktopSafeStorageIdentity.ts";
30​
31const EncryptedConnectionCatalogDocument = Schema.Struct({
32 version: Schema.Literal(1),
33 encryptedCatalog: Schema.String,
34});
35type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
36​
37const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
38const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
39 EncryptedConnectionCatalogDocumentJson,
40);
41const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
42 EncryptedConnectionCatalogDocumentJson,
43);
44const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
45 RuntimeConnectionCatalogDocument,
46);
47const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
48 RuntimeConnectionCatalogDocumentJson,
49);
50const decodeCatalogJsonOption = Schema.decodeOption(RuntimeConnectionCatalogDocumentJson);
51const decodeNativeCatalogJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
52​
53const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
54 "create-temporary-file-name",
55 "encode-document",
56 "create-directory",
57 "write-temporary-file",
58 "replace-catalog-file",
59]);
60​
61const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
62 "read-legacy-registry",
63 "read-legacy-secret",
64 "encode-catalog",
65 "persist-catalog",
66]);
67​
68const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
69 "check-encryption-availability",
70 "encrypt-catalog",
71 "decrypt-catalog",
72]);
73​
74export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedError<DesktopConnectionCatalogStoreWriteError>()(
75 "DesktopConnectionCatalogStoreWriteError",
76 {
77 operation: DesktopConnectionCatalogStoreWriteOperation,
78 path: Schema.String,
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
84 }
86​
87export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedError<DesktopConnectionCatalogStoreDecodeError>()(
88 "DesktopConnectionCatalogStoreDecodeError",
89 {
90 resource: Schema.Literal("encryptedCatalog"),
91 catalogPath: Schema.String,
92 cause: Schema.Defect(),
93 },
94) {
95 override get message(): string {
96 return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
97 }
99​
100export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedError<DesktopConnectionCatalogStoreReadError>()(
101 "DesktopConnectionCatalogStoreReadError",
102 {
103 catalogPath: Schema.String,
104 cause: Schema.Defect(),
105 },
106) {
107 override get message(): string {
108 return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
109 }
111​
112export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedError<DesktopConnectionCatalogStoreDocumentDecodeError>()(
113 "DesktopConnectionCatalogStoreDocumentDecodeError",
114 {
115 catalogPath: Schema.String,
116 cause: Schema.Defect(),
117 },
118) {
119 override get message(): string {
120 return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
121 }
123​
124export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedError<DesktopConnectionCatalogStoreMigrationError>()(
125 "DesktopConnectionCatalogStoreMigrationError",
126 {
127 operation: DesktopConnectionCatalogStoreMigrationOperation,
128 catalogPath: Schema.String,
129 environmentId: Schema.optionalKey(Schema.String),
130 cause: Schema.Defect(),
131 },
132) {
133 override get message(): string {
134 const environment =
135 this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
136 return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
137 }
139​
140export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedError<DesktopConnectionCatalogStoreProtectionError>()(
141 "DesktopConnectionCatalogStoreProtectionError",
142 {
143 operation: DesktopConnectionCatalogStoreProtectionOperation,
144 catalogPath: Schema.String,
145 cause: Schema.Defect(),
146 },
147) {
148 override get message(): string {
149 return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
150 }
152​
153export class DesktopConnectionCatalogStore extends Context.Service<
154 DesktopConnectionCatalogStore,
155 {
156 readonly get: Effect.Effect<
157 Option.Option<string>,
158 | DesktopConnectionCatalogStoreReadError
159 | DesktopConnectionCatalogStoreDocumentDecodeError
160 | DesktopConnectionCatalogStoreDecodeError
161 | DesktopConnectionCatalogStoreMigrationError
162 | DesktopConnectionCatalogStoreProtectionError
163 >;
164 readonly set: (
165 catalog: string,
166 ) => Effect.Effect<
167 boolean,
168 DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
169 >;
170 readonly clear: Effect.Effect<void>;
171 }
172>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
173​
174function 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 );
189​
190const 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​
224const 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​
288function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
289 return `${prefix}:${environmentId}`;
291​
292const 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 */
384export 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 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) =>
397 new DesktopConnectionCatalogStoreProtectionError({
398 operation: "check-encryption-availability",
399 catalogPath,
400 cause,
401 }),
402 ),
403 );
404​
405 const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
406 catalog: string,
407 ) {
408 const encryptedCatalog = Base64.encode(
409 yield* safeStorage.encryptString(catalog).pipe(
410 Effect.mapError(
411 (cause) =>
412 new DesktopConnectionCatalogStoreProtectionError({
413 operation: "encrypt-catalog",
414 catalogPath,
415 cause,
416 }),
417 ),
418 ),
419 );
420 const suffix = (yield* crypto.randomUUIDv4().pipe(
421 Effect.mapError(
422 (cause) =>
423 new DesktopConnectionCatalogStoreWriteError({
424 operation: "create-temporary-file-name",
425 path: catalogPath,
426 cause,
427 }),
428 ),
429 )).replace(/-/g, "");
430 yield* writeDocument({
431 fileSystem,
432 path,
433 catalogPath,
434 document: { version: 1, encryptedCatalog },
435 suffix,
436 });
437 });
438​
439 const migrateLegacyCatalog = Effect.gen(function* () {
440 if (!(yield* encryptionAvailable)) {
441 return Option.none<string>();
442 }
443 const records = yield* savedEnvironments.getRegistry.pipe(
444 Effect.mapError(
445 (cause) =>
446 new DesktopConnectionCatalogStoreMigrationError({
447 operation: "read-legacy-registry",
448 catalogPath,
449 cause,
450 }),
451 ),
452 );
453 if (records.length === 0) {
454 return Option.none<string>();
455 }
456 const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
457 const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
458 Effect.mapError(
459 (cause) =>
460 new DesktopConnectionCatalogStoreMigrationError({
461 operation: "encode-catalog",
462 catalogPath,
463 cause,
464 }),
465 ),
466 );
467 yield* writeCatalog(encoded).pipe(
468 Effect.mapError(
469 (cause) =>
470 new DesktopConnectionCatalogStoreMigrationError({
471 operation: "persist-catalog",
472 catalogPath,
473 cause,
474 }),
475 ),
476 );
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);
517 if (Option.isNone(document)) {
518 return yield* migrateLegacyCatalog;
519 }
520 if (!(yield* encryptionAvailable)) {
521 return Option.none<string>();
522 }
523 const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
524 Effect.flatMap((encryptedCatalog) =>
525 safeStorage.decryptString(encryptedCatalog).pipe(
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 ),
537 );
538 return Option.some(decrypted);
539 }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
540 set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
541 if (!(yield* encryptionAvailable)) {
542 return false;
543 }
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,
552 error,
553 }),
554 ),
555 Effect.withSpan("desktop.connectionCatalogStore.clear"),
556 ),
557 });
558});
559​
560export const layer = Layer.effect(DesktopConnectionCatalogStore, make);