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

clientPersistence.ts

229 lines6.7 KB

1import * as FS from "node:fs";
2import * as Path from "node:path";
3​
4import {
5 ClientSettingsSchema,
6 type ClientSettings,
7 type PersistedSavedEnvironmentRecord,
8} from "@workbench/contracts";
9import { Predicate } from "effect";
10import * as Schema from "effect/Schema";
11​
12interface ClientSettingsDocument {
13 readonly settings: ClientSettings;
15​
16interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
17 readonly encryptedBearerToken?: string;
19​
20interface SavedEnvironmentRegistryDocument {
21 readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
23​
24export interface DesktopSecretStorage {
25 readonly isEncryptionAvailable: () => boolean;
26 readonly encryptString: (value: string) => Buffer;
27 readonly decryptString: (value: Buffer) => string;
29​
30function readJsonFile<T>(filePath: string): T | null {
31 try {
32 if (!FS.existsSync(filePath)) {
33 return null;
34 }
35 return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
36 } catch {
37 return null;
38 }
40​
41function writeJsonFile(filePath: string, value: unknown): void {
42 const directory = Path.dirname(filePath);
43 const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
44 FS.mkdirSync(directory, { recursive: true });
45 FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
46 FS.renameSync(tempPath, filePath);
48​
49function isPersistedSavedEnvironmentStorageRecord(
50 value: unknown,
51): value is PersistedSavedEnvironmentStorageRecord {
52 return (
53 Predicate.isObject(value) &&
54 typeof value.environmentId === "string" &&
55 typeof value.label === "string" &&
56 typeof value.httpBaseUrl === "string" &&
57 typeof value.wsBaseUrl === "string" &&
58 typeof value.createdAt === "string" &&
59 (value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
60 (value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
61 );
63​
64function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
65 const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
66 if (!Predicate.isObject(parsed)) {
67 return { records: [] };
68 }
69​
70 return {
71 records: Array.isArray(parsed.records)
72 ? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
73 : [],
74 };
76​
77function toPersistedSavedEnvironmentRecord(
78 record: PersistedSavedEnvironmentStorageRecord,
79): PersistedSavedEnvironmentRecord {
80 return {
81 environmentId: record.environmentId,
82 label: record.label,
83 httpBaseUrl: record.httpBaseUrl,
84 wsBaseUrl: record.wsBaseUrl,
85 createdAt: record.createdAt,
86 lastConnectedAt: record.lastConnectedAt,
87 };
89​
90export function readClientSettings(settingsPath: string): ClientSettings | null {
91 const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
92 if (!raw) {
93 return null;
94 }
95 try {
96 return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
97 } catch {
98 return null;
99 }
101​
102export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
103 writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
105​
106export function readSavedEnvironmentRegistry(
107 registryPath: string,
108): readonly PersistedSavedEnvironmentRecord[] {
109 return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
110 toPersistedSavedEnvironmentRecord(record),
111 );
113​
114export function writeSavedEnvironmentRegistry(
115 registryPath: string,
116 records: readonly PersistedSavedEnvironmentRecord[],
117): void {
118 const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
119 const encryptedBearerTokenById = new Map(
120 currentDocument.records.flatMap((record) =>
121 record.encryptedBearerToken
122 ? [[record.environmentId, record.encryptedBearerToken] as const]
123 : [],
124 ),
125 );
126 writeJsonFile(registryPath, {
127 records: records.map((record) => {
128 const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
129 return encryptedBearerToken
130 ? {
131 environmentId: record.environmentId,
132 label: record.label,
133 httpBaseUrl: record.httpBaseUrl,
134 wsBaseUrl: record.wsBaseUrl,
135 createdAt: record.createdAt,
136 lastConnectedAt: record.lastConnectedAt,
137 encryptedBearerToken,
138 }
139 : record;
140 }),
141 } satisfies SavedEnvironmentRegistryDocument);
143​
144export function readSavedEnvironmentSecret(input: {
145 readonly registryPath: string;
146 readonly environmentId: string;
147 readonly secretStorage: DesktopSecretStorage;
148}): string | null {
149 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
150 const encoded = document.records.find(
151 (record) => record.environmentId === input.environmentId,
152 )?.encryptedBearerToken;
153 if (!encoded) {
154 return null;
155 }
156​
157 if (!input.secretStorage.isEncryptionAvailable()) {
158 return null;
159 }
160​
161 try {
162 return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
163 } catch {
164 return null;
165 }
167​
168export function writeSavedEnvironmentSecret(input: {
169 readonly registryPath: string;
170 readonly environmentId: string;
171 readonly secret: string;
172 readonly secretStorage: DesktopSecretStorage;
173}): boolean {
174 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
175​
176 if (!input.secretStorage.isEncryptionAvailable()) {
177 return false;
178 }
179​
180 let found = false;
181​
182 writeJsonFile(input.registryPath, {
183 records: document.records.map((record) => {
184 if (record.environmentId !== input.environmentId) {
185 return record;
186 }
187​
188 found = true;
189 const encryptedBearerToken = input.secretStorage
190 .encryptString(input.secret)
191 .toString("base64");
192 return {
193 environmentId: record.environmentId,
194 label: record.label,
195 httpBaseUrl: record.httpBaseUrl,
196 wsBaseUrl: record.wsBaseUrl,
197 createdAt: record.createdAt,
198 lastConnectedAt: record.lastConnectedAt,
199 encryptedBearerToken,
200 } satisfies PersistedSavedEnvironmentStorageRecord;
201 }),
202 } satisfies SavedEnvironmentRegistryDocument);
203 return found;
205​
206export function removeSavedEnvironmentSecret(input: {
207 readonly registryPath: string;
208 readonly environmentId: string;
209}): void {
210 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
211 if (
212 !document.records.some(
213 (record) =>
214 record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
215 )
216 ) {
217 return;
218 }
219​
220 writeJsonFile(input.registryPath, {
221 records: document.records.map((record) => {
222 if (record.environmentId !== input.environmentId) {
223 return record;
224 }
225​
226 return toPersistedSavedEnvironmentRecord(record);
227 }),
228 } satisfies SavedEnvironmentRegistryDocument);