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

DesktopSavedEnvironments.ts

624 lines20.7 KB

1import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
2import { fromLenientJson } from "@t3tools/shared/schemaJson";
3import { retryWindowsFileSystemOperation } from "@t3tools/shared/windowsFileRetry";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as Encoding from "effect/Encoding";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import * as Ref from "effect/Ref";
14​
15import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
17​
18type PersistedSavedEnvironmentDesktopSsh = NonNullable<
19 PersistedSavedEnvironmentRecord["desktopSsh"]
20>;
21​
22interface PersistedSavedEnvironmentStorageRecord extends Omit<
23 PersistedSavedEnvironmentRecord,
24 "desktopSsh"
25> {
26 readonly desktopSsh?: PersistedSavedEnvironmentDesktopSsh;
27 readonly encryptedBearerToken?: string;
29​
30interface SavedEnvironmentRegistryDocument {
31 readonly version: number;
32 readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
34​
35interface SavedEnvironmentRegistryStorageDocument {
36 readonly version?: number;
37 readonly records?: readonly PersistedSavedEnvironmentStorageRecord[];
39​
40const DesktopSshTargetSchema = Schema.Struct({
41 alias: Schema.String,
42 hostname: Schema.String,
43 username: Schema.NullOr(Schema.String),
44 port: Schema.NullOr(Schema.Number),
45});
46​
47const PersistedSavedEnvironmentStorageRecordSchema = Schema.Struct({
48 environmentId: EnvironmentId,
49 label: Schema.String,
50 httpBaseUrl: Schema.String,
51 wsBaseUrl: Schema.String,
52 createdAt: Schema.String,
53 lastConnectedAt: Schema.NullOr(Schema.String),
54 desktopSsh: Schema.optionalKey(DesktopSshTargetSchema),
55 relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })),
56 encryptedBearerToken: Schema.optionalKey(Schema.String),
57});
58​
59const SavedEnvironmentRegistryDocumentSchema = Schema.Struct({
60 version: Schema.optionalKey(Schema.Number),
61 records: Schema.optionalKey(Schema.Array(PersistedSavedEnvironmentStorageRecordSchema)),
62});
63​
64const SavedEnvironmentRegistryDocumentJson = fromLenientJson(
65 SavedEnvironmentRegistryDocumentSchema,
66);
67const decodeSavedEnvironmentRegistryDocumentJson = Schema.decodeEffect(
68 SavedEnvironmentRegistryDocumentJson,
69);
70const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
71 SavedEnvironmentRegistryDocumentJson,
72);
73​
74const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
75 "create-temporary-file-name",
76 "encode-registry",
77 "create-directory",
78 "write-temporary-file",
79 "replace-registry-file",
80]);
81​
82const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
83 "check-encryption-availability",
84 "encrypt-secret",
85 "decrypt-secret",
86]);
87​
88export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
89 "DesktopSavedEnvironmentsWriteError",
90 {
91 operation: DesktopSavedEnvironmentsWriteOperation,
92 path: Schema.String,
93 cause: Schema.Defect(),
94 },
95) {
96 override get message(): string {
97 return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
98 }
100​
101export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
102 "DesktopSavedEnvironmentsReadError",
103 {
104 registryPath: Schema.String,
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Failed to read desktop saved environments at ${this.registryPath}.`;
110 }
112​
113export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsDocumentDecodeError>()(
114 "DesktopSavedEnvironmentsDocumentDecodeError",
115 {
116 registryPath: Schema.String,
117 cause: Schema.Defect(),
118 },
119) {
120 override get message(): string {
121 return `Failed to decode desktop saved environments at ${this.registryPath}.`;
122 }
124​
125export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretDecodeError>()(
126 "DesktopSavedEnvironmentSecretDecodeError",
127 {
128 environmentId: Schema.String,
129 registryPath: Schema.String,
130 field: Schema.Literal("encryptedBearerToken"),
131 cause: Schema.Defect(),
132 },
133) {
134 override get message(): string {
135 return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
136 }
138​
139export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
140 "DesktopSavedEnvironmentSecretProtectionError",
141 {
142 operation: DesktopSavedEnvironmentSecretProtectionOperation,
143 environmentId: Schema.String,
144 registryPath: Schema.String,
145 cause: Schema.Defect(),
146 },
147) {
148 override get message(): string {
149 return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
150 }
152​
153export type DesktopSavedEnvironmentsReadRegistryError =
154 | DesktopSavedEnvironmentsReadError
155 | DesktopSavedEnvironmentsDocumentDecodeError;
156​
157export type DesktopSavedEnvironmentsMutationError =
158 | DesktopSavedEnvironmentsReadRegistryError
159 | DesktopSavedEnvironmentsWriteError;
160​
161export type DesktopSavedEnvironmentsGetSecretError =
162 | DesktopSavedEnvironmentsReadRegistryError
163 | DesktopSavedEnvironmentSecretDecodeError
164 | DesktopSavedEnvironmentSecretProtectionError;
165​
166export type DesktopSavedEnvironmentsSetSecretError =
167 | DesktopSavedEnvironmentsMutationError
168 | DesktopSavedEnvironmentSecretProtectionError;
169​
170export class DesktopSavedEnvironments extends Context.Service<
171 DesktopSavedEnvironments,
172 {
173 readonly getRegistry: Effect.Effect<
174 readonly PersistedSavedEnvironmentRecord[],
175 DesktopSavedEnvironmentsReadRegistryError
176 >;
177 readonly setRegistry: (
178 records: readonly PersistedSavedEnvironmentRecord[],
179 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
180 readonly removeEnvironment: (
181 environmentId: string,
182 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
183 readonly getSecret: (
184 environmentId: string,
185 ) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
186 readonly setSecret: (input: {
187 readonly environmentId: string;
188 readonly secret: string;
189 }) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
190 readonly removeSecret: (
191 environmentId: string,
192 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
193 }
194>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
195​
196function toPersistedSavedEnvironmentRecord(
197 record: PersistedSavedEnvironmentStorageRecord,
198): PersistedSavedEnvironmentRecord {
199 const nextRecord = {
200 environmentId: record.environmentId,
201 label: record.label,
202 httpBaseUrl: record.httpBaseUrl,
203 wsBaseUrl: record.wsBaseUrl,
204 createdAt: record.createdAt,
205 lastConnectedAt: record.lastConnectedAt,
206 };
207 return {
208 ...nextRecord,
209 ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
210 ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
211 };
213​
214function toSavedEnvironmentStorageRecord(
215 record: PersistedSavedEnvironmentRecord | PersistedSavedEnvironmentStorageRecord,
216 encryptedBearerToken: Option.Option<string>,
217): PersistedSavedEnvironmentStorageRecord {
218 const nextRecord = {
219 environmentId: record.environmentId,
220 label: record.label,
221 httpBaseUrl: record.httpBaseUrl,
222 wsBaseUrl: record.wsBaseUrl,
223 createdAt: record.createdAt,
224 lastConnectedAt: record.lastConnectedAt,
225 };
226 const metadata = {
227 ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
228 ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
229 };
230 return Option.match(encryptedBearerToken, {
231 onNone: () => ({ ...nextRecord, ...metadata }),
232 onSome: (value) => ({ ...nextRecord, ...metadata, encryptedBearerToken: value }),
233 });
235​
236function normalizeSavedEnvironmentRegistryDocument(
237 document: SavedEnvironmentRegistryStorageDocument,
238): SavedEnvironmentRegistryDocument {
239 return {
240 version: document.version ?? 1,
241 records: document.records ?? [],
242 };
244​
245function readRegistryDocument(
246 fileSystem: FileSystem.FileSystem,
247 registryPath: string,
248): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> {
249 return fileSystem.readFileString(registryPath).pipe(
250 Effect.catch((error) =>
251 error.reason._tag === "NotFound"
252 ? Effect.succeed<string | null>(null)
253 : Effect.fail(
254 new DesktopSavedEnvironmentsReadError({
255 registryPath,
256 cause: error,
257 }),
258 ),
259 ),
260 Effect.flatMap((raw) =>
261 raw === null
262 ? Effect.succeed({ version: 1, records: [] })
263 : decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
264 Effect.map(normalizeSavedEnvironmentRegistryDocument),
265 Effect.mapError(
266 (cause) =>
267 new DesktopSavedEnvironmentsDocumentDecodeError({
268 registryPath,
269 cause,
270 }),
271 ),
272 ),
273 ),
274 );
276​
277const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistryDocument")(
278 function* (input: {
279 readonly fileSystem: FileSystem.FileSystem;
280 readonly path: Path.Path;
281 readonly registryPath: string;
282 readonly document: SavedEnvironmentRegistryDocument;
283 readonly suffix: string;
284 }): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {
285 const directory = input.path.dirname(input.registryPath);
286 const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
287 const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
288 Effect.mapError(
289 (cause) =>
290 new DesktopSavedEnvironmentsWriteError({
291 operation: "encode-registry",
292 path: input.registryPath,
293 cause,
294 }),
295 ),
296 );
297 yield* retryWindowsFileSystemOperation(
298 input.fileSystem.makeDirectory(directory, { recursive: true }),
299 ).pipe(
300 Effect.mapError(
301 (cause) =>
302 new DesktopSavedEnvironmentsWriteError({
303 operation: "create-directory",
304 path: directory,
305 cause,
306 }),
307 ),
308 );
309 yield* Effect.gen(function* () {
310 yield* retryWindowsFileSystemOperation(
311 input.fileSystem.writeFileString(tempPath, `${encoded}\n`),
312 ).pipe(
313 Effect.mapError(
314 (cause) =>
315 new DesktopSavedEnvironmentsWriteError({
316 operation: "write-temporary-file",
317 path: tempPath,
318 cause,
319 }),
320 ),
321 );
322 yield* retryWindowsFileSystemOperation(
323 input.fileSystem.rename(tempPath, input.registryPath),
324 ).pipe(
325 Effect.mapError(
326 (cause) =>
327 new DesktopSavedEnvironmentsWriteError({
328 operation: "replace-registry-file",
329 path: input.registryPath,
330 cause,
331 }),
332 ),
333 );
334 }).pipe(
335 Effect.ensuring(
336 retryWindowsFileSystemOperation(
337 input.fileSystem.remove(tempPath, { force: true }),
338 ).pipe(Effect.ignore),
339 ),
340 );
341 },
342);
343​
344function preserveExistingSecrets(
345 currentDocument: SavedEnvironmentRegistryDocument,
346 records: readonly PersistedSavedEnvironmentRecord[],
347): SavedEnvironmentRegistryDocument {
348 const encryptedBearerTokenById = new Map(
349 currentDocument.records.flatMap((record) =>
350 record.encryptedBearerToken
351 ? [[record.environmentId, record.encryptedBearerToken] as const]
352 : [],
353 ),
354 );
355​
356 return {
357 version: currentDocument.version,
358 records: records.map((record) => {
359 const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
360 return toSavedEnvironmentStorageRecord(record, Option.fromNullishOr(encryptedBearerToken));
361 }),
362 };
364​
365function decodeSecretBytes(
366 environmentId: string,
367 registryPath: string,
368 encoded: string,
369): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
370 return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
371 Effect.mapError(
372 (cause) =>
373 new DesktopSavedEnvironmentSecretDecodeError({
374 environmentId,
375 registryPath,
376 field: "encryptedBearerToken",
377 cause,
378 }),
379 ),
380 );
382​
383export const make = Effect.gen(function* () {
384 const environment = yield* DesktopEnvironment.DesktopEnvironment;
385 const fileSystem = yield* FileSystem.FileSystem;
386 const path = yield* Path.Path;
387 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
388 const crypto = yield* Crypto.Crypto;
389​
390 const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
391 crypto.randomUUIDv4.pipe(
392 Effect.map((uuid) => uuid.replace(/-/g, "")),
393 Effect.mapError(
394 (cause) =>
395 new DesktopSavedEnvironmentsWriteError({
396 operation: "create-temporary-file-name",
397 path: environment.savedEnvironmentRegistryPath,
398 cause,
399 }),
400 ),
401 Effect.flatMap((suffix) =>
402 writeRegistryDocument({
403 fileSystem,
404 path,
405 registryPath: environment.savedEnvironmentRegistryPath,
406 document,
407 suffix,
408 }),
409 ),
410 );
411​
412 return DesktopSavedEnvironments.of({
413 getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
414 Effect.map((document) =>
415 document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
416 ),
417 Effect.withSpan("desktop.savedEnvironments.getRegistry"),
418 ),
419 setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
420 const currentDocument = yield* readRegistryDocument(
421 fileSystem,
422 environment.savedEnvironmentRegistryPath,
423 );
424 yield* writeDocument(preserveExistingSecrets(currentDocument, records));
425 }),
426 removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
427 function* (environmentId) {
428 yield* Effect.annotateCurrentSpan({ environmentId });
429 const document = yield* readRegistryDocument(
430 fileSystem,
431 environment.savedEnvironmentRegistryPath,
432 );
433 if (!document.records.some((record) => record.environmentId === environmentId)) {
434 return;
435 }
436​
437 yield* writeDocument({
438 version: document.version,
439 records: document.records.filter((record) => record.environmentId !== environmentId),
440 });
441 },
442 ),
443 getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
444 yield* Effect.annotateCurrentSpan({ environmentId });
445 const document = yield* readRegistryDocument(
446 fileSystem,
447 environment.savedEnvironmentRegistryPath,
448 );
449 const encoded = Option.fromNullishOr(
450 document.records.find((record) => record.environmentId === environmentId)
451 ?.encryptedBearerToken,
452 );
453 if (Option.isNone(encoded)) {
454 return Option.none<string>();
455 }
456 const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
457 Effect.mapError(
458 (cause) =>
459 new DesktopSavedEnvironmentSecretProtectionError({
460 operation: "check-encryption-availability",
461 environmentId,
462 registryPath: environment.savedEnvironmentRegistryPath,
463 cause,
464 }),
465 ),
466 );
467 if (!encryptionAvailable) {
468 return Option.none<string>();
469 }
470​
471 const secretBytes = yield* decodeSecretBytes(
472 environmentId,
473 environment.savedEnvironmentRegistryPath,
474 encoded.value,
475 );
476 return Option.some(
477 yield* safeStorage.decryptString(secretBytes).pipe(
478 Effect.mapError(
479 (cause) =>
480 new DesktopSavedEnvironmentSecretProtectionError({
481 operation: "decrypt-secret",
482 environmentId,
483 registryPath: environment.savedEnvironmentRegistryPath,
484 cause,
485 }),
486 ),
487 ),
488 );
489 }),
490 setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
491 const { environmentId, secret } = input;
492 yield* Effect.annotateCurrentSpan({ environmentId });
493 const document = yield* readRegistryDocument(
494 fileSystem,
495 environment.savedEnvironmentRegistryPath,
496 );
497​
498 const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
499 Effect.mapError(
500 (cause) =>
501 new DesktopSavedEnvironmentSecretProtectionError({
502 operation: "check-encryption-availability",
503 environmentId,
504 registryPath: environment.savedEnvironmentRegistryPath,
505 cause,
506 }),
507 ),
508 );
509 if (!encryptionAvailable) {
510 return false;
511 }
512​
513 const encryptedBearerToken = Encoding.encodeBase64(
514 yield* safeStorage.encryptString(secret).pipe(
515 Effect.mapError(
516 (cause) =>
517 new DesktopSavedEnvironmentSecretProtectionError({
518 operation: "encrypt-secret",
519 environmentId,
520 registryPath: environment.savedEnvironmentRegistryPath,
521 cause,
522 }),
523 ),
524 ),
525 );
526 let found = false;
527 const nextDocument: SavedEnvironmentRegistryDocument = {
528 version: document.version,
529 records: document.records.map((record) => {
530 if (record.environmentId !== environmentId) {
531 return record;
532 }
533​
534 found = true;
535 return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
536 }),
537 };
538​
539 if (found) {
540 yield* writeDocument(nextDocument);
541 }
542 return found;
543 }),
544 removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
545 yield* Effect.annotateCurrentSpan({ environmentId });
546 const document = yield* readRegistryDocument(
547 fileSystem,
548 environment.savedEnvironmentRegistryPath,
549 );
550 if (
551 !document.records.some(
552 (record) =>
553 record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
554 )
555 ) {
556 return;
557 }
558​
559 yield* writeDocument({
560 version: document.version,
561 records: document.records.map((record) => {
562 if (record.environmentId !== environmentId) {
563 return record;
564 }
565 return toPersistedSavedEnvironmentRecord(record);
566 }),
567 });
568 }),
569 });
570});
571​
572export const layer = Layer.effect(DesktopSavedEnvironments, make);
573​
574export const layerTest = (input?: {
575 readonly records?: readonly PersistedSavedEnvironmentRecord[];
576 readonly secrets?: ReadonlyMap<string, string>;
577}) =>
578 Layer.effect(
579 DesktopSavedEnvironments,
580 Effect.gen(function* () {
581 const recordsRef = yield* Ref.make(input?.records ?? []);
582 const secretsRef = yield* Ref.make(new Map(input?.secrets ?? []));
583​
584 return DesktopSavedEnvironments.of({
585 getRegistry: Ref.get(recordsRef),
586 setRegistry: (records) => Ref.set(recordsRef, records),
587 removeEnvironment: (environmentId) =>
588 Ref.update(recordsRef, (records) =>
589 records.filter((record) => record.environmentId !== environmentId),
590 ).pipe(
591 Effect.andThen(
592 Ref.update(secretsRef, (secrets) => {
593 const nextSecrets = new Map(secrets);
594 nextSecrets.delete(environmentId);
595 return nextSecrets;
596 }),
597 ),
598 ),
599 getSecret: (environmentId) =>
600 Ref.get(secretsRef).pipe(
601 Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
602 ),
603 setSecret: ({ environmentId, secret }) =>
604 Ref.get(recordsRef).pipe(
605 Effect.flatMap((records) => {
606 if (!records.some((record) => record.environmentId === environmentId)) {
607 return Effect.succeed(false);
608 }
609 return Ref.update(secretsRef, (secrets) => {
610 const nextSecrets = new Map(secrets);
611 nextSecrets.set(environmentId, secret);
612 return nextSecrets;
613 }).pipe(Effect.as(true));
614 }),
615 ),
616 removeSecret: (environmentId) =>
617 Ref.update(secretsRef, (secrets) => {
618 const nextSecrets = new Map(secrets);
619 nextSecrets.delete(environmentId);
620 return nextSecrets;
621 }),
622 });
623 }),
624 );