diff --git a/lib/config.js b/lib/config.js index 241a93e9..a6ecf322 100644 --- a/lib/config.js +++ b/lib/config.js @@ -2,7 +2,7 @@ import path from 'node:path'; import os from 'node:os'; import { readJson, writeJson } from './file.js'; -import { existsSync } from 'node:fs'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; export const GLOBAL_CONFIG = Symbol('globalConfig'); @@ -61,13 +61,31 @@ export function getConfigPath(configType, dir) { }; export function writeConfig(configType, obj, dir) { - writeJson(getConfigPath(configType, dir), obj); + const configPath = getConfigPath(configType, dir); + const encryptedConfigPath = configPath + '.gpg'; + if (existsSync(encryptedConfigPath)) { + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'ncurc-')); + const tmpFile = path.join(tmpDir, 'config.json'); + try { + writeJson(tmpFile, obj); + const { status } = spawnSync('gpg', + ['--default-recipient-self', '--yes', '--encrypt', '--output', encryptedConfigPath, tmpFile] + ); + if (status !== 0) { + throw new Error('Failed to encrypt config file: ' + encryptedConfigPath); + } + } finally { + rmSync(tmpDir, { recursive: true, force: true }); + } + return encryptedConfigPath; + } + writeJson(configPath, obj); + return configPath; }; export function updateConfig(configType, obj, dir) { const config = getConfig(configType, dir); - const configPath = getConfigPath(configType, dir); - writeJson(configPath, Object.assign(config, obj)); + writeConfig(configType, Object.assign(config, obj), dir); }; export function getHomeDir(home) {