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