File size: 1,547 Bytes
1dbc34b | 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | /**
* API key management
*
* Handles generation, storage, and retrieval of the API key for CSRF protection.
* Uses centralized electronUserData methods for path validation.
*/
import crypto from 'crypto';
import {
electronUserDataExists,
electronUserDataReadFileSync,
electronUserDataWriteFileSync,
} from '@automaker/platform';
import { createLogger } from '@automaker/utils/logger';
import { API_KEY_FILENAME } from '../constants';
import { state } from '../state';
const logger = createLogger('ApiKeyManager');
/**
* Ensure an API key exists - load from file or generate new one.
* This key is passed to the server for CSRF protection.
* Uses centralized electronUserData methods for path validation.
*/
export function ensureApiKey(): string {
try {
if (electronUserDataExists(API_KEY_FILENAME)) {
const key = electronUserDataReadFileSync(API_KEY_FILENAME).trim();
if (key) {
state.apiKey = key;
logger.info('Loaded existing API key');
return state.apiKey;
}
}
} catch (error) {
logger.warn('Error reading API key:', error);
}
// Generate new key
state.apiKey = crypto.randomUUID();
try {
electronUserDataWriteFileSync(API_KEY_FILENAME, state.apiKey, {
encoding: 'utf-8',
mode: 0o600,
});
logger.info('Generated new API key');
} catch (error) {
logger.error('Failed to save API key:', error);
}
return state.apiKey;
}
/**
* Get the current API key
*/
export function getApiKey(): string | null {
return state.apiKey;
}
|