Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

2.2 KB
Raw Blame
import fs from 'fs';
import path from 'path';
import bcrypt from 'bcryptjs';
import { appPaths } from './AppPaths';
import { applyStrictPermissions } from './envFileHelpers';
import { prompt } from './cliPrompt';

const BCRYPT_SALT_ROUNDS = 10;

/**
 * Stores the new password hash in keys.json.
 */
async function storeNewPassword(userName: string, password: string): Promise<void> {
	// Hash the password
	const hash = bcrypt.hashSync(password, BCRYPT_SALT_ROUNDS);

	// Update keys.json with new PASSWORD_HASH
	const keysPath = path.join(appPaths.getDataDir(), 'keys.json');
	let keysFileContent: Record<string, any> = {};
	try {
		if (fs.existsSync(keysPath)) {
			keysFileContent = JSON.parse(fs.readFileSync(keysPath, 'utf-8'));
		}
	} catch {
		// Start fresh if keys.json is corrupted
	}

	keysFileContent.PASSWORD_HASH = hash;
	keysFileContent.USER_NAME = userName;
	const dir = path.dirname(keysPath);
	if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
	fs.writeFileSync(keysPath, JSON.stringify(keysFileContent, null, 2), { mode: 0o600 });
	applyStrictPermissions(keysPath);

	console.log('✅ Password hash updated in keys.json.');
}

/**
 * Handles the --reset-password CLI command.
 * Prompts the user interactively for a new username and password.
 *
 * Usage:
 *   pluton --reset-password
 */
export async function handlePasswordReset(): Promise<void> {
	console.log('\n🔐 Pluton Password Reset\n');

	if (!process.stdin.isTTY) {
		console.error('❌ Password reset requires a terminal (TTY).');
		console.error('   Run this command in an interactive terminal.');
		process.exit(1);
	}

	const userName = (await prompt('Enter new username (default: admin): ')).trim() || 'admin';

	const password1 = await prompt('Enter new password: ', true);
	if (!password1) {
		console.error('❌ Password cannot be empty.');
		process.exit(1);
	}

	const password2 = await prompt('Confirm new password: ', true);
	if (password1 !== password2) {
		console.error('❌ Passwords do not match.');
		process.exit(1);
	}

	console.log(`\nResetting password for user: ${userName}`);
	await storeNewPassword(userName, password1);

	console.log(
		'\n✅ Password reset successful. Restart the Pluton service and log in with your new credentials.\n'
	);
	process.exit(0);
}