A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: Secret and API key input made optional and auto generated.
towfiqi7f9db8104568
diff --git a/backend/src/managers/SecurityKeyManager.ts b/backend/src/managers/SecurityKeyManager.tsindex d55dfee..2b85962 100644--- a/backend/src/managers/SecurityKeyManager.ts+++ b/backend/src/managers/SecurityKeyManager.ts@@ -27,6 +27,20 @@ class SecurityKeyManager {}public async setupInitialKeys(): Promise<void> {+ const keysPath = path.join(appPaths.getDataDir(), 'keys.json');++ // 1. Check if keys already exist (Optimization)+ try {+ const existingContent = JSON.parse(await fs.readFile(keysPath, 'utf-8'));+ if (existingContent.publicKey && existingContent.encryptedPrivateKey) {+ console.log('[SecurityKeyManager] Keys already exist. Skipping generation.');+ this.keyData = existingContent;+ return;+ }+ } catch (e) {+ // File might not exist or be corrupt, proceed to generate+ }+console.log('[SecurityKeyManager] Generating new Ed25519 key pair...');const keyPair = crypto.generateKeyPairSync('ed25519', {privateKeyEncoding: { type: 'pkcs8', format: 'pem' },@@ -36,22 +50,35 @@ class SecurityKeyManager {const cryptr = new Cryptr(configService.config.SECRET);const encryptedPrivateKey = cryptr.encrypt(keyPair.privateKey);- const newKeyData: KeyData = {+ const newKeyData = {publicKey: keyPair.publicKey,encryptedPrivateKey: encryptedPrivateKey,};- // Create the key files- const keysPath = path.join(appPaths.getDataDir(), 'keys.json');+ // 2. MERGE with existing data (Crucial to preserve SECRET/APIKEY)try {- await fs.access(keysPath);- } catch (error) {- await fs.writeFile(keysPath, JSON.stringify(newKeyData, null, 2), { mode: 0o600 });+ let currentFileContent = {};+ try {+ const fileStr = await fs.readFile(keysPath, 'utf-8');+ currentFileContent = JSON.parse(fileStr);+ } catch (e) {+ // File doesn't exist yet, that's fine+ }++ const finalContent = {+ ...currentFileContent,+ ...newKeyData+ };++ await fs.writeFile(keysPath, JSON.stringify(finalContent, null, 2), { mode: 0o600 });console.log(`[SecurityKeyManager] Cryptographic keys securely stored at ${keysPath}`);++ // Update local state+ this.keyData = finalContent as KeyData; // Cast or update interface+ } catch (error) {+ console.error('[SecurityKeyManager] Error saving keys:', error);+ throw error;}-- // Immediately load the newly created keys into the instance- this.keyData = newKeyData;}private async loadKeys(): Promise<void> {diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.tsindex 8aab0b3..eea3c19 100644--- a/backend/src/services/ConfigService.ts+++ b/backend/src/services/ConfigService.ts@@ -1,5 +1,6 @@import { z } from 'zod';import fs from 'fs';+import crypto from 'crypto';import { appPaths } from '../utils/AppPaths';import path from 'path';@@ -10,7 +11,7 @@ const configSchema = z.object({SERVER_PORT: z.coerce.number().int().positive().default(5173),MQTT_PORT: z.coerce.number().int().positive().default(1883).optional(),APP_URL: z.string().default('http://localhost:5173'),- APP_TITLE: z.string().min(1),+ APP_TITLE: z.string().min(1).default('Pluton'),MAX_CONCURRENT_BACKUPS: z.coerce.number().int().positive().default(2),LICENSE_KEY: z.string().optional(),@@ -19,21 +20,17 @@ const configSchema = z.object({ALLOW_FILE_BROWSER: z.coerce.boolean().default(true).optional(),// Security- SECRET: z- .string()- .min(12, { message: 'SECRET must be at least 12 characters long for secure encryption.' }),ENCRYPTION_KEY: z.string().min(12, { message: 'ENCRYPTION_KEY is required for rclone/restic.' }),- APIKEY: z.string().min(12, { message: 'APIKEY must be at least 12 characters long.' }),+ SECRET: z.string().min(12).optional(),+ APIKEY: z.string().min(12).optional(),DISABLE_EVENT_SCRIPTS: z.coerce.boolean().default(false).optional(),// User Authentication- USER_NAME: z.string().min(1),+ USER_NAME: z.string().min(1).default('admin'),USER_PASSWORD: z.string().min(1),SESSION_DURATION: z.coerce.number().int().positive().default(7), // in days});-export type AppConfig = z.infer<typeof configSchema>;-// A schema for the user-editable config.json fileconst userConfigSchema = configSchema.pick({@@ -49,24 +46,64 @@ const userConfigSchema = configSchema}).partial();+const finalConfigSchema = configSchema.extend({+ SECRET: z.string().min(12),+ APIKEY: z.string().min(12),+});++export type AppConfig = z.infer<typeof finalConfigSchema>;+class ConfigService {private static instance: ConfigService;public readonly config: AppConfig;+ private keysPath: string;private constructor() {// Note: dotenv is loaded in index.ts before this service is initialized- // Load env variables- const envConfig = configSchema.partial().parse(process.env);+ // 1. Load env variables+ const rawEnv = process.env;+ const normalizedEnv = { ...rawEnv };- // 3. Layer user's config.json file+ // Map PLUTON_ prefixed variables for non-docker setups+ if (normalizedEnv.PLUTON_ENCRYPTION_KEY) {+ normalizedEnv.ENCRYPTION_KEY = normalizedEnv.PLUTON_ENCRYPTION_KEY;+ }+ if (normalizedEnv.PLUTON_USER_NAME) {+ normalizedEnv.USER_NAME = normalizedEnv.PLUTON_USER_NAME;+ }+ if (normalizedEnv.PLUTON_USER_PASSWORD) {+ normalizedEnv.USER_PASSWORD = normalizedEnv.PLUTON_USER_PASSWORD;+ }++ const envConfig = configSchema.partial().parse(normalizedEnv);+ // Initialize or load SECRET and APIKEY++ // 2. Layer user's config.json filelet fileConfig = {};const configPath = path.join(appPaths.getConfigDir(), 'config.json');try {if (fs.existsSync(configPath)) {const fileContent = fs.readFileSync(configPath, 'utf-8');const parsedJson = JSON.parse(fileContent);- fileConfig = userConfigSchema.parse(parsedJson); // Validate the user's config++ // Security validation: Check if config.json contains sensitive fields+ const sensitiveFields = ['ENCRYPTION_KEY', 'USER_NAME', 'USER_PASSWORD'];+ const foundSensitiveFields = sensitiveFields.filter(field => field in parsedJson);++ if (foundSensitiveFields.length > 0) {+ console.warn(+ '⚠️ [ConfigService] SECURITY WARNING: config.json contains sensitive fields that should be in environment variables:'+ );+ foundSensitiveFields.forEach(field => {+ console.warn(` - ${field}`);+ });+ console.warn(+ '⚠️ These fields will be ignored. Please move them to system environment variables.'+ );+ }++ fileConfig = userConfigSchema.parse(parsedJson); // Validate the user's config (will exclude sensitive fields)console.log(`[ConfigService] Loaded user configuration from ${configPath}`);}} catch (error) {@@ -75,13 +112,20 @@ class ConfigService {);}+ // 3. Load or Generate System Secrets (New logic)+ this.keysPath = path.join(appPaths.getDataDir(), 'keys.json');+ const secrets = this.loadOrGenerateSecrets(envConfig.SECRET, envConfig.APIKEY);+// 4. Merge all sources (file overrides env, which overrides defaults)const mergedConfig = {...envConfig,...fileConfig,+ SECRET: secrets.SECRET, // System secrets fill in the gaps+ APIKEY: secrets.APIKEY,};- const parsedConfig = configSchema.safeParse(mergedConfig);+ // 5. Validate final configuration+ const parsedConfig = finalConfigSchema.safeParse(mergedConfig);if (!parsedConfig.success) {// If validation fails, log the errors and exit immediately.@@ -90,6 +134,11 @@ class ConfigService {parsedConfig.error.issues.forEach(err => {console.error(` - ${err.path.join('.')}: ${err.message}`);});+ console.error('\n💡 Required environment variables for production:');+ console.error(' - ENCRYPTION_KEY (min 12 characters)');+ console.error(' - USER_NAME');+ console.error(' - USER_PASSWORD');+ console.error('\nPlease set these environment variables and restart the application.');process.exit(1);}@@ -97,6 +146,48 @@ class ConfigService {console.log('✅ Environment configuration loaded and validated successfully.');}+ private loadOrGenerateSecrets(envSecret?: string, envApiKey?: string) {+ let keysFileContent: Record<string, any> = {};++ // Read existing keys.json+ try {+ if (fs.existsSync(this.keysPath)) {+ keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));+ }+ } catch (error) {+ // Ignore read errors, we will overwrite/create+ }++ // Priority: Env > Existing File > Generate+ const finalSecret =+ envSecret || keysFileContent.SECRET || crypto.randomBytes(32).toString('hex');+ const finalApiKey =+ envApiKey || keysFileContent.APIKEY || crypto.randomBytes(24).toString('hex');++ // Save if something changed or didn't exist+ if (finalSecret !== keysFileContent.SECRET || finalApiKey !== keysFileContent.APIKEY) {+ try {+ // IMPORTANT: Preserve existing data (like publicKey/encryptedPrivateKey)+ const newContent = {+ ...keysFileContent,+ SECRET: finalSecret,+ APIKEY: finalApiKey,+ };++ // Ensure dir exists (synchronously, as ConfigService is sync)+ const dir = path.dirname(this.keysPath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });++ fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });+ console.log(`[ConfigService] Secrets updated in ${this.keysPath}`);+ } catch (error) {+ console.error(`[ConfigService] Failed to save secrets to keys.json: ${error}`);+ }+ }++ return { SECRET: finalSecret, APIKEY: finalApiKey };+ }+/*** Gets the singleton instance of the ConfigService.*/