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

DesktopConnectionCatalogStore.ts

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