import { safeStorage, app } from 'electron' import { readFile, writeFile, mkdir } from 'node:fs/promises' import { join, dirname } from 'node:path' import { existsSync } from 'node:fs' export class CredentialStore { private filePath: string private data: Record = {} constructor() { this.filePath = join(app.getPath('userData'), 'credentials.json') } async load(): Promise { try { if (!existsSync(this.filePath)) return const raw = await readFile(this.filePath, 'utf-8') let parsed: Record try { parsed = JSON.parse(raw) as Record } catch { console.warn('[CredentialStore] credentials.json is corrupted — starting fresh') this.data = {} return } for (const [key, value] of Object.entries(parsed)) { try { if (value.startsWith('plain:')) { this.data[key] = Buffer.from(value.slice(6), 'base64').toString() } else if (value.startsWith('enc:')) { this.data[key] = safeStorage.decryptString(Buffer.from(value.slice(4), 'base64')) } else { // старый формат без префикса — пробуем расшифровать this.data[key] = safeStorage.decryptString(Buffer.from(value, 'base64')) } } catch { console.warn(`Failed to decrypt credential for ${key}`) } } } catch { this.data = {} } } async save(accountId: string, secret: string): Promise { this.data[accountId] = secret await this.persist() } get(accountId: string): string | undefined { return this.data[accountId] } async remove(accountId: string): Promise { delete this.data[accountId] await this.persist() } isEncryptionAvailable(): boolean { return safeStorage.isEncryptionAvailable() } private async persist(): Promise { const canEncrypt = safeStorage.isEncryptionAvailable() if (!canEncrypt) { console.warn( '[CredentialStore] safeStorage unavailable — credentials stored without encryption. ' + 'Install a keychain daemon (e.g. gnome-keyring or kwallet) for secure storage.' ) } const out: Record = {} for (const [key, value] of Object.entries(this.data)) { if (canEncrypt) { out[key] = 'enc:' + safeStorage.encryptString(value).toString('base64') } else { // safeStorage недоступен — храним обфусцированно, без реального шифрования out[key] = 'plain:' + Buffer.from(value).toString('base64') } } const dir = dirname(this.filePath) if (!existsSync(dir)) { await mkdir(dir, { recursive: true }) } await writeFile(this.filePath, JSON.stringify(out, null, 2), 'utf-8') } }