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