-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathapi-key.ts
More file actions
40 lines (31 loc) · 1.06 KB
/
Copy pathapi-key.ts
File metadata and controls
40 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { safeStorage } from 'electron';
import type { AppSettings } from '../shared/types';
export function encryptApiKey(rawKey: string): string {
if (!safeStorage.isEncryptionAvailable()) {
throw new Error('Encryption is not available on this system. Cannot store API key securely.');
}
const encrypted = safeStorage.encryptString(rawKey);
return encrypted.toString('base64');
}
export function decryptApiKey(encrypted: string): string {
if (!encrypted) {
throw new Error('No encrypted API key to decrypt.');
}
if (!safeStorage.isEncryptionAvailable()) {
throw new Error('Encryption is not available on this system. Cannot read API key.');
}
return safeStorage.decryptString(Buffer.from(encrypted, 'base64'));
}
export function isApiKeySet(settings: AppSettings): boolean {
return settings.openaiApiKeyEncrypted.length > 0;
}
export function getApiKey(settings: AppSettings): string | null {
if (!isApiKeySet(settings)) {
return null;
}
try {
return decryptApiKey(settings.openaiApiKeyEncrypted);
} catch {
return null;
}
}