@enactprotocol/shared 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,11 +7,16 @@ import { mkdir, readFile, writeFile } from "fs/promises";
7
7
  // Define config paths
8
8
  const CONFIG_DIR = join(homedir(), ".enact");
9
9
  const CONFIG_FILE = join(CONFIG_DIR, "config.json");
10
+ const TRUSTED_KEYS_DIR = join(CONFIG_DIR, "trusted-keys");
10
11
 
11
12
  // Define config interface
12
13
  export interface EnactConfig {
13
14
  defaultUrl?: string;
14
15
  history?: string[];
16
+ urls?: {
17
+ frontend?: string;
18
+ api?: string;
19
+ };
15
20
  }
16
21
 
17
22
  /**
@@ -23,7 +28,14 @@ export async function ensureConfig(): Promise<void> {
23
28
  }
24
29
 
25
30
  if (!existsSync(CONFIG_FILE)) {
26
- await writeFile(CONFIG_FILE, JSON.stringify({ history: [] }, null, 2));
31
+ const defaultConfig = {
32
+ history: [],
33
+ urls: {
34
+ frontend: DEFAULT_FRONTEND_URL,
35
+ api: DEFAULT_API_URL,
36
+ },
37
+ };
38
+ await writeFile(CONFIG_FILE, JSON.stringify(defaultConfig, null, 2));
27
39
  }
28
40
  }
29
41
 
@@ -35,10 +47,27 @@ export async function readConfig(): Promise<EnactConfig> {
35
47
 
36
48
  try {
37
49
  const data = await readFile(CONFIG_FILE, "utf8");
38
- return JSON.parse(data) as EnactConfig;
50
+ const config = JSON.parse(data) as EnactConfig;
51
+
52
+ // Migrate old configs that don't have URLs section
53
+ if (!config.urls) {
54
+ config.urls = {
55
+ frontend: DEFAULT_FRONTEND_URL,
56
+ api: DEFAULT_API_URL,
57
+ };
58
+ await writeConfig(config);
59
+ }
60
+
61
+ return config;
39
62
  } catch (error) {
40
63
  console.error("Failed to read config:", (error as Error).message);
41
- return { history: [] };
64
+ return {
65
+ history: [],
66
+ urls: {
67
+ frontend: DEFAULT_FRONTEND_URL,
68
+ api: DEFAULT_API_URL,
69
+ },
70
+ };
42
71
  }
43
72
  }
44
73
 
@@ -95,3 +124,315 @@ export async function getDefaultUrl(): Promise<string | undefined> {
95
124
  const config = await readConfig();
96
125
  return config.defaultUrl;
97
126
  }
127
+
128
+ // Default URLs
129
+ const DEFAULT_FRONTEND_URL = "https://enact.tools";
130
+ const DEFAULT_API_URL = "https://xjnhhxwxovjifdxdwzih.supabase.co";
131
+
132
+ // Default trusted public key (Enact Protocol official key)
133
+ const DEFAULT_ENACT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
134
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8VyE3jGm5yT2mKnPx1dQF7q8Z2Kv
135
+ 7mX9YnE2mK8vF3tY9pL6xH2dF8sK3mN7wQ5vT2gR8sL4xN6pM9uE3wF2Qw==
136
+ -----END PUBLIC KEY-----`;
137
+
138
+ // Trusted key metadata interface (for .meta files)
139
+ export interface TrustedKeyMeta {
140
+ name: string;
141
+ description?: string;
142
+ addedAt: string;
143
+ source: "default" | "user" | "organization";
144
+ keyFile: string;
145
+ }
146
+
147
+ // Combined trusted key interface
148
+ export interface TrustedKey {
149
+ id: string;
150
+ name: string;
151
+ publicKey: string;
152
+ description?: string;
153
+ addedAt: string;
154
+ source: "default" | "user" | "organization";
155
+ keyFile: string;
156
+ }
157
+
158
+ /**
159
+ * Get the frontend URL with fallbacks
160
+ */
161
+ export async function getFrontendUrl(): Promise<string> {
162
+ // 1. Environment variable override
163
+ if (process.env.ENACT_FRONTEND_URL) {
164
+ return process.env.ENACT_FRONTEND_URL;
165
+ }
166
+
167
+ // 2. Config file setting
168
+ const config = await readConfig();
169
+ if (config.urls?.frontend) {
170
+ return config.urls.frontend;
171
+ }
172
+
173
+ // 3. Default
174
+ return DEFAULT_FRONTEND_URL;
175
+ }
176
+
177
+ /**
178
+ * Get the API URL with fallbacks
179
+ */
180
+ export async function getApiUrl(): Promise<string> {
181
+ // 1. Environment variable override
182
+ if (process.env.ENACT_API_URL) {
183
+ return process.env.ENACT_API_URL;
184
+ }
185
+
186
+ // 2. Config file setting
187
+ const config = await readConfig();
188
+ if (config.urls?.api) {
189
+ return config.urls.api;
190
+ }
191
+
192
+ // 3. Default
193
+ return DEFAULT_API_URL;
194
+ }
195
+
196
+ /**
197
+ * Set the frontend URL in config
198
+ */
199
+ export async function setFrontendUrl(url: string): Promise<void> {
200
+ const config = await readConfig();
201
+ if (!config.urls) {
202
+ config.urls = {};
203
+ }
204
+ config.urls.frontend = url;
205
+ await writeConfig(config);
206
+ }
207
+
208
+ /**
209
+ * Set the API URL in config
210
+ */
211
+ export async function setApiUrl(url: string): Promise<void> {
212
+ const config = await readConfig();
213
+ if (!config.urls) {
214
+ config.urls = {};
215
+ }
216
+ config.urls.api = url;
217
+ await writeConfig(config);
218
+ }
219
+
220
+ /**
221
+ * Reset URLs to defaults
222
+ */
223
+ export async function resetUrls(): Promise<void> {
224
+ const config = await readConfig();
225
+ if (config.urls) {
226
+ delete config.urls.frontend;
227
+ delete config.urls.api;
228
+ }
229
+ await writeConfig(config);
230
+ }
231
+
232
+ /**
233
+ * Get current URL configuration
234
+ */
235
+ export async function getUrlConfig(): Promise<{
236
+ frontend: { value: string; source: string };
237
+ api: { value: string; source: string };
238
+ }> {
239
+ const config = await readConfig();
240
+
241
+ // Determine frontend URL source
242
+ let frontendValue = DEFAULT_FRONTEND_URL;
243
+ let frontendSource = "default";
244
+
245
+ if (config.urls?.frontend) {
246
+ frontendValue = config.urls.frontend;
247
+ frontendSource = "config";
248
+ }
249
+
250
+ if (process.env.ENACT_FRONTEND_URL) {
251
+ frontendValue = process.env.ENACT_FRONTEND_URL;
252
+ frontendSource = "environment";
253
+ }
254
+
255
+ // Determine API URL source
256
+ let apiValue = DEFAULT_API_URL;
257
+ let apiSource = "default";
258
+
259
+ if (config.urls?.api) {
260
+ apiValue = config.urls.api;
261
+ apiSource = "config";
262
+ }
263
+
264
+ if (process.env.ENACT_API_URL) {
265
+ apiValue = process.env.ENACT_API_URL;
266
+ apiSource = "environment";
267
+ }
268
+
269
+ return {
270
+ frontend: { value: frontendValue, source: frontendSource },
271
+ api: { value: apiValue, source: apiSource },
272
+ };
273
+ }
274
+
275
+ /**
276
+ * Ensure trusted keys directory exists with default key
277
+ */
278
+ async function ensureTrustedKeysDir(): Promise<void> {
279
+ if (!existsSync(CONFIG_DIR)) {
280
+ await mkdir(CONFIG_DIR, { recursive: true });
281
+ }
282
+
283
+ if (!existsSync(TRUSTED_KEYS_DIR)) {
284
+ await mkdir(TRUSTED_KEYS_DIR, { recursive: true });
285
+ }
286
+
287
+ // Create default Enact Protocol key if it doesn't exist
288
+ const defaultKeyFile = join(TRUSTED_KEYS_DIR, "enact-protocol-official.pem");
289
+ const defaultMetaFile = join(TRUSTED_KEYS_DIR, "enact-protocol-official.meta");
290
+
291
+ if (!existsSync(defaultKeyFile)) {
292
+ await writeFile(defaultKeyFile, DEFAULT_ENACT_PUBLIC_KEY);
293
+ }
294
+
295
+ if (!existsSync(defaultMetaFile)) {
296
+ const defaultMeta: TrustedKeyMeta = {
297
+ name: "Enact Protocol Official",
298
+ description: "Official Enact Protocol signing key for verified tools",
299
+ addedAt: new Date().toISOString(),
300
+ source: "default",
301
+ keyFile: "enact-protocol-official.pem"
302
+ };
303
+ await writeFile(defaultMetaFile, JSON.stringify(defaultMeta, null, 2));
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Read all trusted keys from directory
309
+ */
310
+ export async function getTrustedKeys(): Promise<TrustedKey[]> {
311
+ await ensureTrustedKeysDir();
312
+
313
+ const keys: TrustedKey[] = [];
314
+
315
+ try {
316
+ const { readdir } = await import('fs/promises');
317
+ const files = await readdir(TRUSTED_KEYS_DIR);
318
+
319
+ // Get all .pem files
320
+ const pemFiles = files.filter(f => f.endsWith('.pem'));
321
+
322
+ for (const pemFile of pemFiles) {
323
+ try {
324
+ const keyId = pemFile.replace('.pem', '');
325
+ const keyPath = join(TRUSTED_KEYS_DIR, pemFile);
326
+ const metaPath = join(TRUSTED_KEYS_DIR, `${keyId}.meta`);
327
+
328
+ // Read the public key
329
+ const publicKey = await readFile(keyPath, 'utf8');
330
+
331
+ // Read metadata if it exists
332
+ let meta: TrustedKeyMeta = {
333
+ name: keyId,
334
+ addedAt: new Date().toISOString(),
335
+ source: "user",
336
+ keyFile: pemFile
337
+ };
338
+
339
+ if (existsSync(metaPath)) {
340
+ try {
341
+ const metaData = await readFile(metaPath, 'utf8');
342
+ meta = { ...meta, ...JSON.parse(metaData) };
343
+ } catch {
344
+ // Use defaults if meta file is corrupted
345
+ }
346
+ }
347
+
348
+ keys.push({
349
+ id: keyId,
350
+ name: meta.name,
351
+ publicKey: publicKey.trim(),
352
+ description: meta.description,
353
+ addedAt: meta.addedAt,
354
+ source: meta.source,
355
+ keyFile: pemFile
356
+ });
357
+ } catch (error) {
358
+ console.warn(`Warning: Could not read key file ${pemFile}:`, error);
359
+ }
360
+ }
361
+ } catch (error) {
362
+ console.error("Failed to read trusted keys directory:", error);
363
+ }
364
+
365
+ return keys;
366
+ }
367
+
368
+ /**
369
+ * Add a trusted key
370
+ */
371
+ export async function addTrustedKey(keyData: {
372
+ id: string;
373
+ name: string;
374
+ publicKey: string;
375
+ description?: string;
376
+ source?: "user" | "organization";
377
+ }): Promise<void> {
378
+ await ensureTrustedKeysDir();
379
+
380
+ const keyFile = `${keyData.id}.pem`;
381
+ const metaFile = `${keyData.id}.meta`;
382
+ const keyPath = join(TRUSTED_KEYS_DIR, keyFile);
383
+ const metaPath = join(TRUSTED_KEYS_DIR, metaFile);
384
+
385
+ // Check if key already exists
386
+ if (existsSync(keyPath)) {
387
+ throw new Error(`Key with ID '${keyData.id}' already exists`);
388
+ }
389
+
390
+ // Write the public key file
391
+ await writeFile(keyPath, keyData.publicKey);
392
+
393
+ // Write the metadata file
394
+ const meta: TrustedKeyMeta = {
395
+ name: keyData.name,
396
+ description: keyData.description,
397
+ addedAt: new Date().toISOString(),
398
+ source: keyData.source || "user",
399
+ keyFile
400
+ };
401
+ await writeFile(metaPath, JSON.stringify(meta, null, 2));
402
+ }
403
+
404
+ /**
405
+ * Remove a trusted key
406
+ */
407
+ export async function removeTrustedKey(keyId: string): Promise<void> {
408
+ const keyPath = join(TRUSTED_KEYS_DIR, `${keyId}.pem`);
409
+ const metaPath = join(TRUSTED_KEYS_DIR, `${keyId}.meta`);
410
+
411
+ if (!existsSync(keyPath)) {
412
+ throw new Error(`Trusted key '${keyId}' not found`);
413
+ }
414
+
415
+ // Remove both files
416
+ const { unlink } = await import('fs/promises');
417
+ await unlink(keyPath);
418
+
419
+ if (existsSync(metaPath)) {
420
+ await unlink(metaPath);
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Get a specific trusted key
426
+ */
427
+ export async function getTrustedKey(keyId: string): Promise<TrustedKey | null> {
428
+ const keys = await getTrustedKeys();
429
+ return keys.find(k => k.id === keyId) || null;
430
+ }
431
+
432
+ /**
433
+ * Check if a public key is trusted
434
+ */
435
+ export async function isKeyTrusted(publicKey: string): Promise<boolean> {
436
+ const keys = await getTrustedKeys();
437
+ return keys.some(k => k.publicKey.trim() === publicKey.trim());
438
+ }