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

DesktopSavedEnvironments.ts

557 lines18.3 KB

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";
12​
13import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
14import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
15​
16type PersistedSavedEnvironmentDesktopSsh = NonNullable<
17 PersistedSavedEnvironmentRecord["desktopSsh"]
18>;
19​
20interface PersistedSavedEnvironmentStorageRecord extends Omit<
21 PersistedSavedEnvironmentRecord,
22 "desktopSsh"
23> {
24 readonly desktopSsh?: PersistedSavedEnvironmentDesktopSsh;
25 readonly encryptedBearerToken?: string;
27​
28interface SavedEnvironmentRegistryDocument {
29 readonly version: number;
30 readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
32​
33interface SavedEnvironmentRegistryStorageDocument {
34 readonly version?: number;
35 readonly records?: readonly PersistedSavedEnvironmentStorageRecord[];
37​
38const DesktopSshTargetSchema = Schema.Struct({
39 alias: Schema.String,
40 hostname: Schema.String,
41 username: Schema.NullOr(Schema.String),
42 port: Schema.NullOr(Schema.Number),
43});
44​
45const PersistedSavedEnvironmentStorageRecordSchema = Schema.Struct({
46 environmentId: EnvironmentId,
47 label: Schema.String,
48 httpBaseUrl: Schema.String,
49 wsBaseUrl: Schema.String,
50 createdAt: Schema.String,
51 lastConnectedAt: Schema.NullOr(Schema.String),
52 desktopSsh: Schema.optionalKey(DesktopSshTargetSchema),
53 relayManaged: Schema.optionalKey(Schema.Struct({ relayUrl: Schema.String })),
54 encryptedBearerToken: Schema.optionalKey(Schema.String),
55});
56​
57const SavedEnvironmentRegistryDocumentSchema = Schema.Struct({
58 version: Schema.optionalKey(Schema.Number),
59 records: Schema.optionalKey(Schema.Array(PersistedSavedEnvironmentStorageRecordSchema)),
60});
61​
62const SavedEnvironmentRegistryDocumentJson = fromLenientJson(
63 SavedEnvironmentRegistryDocumentSchema,
64);
65const decodeSavedEnvironmentRegistryDocumentJson = Schema.decodeEffect(
66 SavedEnvironmentRegistryDocumentJson,
67);
68const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
69 SavedEnvironmentRegistryDocumentJson,
70);
71​
72const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
73 "create-temporary-file-name",
74 "encode-registry",
75 "create-directory",
76 "write-temporary-file",
77 "replace-registry-file",
78]);
79​
80const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
81 "check-encryption-availability",
82 "encrypt-secret",
83 "decrypt-secret",
84]);
85​
86export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedError<DesktopSavedEnvironmentsWriteError>()(
87 "DesktopSavedEnvironmentsWriteError",
88 {
89 operation: DesktopSavedEnvironmentsWriteOperation,
90 path: Schema.String,
91 cause: Schema.Defect(),
92 },
93) {
94 override get message(): string {
95 return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
96 }
98​
99export class DesktopSavedEnvironmentsReadError extends Schema.TaggedError<DesktopSavedEnvironmentsReadError>()(
100 "DesktopSavedEnvironmentsReadError",
101 {
102 registryPath: Schema.String,
103 cause: Schema.Defect(),
104 },
105) {
106 override get message(): string {
107 return `Failed to read desktop saved environments at ${this.registryPath}.`;
108 }
110​
111export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedError<DesktopSavedEnvironmentsDocumentDecodeError>()(
112 "DesktopSavedEnvironmentsDocumentDecodeError",
113 {
114 registryPath: Schema.String,
115 cause: Schema.Defect(),
116 },
117) {
118 override get message(): string {
119 return `Failed to decode desktop saved environments at ${this.registryPath}.`;
120 }
122​
123export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError<DesktopSavedEnvironmentSecretDecodeError>()(
124 "DesktopSavedEnvironmentSecretDecodeError",
125 {
126 environmentId: Schema.String,
127 registryPath: Schema.String,
128 field: Schema.Literal("encryptedBearerToken"),
129 cause: Schema.Defect(),
130 },
131) {
132 override get message(): string {
133 return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
134 }
136​
137export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedError<DesktopSavedEnvironmentSecretProtectionError>()(
138 "DesktopSavedEnvironmentSecretProtectionError",
139 {
140 operation: DesktopSavedEnvironmentSecretProtectionOperation,
141 environmentId: Schema.String,
142 registryPath: Schema.String,
143 cause: Schema.Defect(),
144 },
145) {
146 override get message(): string {
147 return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
148 }
150​
151export type DesktopSavedEnvironmentsReadRegistryError =
152 | DesktopSavedEnvironmentsReadError
153 | DesktopSavedEnvironmentsDocumentDecodeError;
154​
155export type DesktopSavedEnvironmentsMutationError =
156 | DesktopSavedEnvironmentsReadRegistryError
157 | DesktopSavedEnvironmentsWriteError;
158​
159export type DesktopSavedEnvironmentsGetSecretError =
160 | DesktopSavedEnvironmentsReadRegistryError
161 | DesktopSavedEnvironmentSecretDecodeError
162 | DesktopSavedEnvironmentSecretProtectionError;
163​
164export type DesktopSavedEnvironmentsSetSecretError =
165 | DesktopSavedEnvironmentsMutationError
166 | DesktopSavedEnvironmentSecretProtectionError;
167​
168export class DesktopSavedEnvironments extends Context.Service<
169 DesktopSavedEnvironments,
170 {
171 readonly getRegistry: Effect.Effect<
172 readonly PersistedSavedEnvironmentRecord[],
173 DesktopSavedEnvironmentsReadRegistryError
174 >;
175 readonly setRegistry: (
176 records: readonly PersistedSavedEnvironmentRecord[],
177 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
178 readonly removeEnvironment: (
179 environmentId: string,
180 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
181 readonly getSecret: (
182 environmentId: string,
183 ) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
184 readonly setSecret: (input: {
185 readonly environmentId: string;
186 readonly secret: string;
187 }) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
188 readonly removeSecret: (
189 environmentId: string,
190 ) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
191 }
192>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
193​
194function toPersistedSavedEnvironmentRecord(
195 record: PersistedSavedEnvironmentStorageRecord,
196): PersistedSavedEnvironmentRecord {
197 const nextRecord = {
198 environmentId: record.environmentId,
199 label: record.label,
200 httpBaseUrl: record.httpBaseUrl,
201 wsBaseUrl: record.wsBaseUrl,
202 createdAt: record.createdAt,
203 lastConnectedAt: record.lastConnectedAt,
204 };
205 return {
206 ...nextRecord,
207 ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
208 ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
209 };
211​
212function toSavedEnvironmentStorageRecord(
213 record: PersistedSavedEnvironmentRecord | PersistedSavedEnvironmentStorageRecord,
214 encryptedBearerToken: Option.Option<string>,
215): PersistedSavedEnvironmentStorageRecord {
216 const nextRecord = {
217 environmentId: record.environmentId,
218 label: record.label,
219 httpBaseUrl: record.httpBaseUrl,
220 wsBaseUrl: record.wsBaseUrl,
221 createdAt: record.createdAt,
222 lastConnectedAt: record.lastConnectedAt,
223 };
224 const metadata = {
225 ...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
226 ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),
227 };
228 return Option.match(encryptedBearerToken, {
229 onNone: () => ({ ...nextRecord, ...metadata }),
230 onSome: (value) => ({ ...nextRecord, ...metadata, encryptedBearerToken: value }),
231 });
233​
234function normalizeSavedEnvironmentRegistryDocument(
235 document: SavedEnvironmentRegistryStorageDocument,
236): SavedEnvironmentRegistryDocument {
237 return {
238 version: document.version ?? 1,
239 records: document.records ?? [],
240 };
242​
243function readRegistryDocument(
244 fileSystem: FileSystem.FileSystem,
245 registryPath: string,
246): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> {
247 return fileSystem.readFileString(registryPath).pipe(
248 Effect.catch((error) =>
249 error.reason._tag === "NotFound"
250 ? Effect.succeed<string | null>(null)
251 : Effect.fail(
252 new DesktopSavedEnvironmentsReadError({
253 registryPath,
254 cause: error,
255 }),
256 ),
257 ),
258 Effect.flatMap((raw) =>
259 raw === null
260 ? Effect.succeed({ version: 1, records: [] })
261 : decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
262 Effect.map(normalizeSavedEnvironmentRegistryDocument),
263 Effect.mapError(
264 (cause) =>
265 new DesktopSavedEnvironmentsDocumentDecodeError({
266 registryPath,
267 cause,
268 }),
269 ),
270 ),
271 ),
272 );
274​
275const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistryDocument")(
276 function* (input: {
277 readonly fileSystem: FileSystem.FileSystem;
278 readonly path: Path.Path;
279 readonly registryPath: string;
280 readonly document: SavedEnvironmentRegistryDocument;
281 readonly suffix: string;
282 }): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {
283 const directory = input.path.dirname(input.registryPath);
284 const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
285 const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
286 Effect.mapError(
287 (cause) =>
288 new DesktopSavedEnvironmentsWriteError({
289 operation: "encode-registry",
290 path: input.registryPath,
291 cause,
292 }),
293 ),
294 );
295 yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
296 Effect.mapError(
297 (cause) =>
298 new DesktopSavedEnvironmentsWriteError({
299 operation: "create-directory",
300 path: directory,
301 cause,
302 }),
303 ),
304 );
305 yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
306 Effect.mapError(
307 (cause) =>
308 new DesktopSavedEnvironmentsWriteError({
309 operation: "write-temporary-file",
310 path: tempPath,
311 cause,
312 }),
313 ),
314 );
315 yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
316 Effect.mapError(
317 (cause) =>
318 new DesktopSavedEnvironmentsWriteError({
319 operation: "replace-registry-file",
320 path: input.registryPath,
321 cause,
322 }),
323 ),
324 );
325 },
326);
327​
328function preserveExistingSecrets(
329 currentDocument: SavedEnvironmentRegistryDocument,
330 records: readonly PersistedSavedEnvironmentRecord[],
331): SavedEnvironmentRegistryDocument {
332 const encryptedBearerTokenById = new Map(
333 currentDocument.records.flatMap((record) =>
334 record.encryptedBearerToken
335 ? [[record.environmentId, record.encryptedBearerToken] as const]
336 : [],
337 ),
338 );
339​
340 return {
341 version: currentDocument.version,
342 records: records.map((record) => {
343 const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
344 return toSavedEnvironmentStorageRecord(record, Option.fromNullishOr(encryptedBearerToken));
345 }),
346 };
348​
349function decodeSecretBytes(
350 environmentId: string,
351 registryPath: string,
352 encoded: string,
353): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
354 return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
355 Effect.mapError(
356 (cause) =>
357 new DesktopSavedEnvironmentSecretDecodeError({
358 environmentId,
359 registryPath,
360 field: "encryptedBearerToken",
361 cause,
362 }),
363 ),
364 );
366​
367/** @public Service construction is part of the canonical Effect module API. */
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);