A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
refactor: make linux installations run as a non-root pluton user
towfiqi42ad7a511463
diff --git a/backend/__tests__/controllers/SetupController.test.ts b/backend/__tests__/controllers/SetupController.test.tsindex b6b0381..1a1caee 100644--- a/backend/__tests__/controllers/SetupController.test.ts+++ b/backend/__tests__/controllers/SetupController.test.ts@@ -30,6 +30,7 @@ jest.mock('../../src/db', () => ({jest.mock('../../src/utils/AppPaths', () => ({appPaths: {getDataDir: jest.fn().mockReturnValue('/mock/data'),+ getEncEnvFilePath: jest.fn().mockReturnValue('/mock/config/pluton.enc.env'),},}));diff --git a/backend/__tests__/managers/handlers/BackupHandler.test.ts b/backend/__tests__/managers/handlers/BackupHandler.test.tsindex 7b0bb72..dbeee33 100644--- a/backend/__tests__/managers/handlers/BackupHandler.test.ts+++ b/backend/__tests__/managers/handlers/BackupHandler.test.ts@@ -123,8 +123,9 @@ describe('BackupHandler', () => {process.env.ENCRYPTION_KEY = 'test-key';- // Mock fs.promises.access+ // Mock filesystem checks used by canRun.jest.spyOn(fs.promises, 'access').mockResolvedValue(undefined);+ jest.spyOn(fs.promises, 'stat').mockResolvedValue({} as any);// Simulate the event listener that responds to backup_init by emitting backup_created.// This mirrors what BackupEventService.onBackupInit does in production.@@ -545,7 +546,7 @@ describe('BackupHandler', () => {it('should throw error when source paths not accessible', async () => {jest.spyOn(os, 'freemem').mockReturnValue(1024 * 1024 * 1024);- jest.spyOn(fs.promises, 'access').mockRejectedValue(new Error('Path not found'));+ jest.spyOn(fs.promises, 'stat').mockRejectedValue(new Error('Path not found'));const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', baseOptions as any);await expect(handler.canRun(baseOptions, resticArgsAndEnv)).rejects.toThrow(@@ -1083,7 +1084,7 @@ describe('BackupHandler', () => {it('should list all inaccessible paths in error message', async () => {jest.spyOn(os, 'freemem').mockReturnValue(1024 * 1024 * 1024);- jest.spyOn(fs.promises, 'access').mockRejectedValue(new Error('Not accessible'));+ jest.spyOn(fs.promises, 'stat').mockRejectedValue(new Error('Not accessible'));const optionsMultiplePaths = {...baseOptions,@@ -1104,7 +1105,7 @@ describe('BackupHandler', () => {it('should check each source path individually', async () => {jest.spyOn(os, 'freemem').mockReturnValue(1024 * 1024 * 1024);- const accessSpy = jest.spyOn(fs.promises, 'access').mockResolvedValue(undefined);+ const statSpy = jest.spyOn(fs.promises, 'stat').mockResolvedValue({} as any);const optionsMultiplePaths = {...baseOptions,@@ -1120,9 +1121,9 @@ describe('BackupHandler', () => {);await handler.canRun(optionsMultiplePaths, resticArgsAndEnv);- expect(accessSpy).toHaveBeenCalledTimes(2);- expect(accessSpy).toHaveBeenCalledWith('C:\\path1', fs.constants.R_OK);- expect(accessSpy).toHaveBeenCalledWith('C:\\path2', fs.constants.R_OK);+ expect(statSpy).toHaveBeenCalledTimes(2);+ expect(statSpy).toHaveBeenCalledWith('C:\\path1');+ expect(statSpy).toHaveBeenCalledWith('C:\\path2');});});diff --git a/backend/__tests__/managers/handlers/RestoreHandler.test.ts b/backend/__tests__/managers/handlers/RestoreHandler.test.tsindex 2479fb8..51f2ea4 100644--- a/backend/__tests__/managers/handlers/RestoreHandler.test.ts+++ b/backend/__tests__/managers/handlers/RestoreHandler.test.ts@@ -672,6 +672,46 @@ describe('RestoreHandler', () => {});});+ describe('createHelperRestoreArgs', () => {+ it('should render helper restore arguments from the shared restore request', () => {+ const result = handler.createHelperRestoreArgs('backup-1', 'snapshot-123', baseOptions, true);++ expect(result).toEqual(+ expect.arrayContaining([+ 'restore',+ '--repo',+ 'rclone:test-storage:backups/test',+ '--snapshot',+ 'snapshot-123',+ '--target',+ '/restore/target',+ '--dry-run',+ '--insecure-no-password',+ '--gomaxprocs',+ '2',+ '--rclone-transfers',+ '4',+ '--rclone-buffer-size',+ '16M',+ '--rclone-multi-thread-streams',+ '4',+ ])+ );+ });++ it('should omit the helper no-password flag when encryption is enabled', () => {+ const result = handler.createHelperRestoreArgs('backup-1', 'snapshot-123', {+ ...baseOptions,+ encryption: true,+ overwrite: 'if-newer',+ });++ expect(result).toContain('--overwrite');+ expect(result).toContain('if-newer');+ expect(result).not.toContain('--insecure-no-password');+ });+ });+describe('createHandlers', () => {it('should create handlers that emit proper events', () => {const errorListener = jest.fn();diff --git a/backend/__tests__/services/ConfigService.test.ts b/backend/__tests__/services/ConfigService.test.tsindex f1e7001..c220aec 100644--- a/backend/__tests__/services/ConfigService.test.ts+++ b/backend/__tests__/services/ConfigService.test.ts@@ -7,6 +7,7 @@ const mockWriteFileSync = jest.fn();const mockMkdirSync = jest.fn();const mockGetConfigDir = jest.fn() as jest.MockedFunction<() => string>;const mockGetDataDir = jest.fn() as jest.MockedFunction<() => string>;+const mockGetEncEnvFilePath = jest.fn() as jest.MockedFunction<() => string>;const mockDotenvConfig = jest.fn();// Mock fs module@@ -23,6 +24,7 @@ jest.mock('../../src/utils/AppPaths', () => ({appPaths: {getConfigDir: mockGetConfigDir,getDataDir: mockGetDataDir,+ getEncEnvFilePath: mockGetEncEnvFilePath,},}));@@ -74,10 +76,12 @@ describe('ConfigService', () => {mockDotenvConfig.mockReset();mockGetConfigDir.mockReset();mockGetDataDir.mockReset();+ mockGetEncEnvFilePath.mockReset();// Mock appPaths to return a predictable directorymockGetConfigDir.mockReturnValue('/fake/config/dir');mockGetDataDir.mockReturnValue('/fake/data/dir');+ mockGetEncEnvFilePath.mockReturnValue('/fake/data/dir/pluton.enc.env');// Clear the module cache to reset the singletonjest.resetModules();diff --git a/backend/__tests__/utils/initSetup.test.ts b/backend/__tests__/utils/initSetup.test.tsindex 5e53f6c..00cbace 100644--- a/backend/__tests__/utils/initSetup.test.ts+++ b/backend/__tests__/utils/initSetup.test.ts@@ -48,6 +48,7 @@ jest.mock('../../src/utils/AppPaths', () => ({getSyncDir: jest.fn().mockReturnValue('/data/sync'),getConfigDir: jest.fn().mockReturnValue('/data/config'),getRescueDir: jest.fn().mockReturnValue('/data/rescue'),+ getEncEnvFilePath: jest.fn().mockReturnValue('/data/pluton.enc.env'),},}));diff --git a/backend/src/controllers/SetupController.ts b/backend/src/controllers/SetupController.tsindex b7e9925..5a615ae 100644--- a/backend/src/controllers/SetupController.ts+++ b/backend/src/controllers/SetupController.ts@@ -1,5 +1,6 @@import { Request, Response } from 'express';import fs from 'fs';+import path from 'path';import { configService } from '../services/ConfigService';import { requiresDesktopSetup, isBinaryMode } from '../utils/installHelpers';import { writeEncryptionKeyToEnvFile, encEnvFileExists } from '../utils/envFileHelpers';@@ -138,10 +139,10 @@ export class SetupController {*/async checkKeyringAvailability(req: Request, res: Response) {try {- const dataDir = appPaths.getDataDir();+ const encEnvDir = path.dirname(appPaths.getEncEnvFilePath());let writable = false;try {- fs.accessSync(dataDir, fs.constants.W_OK);+ fs.accessSync(encEnvDir, fs.constants.W_OK);writable = true;} catch {writable = false;diff --git a/backend/src/managers/BaseSystemManager.ts b/backend/src/managers/BaseSystemManager.tsindex 7410273..c24b31c 100644--- a/backend/src/managers/BaseSystemManager.ts+++ b/backend/src/managers/BaseSystemManager.ts@@ -14,6 +14,7 @@ import { BaseStorageManager } from './BaseStorageManager';import { runCommand } from '../utils/runCommand';import { appPaths } from '../utils/AppPaths';import { saveRcloneGlobalSettings, saveResticGlobalSettings } from '../utils/globalSettings';+import { isLinuxInstalledRuntime, runHelper } from '../utils/linuxHelper';const execAsync = promisify(exec);@@ -783,11 +784,17 @@ export class BaseSystemManager {return { success: false, result: 'lsblk is only supported on Linux systems' };}- const { stdout, stderr } = await execAsync(- 'lsblk --json -o NAME,FSTYPE,LABEL,UUID,MOUNTPOINT,SIZE'- );- if (stderr) {- return { success: false, result: `Error executing lsblk: ${stderr}` };+ let lsblkOutput: string;+ if (isLinuxInstalledRuntime()) {+ lsblkOutput = await runHelper('system-info', ['mounts']);+ } else {+ const { stdout, stderr } = await execAsync(+ 'lsblk --json -o NAME,FSTYPE,LABEL,UUID,MOUNTPOINT,SIZE'+ );+ if (stderr) {+ return { success: false, result: `Error executing lsblk: ${stderr}` };+ }+ lsblkOutput = stdout;}let dfData;@@ -799,24 +806,7 @@ export class BaseSystemManager {console.log('df output failed!');}- const filesystems = await this.analyzeBlockDevices(stdout, dfData);-- // const dummyOutput =- // '{"blockdevices":[{"name":"vda","fstype":null,"label":null,"uuid":null,"mountpoint":null,"size":"10G","children":[{"name":"vda1","fstype":null,"label":null,"uuid":null,"mountpoint":null,"size":"1M"},{"name":"vda2","fstype":"vfat","label":null,"uuid":"A893-0D16","mountpoint":"/boot/efi","size":"256M"},{"name":"vda3","fstype":"ext4","label":null,"uuid":"fc0fca72-9290-4996-b6c3-5b963959e146","mountpoint":"/boot","size":"800M"},{"name":"vda4","fstype":"ext4","label":null,"uuid":"cbdc5f51-f4b3-4772-9d61-86cb1e2b089c","mountpoint":"/","size":"9G"}]},{"name":"vdb","fstype":"ext4","label":"ephemeral0","uuid":"e8afea20-c269-4593-9347-2622cd524c1e","mountpoint":"/data","size":"300G"}]}';- // const dummyDFOutput = `Filesystem Size Used Avail Use% Mounted on- // tmpfs 1.2G 976K 1.2G 1% /run- // efivarfs 56K 16K 36K 30% /sys/firmware/efi/efivars- // /dev/vda4 8.8G 4.2G 4.2G 51% /- // tmpfs 5.9G 0 5.9G 0% /dev/shm- // tmpfs 5.0M 0 5.0M 0% /run/lock- // /dev/vdb 295G 612M 279G 1% /data- // /dev/vda3 770M 65M 650M 10% /boot- // /dev/vda2 256M 6.1M 250M 3% /boot/efi- // overlay 8.8G 4.2G 4.2G 51% /var/lib/docker/overlay2/233a3438f3732cb014fbb15261647c03877ffced00278e8a6abee4c27111acd7/merged- // tmpfs 1.2G 0 1.2G 0% /run/user/0- // overlay 8.8G 4.2G 4.2G 51% /var/lib/docker/overlay2/6d0db4005ad4a4cdee861888afc2fa886c7afdeaef68752944ffb18b5a04ac03/merged`;- // const dfData = this.parseDfOutput(dummyDFOutput);- // const filesystems = await this.analyzeBlockDevices(dummyOutput, dfData);+ const filesystems = await this.analyzeBlockDevices(lsblkOutput, dfData);return { success: true, result: filesystems };} catch {diff --git a/backend/src/managers/handlers/BackupHandler.ts b/backend/src/managers/handlers/BackupHandler.tsindex 1a6916b..d9f6949 100644--- a/backend/src/managers/handlers/BackupHandler.ts+++ b/backend/src/managers/handlers/BackupHandler.ts@@ -531,7 +531,10 @@ export class BackupHandler {const pathsNotFound = [];for (const path of options.sourceConfig.includes) {try {- await fs.promises.access(path, fs.constants.R_OK);+ // must use stat instead of access since the linux-helper has read capabilities+ // through CAP_DAC_READ_SEARCH, which causes access to return false even when the path is readable.+ // stat correctly returns the file info without being affected by permissions.+ await fs.promises.stat(path);} catch (error) {pathsNotFound.push(path);}diff --git a/backend/src/managers/handlers/DownloadHandler.ts b/backend/src/managers/handlers/DownloadHandler.tsindex 4acda5f..3271817 100644--- a/backend/src/managers/handlers/DownloadHandler.ts+++ b/backend/src/managers/handlers/DownloadHandler.ts@@ -32,7 +32,7 @@ export class DownloadHandler {targetPath: zipPath,});- await mkdir(path.dirname(tempDir), { recursive: true });+ await mkdir(tempDir, { recursive: true });return new Promise((resolve, reject) => {const handlers = this.createHandlers(planId, backupId);diff --git a/backend/src/managers/handlers/RestoreHandler.ts b/backend/src/managers/handlers/RestoreHandler.tsindex 8f4245a..d237472 100644--- a/backend/src/managers/handlers/RestoreHandler.ts+++ b/backend/src/managers/handlers/RestoreHandler.ts@@ -3,8 +3,13 @@ import os from 'os';import { existsSync, constants } from 'fs';import { rm, access } from 'fs/promises';import { EventEmitter } from 'events';-import { getSnapshotByTag, runResticCommand } from '../../utils/restic/restic';+import { getSnapshotByTag, runHelperRestore, runResticCommand } from '../../utils/restic/restic';import { generateResticRepoPath, resticPathToWindows } from '../../utils/restic/helpers';+import {+ buildHelperRestoreArgs,+ buildResticRestoreCommand,+ createNormalizedRestoreRequest,+} from '../../utils/restic/restoreArgs';import { processManager } from '../ProcessManager';import copyFilesNatively from '../../utils/copyFiles';import { ResticRestoredFile, ResticSnapshot } from '../../types/restic';@@ -13,6 +18,13 @@ import { appPaths } from '../../utils/AppPaths';import { RestoreOptions } from '../../types/restores';import { RestoreStatsManager } from '../RestoreStatsManager';import { configService } from '../../services/ConfigService';+import {+ canWriteTargetOrParent,+ isHelperDeniedTarget,+ isLinuxInstalledRuntime,+ isPermissionDeniedError,+ runHelper,+} from '../../utils/linuxHelper';export class RestoreHandler {private runningRestores = new Set<string>();@@ -268,20 +280,54 @@ export class RestoreHandler {await this.updateProgress(planId, restoreId, 'restore', 'RESTORE_OPERATION_START', false);const handlers = this.createHandlers(planId, backupId, restoreId);const resticOpts = this.createResticRestoreArgs(backupId, snapshot.id, options);+ const helperArgs = this.createHelperRestoreArgs(backupId, snapshot.id, options);+ const useHelper = await this.shouldUseHelperRestore(options);try {- const result = await runResticCommand(- resticOpts.args,- resticOpts.env,- handlers.onProgress,- handlers.onError,- handlers.onComplete,- process => processManager.trackProcess(`restore-${restoreId}`, process)- );+ const result = useHelper+ ? await runHelperRestore(+ helperArgs,+ handlers.onProgress,+ handlers.onError,+ handlers.onComplete,+ process => processManager.trackProcess(`restore-${restoreId}`, process)+ )+ : await runResticCommand(+ resticOpts.args,+ resticOpts.env,+ handlers.onProgress,+ handlers.onError,+ handlers.onComplete,+ process => processManager.trackProcess(`restore-${restoreId}`, process)+ );await this.updateProgress(planId, restoreId, 'restore', 'RESTORE_OPERATION_COMPLETE', true);return result;} catch (error: any) {- const errMsg = error.message || 'Restic restore command failed';+ let restoreError = error;+ if (!useHelper && isLinuxInstalledRuntime() && isPermissionDeniedError(error)) {+ await this.validateHelperRestoreTarget(options);+ try {+ const result = await runHelperRestore(+ helperArgs,+ handlers.onProgress,+ handlers.onError,+ handlers.onComplete,+ process => processManager.trackProcess(`restore-${restoreId}`, process)+ );+ await this.updateProgress(+ planId,+ restoreId,+ 'restore',+ 'RESTORE_OPERATION_COMPLETE',+ true+ );+ return result;+ } catch (helperError) {+ restoreError = helperError;+ }+ }++ const errMsg = restoreError.message || 'Restic restore command failed';// On macOS, restic exits with code 1 for non-fatal xattr errors (e.g.,// SIP-protected "com.apple.rootless"). The file data is restored successfully;@@ -314,7 +360,7 @@ export class RestoreHandler {true,errMsg);- throw error;+ throw restoreError;}}@@ -460,7 +506,20 @@ export class RestoreHandler {}// Check if target path is accessible- if (options.target && options.target !== '/') {+ if (isLinuxInstalledRuntime()) {+ await this.validateHelperRestoreTarget(options);+ const target = options.target || '/';+ const targetWritable = await canWriteTargetOrParent(target);+ if (!targetWritable) {+ try {+ await runHelper('version');+ } catch (error: any) {+ throw new Error(+ `Target path requires pluton-helper, but helper is unavailable: ${error.message}`+ );+ }+ }+ } else if (options.target && options.target !== '/') {try {await access(path.dirname(options.target), constants.W_OK);} catch (error) {@@ -468,11 +527,13 @@ export class RestoreHandler {}}- // Check if restic is installed- try {- await runResticCommand(['version']);- } catch (error) {- throw new Error(`Restic is not installed.`);+ // Check if restic is installed when the direct path may be used.+ if (!isLinuxInstalledRuntime() || (await canWriteTargetOrParent(options.target || '/'))) {+ try {+ await runResticCommand(['version']);+ } catch (error) {+ throw new Error(`Restic is not installed.`);+ }}return true;@@ -484,76 +545,32 @@ export class RestoreHandler {options: RestoreOptions,dryRun: boolean = false) {- const {- storageName,- storagePath,- encryption,- target,- overwrite = 'always',- delete: deleteOption,- includes,- excludes,- performanceSettings: performance,- } = options;- const repoPassword = encryption ? configService.config.ENCRYPTION_KEY : '';- const repoPath = generateResticRepoPath(storageName, storagePath || '');- const overWriteCommand = overwrite == 'always' ? [] : ['--overwrite', overwrite];- // Set the target path for the restore operation- // If Windows, use a Pluton temp directory as restic may not restore to original paths on Windows.- let theTargetPath = target || '/';- const restoresDir = appPaths.getRestoresDir();- const winRestorePath = path.join(restoresDir, 'backup-' + backupId);- if (theTargetPath === '/' && process.platform === 'win32') {- theTargetPath = winRestorePath;- }- const resticEnv: Record<string, string> = {};- const resticArgs = [- 'restore',- '-r',- repoPath,+ const repoPassword = options.encryption ? configService.config.ENCRYPTION_KEY : '';+ const request = createNormalizedRestoreRequest(+ backupId,snapshotId,- '--target',- theTargetPath,- ...overWriteCommand,- '--verbose=2',- '--json',- ];-- if (includes && includes.length > 0) {- includes.forEach(item => {- resticArgs.push('--include', item);- });- }- if (excludes && excludes.length > 0) {- excludes.forEach(item => {- resticArgs.push('--exclude', item);- });- }- if (deleteOption) {- resticArgs.push('--delete');- }-- if (performance) {- if (performance.maxProcessor) resticEnv.GOMAXPROCS = performance.maxProcessor.toString();- if (performance.transfers) {- resticEnv['RCLONE_TRANSFERS'] = performance.transfers.toString();- }- if (performance.bufferSize) {- resticEnv['RCLONE_BUFFER_SIZE'] = performance.bufferSize;- }- if (performance.multiThreadStream) {- resticEnv['RCLONE_MULTI_THREAD_STREAMS'] = performance.multiThreadStream.toString();- }- }-- if (!encryption) {- resticArgs.push('--insecure-no-password');- }+ options,+ repoPassword,+ dryRun+ );+ return buildResticRestoreCommand(request);+ }- if (dryRun) {- resticArgs.push('--dry-run');- }- return { args: resticArgs, env: { RESTIC_PASSWORD: repoPassword, ...resticEnv } };+ createHelperRestoreArgs(+ backupId: string,+ snapshotId: string,+ options: RestoreOptions,+ dryRun: boolean = false+ ) {+ const repoPassword = options.encryption ? configService.config.ENCRYPTION_KEY : '';+ const request = createNormalizedRestoreRequest(+ backupId,+ snapshotId,+ options,+ repoPassword,+ dryRun+ );+ return buildHelperRestoreArgs(request);}async dryRestore(@@ -563,19 +580,24 @@ export class RestoreHandler {): Promise<{ success: boolean; result: string | { stats: any; files: ResticRestoredFile[] } }> {try {const resticOpts = this.createResticRestoreArgs(backupId, snapshotId, options, true);- const dryRes = await runResticCommand(resticOpts.args, resticOpts.env);+ const helperArgs = this.createHelperRestoreArgs(backupId, snapshotId, options, true);+ let dryRes: string;- const jsonLines = dryRes.split('\n').filter(line => line.trim());- const parsedLines = jsonLines.map(line => JSON.parse(line));- const stats = parsedLines.find(item => item.message_type === 'summary');+ if (await this.shouldUseHelperRestore(options)) {+ dryRes = await runHelperRestore(helperArgs);+ } else {+ try {+ dryRes = await runResticCommand(resticOpts.args, resticOpts.env);+ } catch (error) {+ if (!isLinuxInstalledRuntime() || !isPermissionDeniedError(error)) {+ throw error;+ }+ await this.validateHelperRestoreTarget(options);+ dryRes = await runHelperRestore(helperArgs);+ }+ }- const files: ResticRestoredFile[] = parsedLines- .filter(item => item.message_type === 'verbose_status')- .map(item => ({- path: process.platform === 'win32' ? resticPathToWindows(item.item) : item.item,- size: parseInt(item.size, 10),- action: item.action,- }));+ const { stats, files } = this.parseDryRestoreResult(dryRes);return {success: true,@@ -597,6 +619,46 @@ export class RestoreHandler {}}+ private async shouldUseHelperRestore(options: RestoreOptions): Promise<boolean> {+ if (!isLinuxInstalledRuntime()) {+ return false;+ }++ await this.validateHelperRestoreTarget(options);+ return !(await canWriteTargetOrParent(options.target || '/'));+ }++ private async validateHelperRestoreTarget(options: RestoreOptions): Promise<void> {+ const target = options.target || '/';+ const allowRootTarget = target === '/' && ((options.includes?.length || 0) > 0 || (options.sources?.length || 0) > 0);+ if (isHelperDeniedTarget(target, allowRootTarget)) {+ throw new Error(+ `Restore target is not allowed for privileged restore: ${target}. Choose a non-system directory such as /srv/pluton-restore.`+ );+ }+ if (target === '/' && !allowRootTarget) {+ throw new Error(+ "Privileged restore to '/' requires at least one included source path so the helper can scope the restore."+ );+ }+ }++ private parseDryRestoreResult(dryRes: string): { stats: any; files: ResticRestoredFile[] } {+ const jsonLines = dryRes.split('\n').filter(line => line.trim());+ const parsedLines = jsonLines.map(line => JSON.parse(line));+ const stats = parsedLines.find(item => item.message_type === 'summary');++ const files: ResticRestoredFile[] = parsedLines+ .filter(item => item.message_type === 'verbose_status')+ .map(item => ({+ path: process.platform === 'win32' ? resticPathToWindows(item.item) : item.item,+ size: parseInt(item.size, 10),+ action: item.action,+ }));++ return { stats, files };+ }+async cancel(planId: string, restoreId: string) {this.cancelledRestores.add(planId);await this.progressManager.markCompleted(@@ -630,7 +692,7 @@ export class RestoreHandler {error: data.toString(),});},- onComplete: (code: number) => {+ onComplete: (code: number | null) => {this.emitter.emit('restore_complete', {backupId,restoreId,diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.tsindex d488067..a9dca93 100644--- a/backend/src/services/ConfigService.ts+++ b/backend/src/services/ConfigService.ts@@ -3,7 +3,10 @@ import fs from 'fs';import { appPaths } from '../utils/AppPaths';import path from 'path';import { requiresDesktopSetup } from '../utils/installHelpers';-import { readEncryptionKeyFromEnvFile, verifyFilePermissions } from '../utils/envFileHelpers';+import {+ readEncryptionKeyFromEnvFile,+ verifyFilePermissions,+} from '../utils/envFileHelpers';import { credentialManager } from './CredentialManager';// Schema for the .env config file (with optional sensitive fields for setup mode)@@ -123,14 +126,9 @@ class ConfigService {}// 1b. Load ENCRYPTION_KEY from pluton.enc.env if not already in process env- // On server installs, the file lives in /etc/pluton/; on desktop, in the data dir.const dataDir = appPaths.getDataDir();if (!normalizedEnv.ENCRYPTION_KEY) {- const serverEncEnvPath = '/etc/pluton/pluton.enc.env';- const envFileKey =- (process.platform !== 'win32' && fs.existsSync(serverEncEnvPath)- ? readEncryptionKeyFromEnvFile('/etc/pluton')- : null) ?? readEncryptionKeyFromEnvFile(dataDir);+ const envFileKey = readEncryptionKeyFromEnvFile(dataDir);if (envFileKey) {normalizedEnv.ENCRYPTION_KEY = envFileKey;console.log('[ConfigService] Loaded ENCRYPTION_KEY from pluton.enc.env');@@ -235,12 +233,7 @@ class ConfigService {// Verify permissions on sensitive filesverifyFilePermissions(credentialManager.getKeysPath());- const serverEncEnvPath = '/etc/pluton/pluton.enc.env';- const encEnvPath =- process.platform !== 'win32' && fs.existsSync(serverEncEnvPath)- ? serverEncEnvPath- : path.join(dataDir, 'pluton.enc.env');- verifyFilePermissions(encEnvPath);+ verifyFilePermissions(appPaths.getEncEnvFilePath());console.log('✅ Environment configuration loaded and validated successfully.');}diff --git a/backend/src/services/RestoreService.ts b/backend/src/services/RestoreService.tsindex 58b5be2..df1d2ff 100644--- a/backend/src/services/RestoreService.ts+++ b/backend/src/services/RestoreService.ts@@ -108,6 +108,7 @@ export class RestoreService {includes: restoreConfig.includes,excludes: restoreConfig.excludes,replicationId: restoreConfig.replicationId,+ sources: plan.sourceConfig?.includes || [],});diff --git a/backend/src/services/events/BackupEventService.ts b/backend/src/services/events/BackupEventService.tsindex ca02e60..fc31016 100644--- a/backend/src/services/events/BackupEventService.ts+++ b/backend/src/services/events/BackupEventService.ts@@ -7,7 +7,7 @@ import { PlanStore } from '../../stores/PlanStore';import { planLogger } from '../../utils/logger';import { BackupNotification } from '../../notifications/BackupNotification';import { appPaths } from '../../utils/AppPaths';-import { backupInsertSchema, NewBackup } from '../../db/schema/backups';+import { Backup, backupInsertSchema, NewBackup } from '../../db/schema/backups';import { SourceTypes } from '../../types/source';// import { jobProcessor } from '../../jobs/JobProcessor';import {@@ -88,7 +88,7 @@ export class BackupEventService {compression,sourceConfig,taskStats: null,- method: 'backup',+ method: thePlan.method,};// Parse Backup Data@@ -206,19 +206,31 @@ export class BackupEventService {}}- const backup = await this.backupStore.update(backupId, {+ const backupPayload: Partial<Backup> = {inProgress: false,status: success ? 'completed' : 'failed',success: !!success,ended: sql`(unixepoch())` as any,completionStats: summaryData ? summaryData : null,- });+ ...(success ? { errorMsg: null } : {}),+ };+ const plan = await this.planStore.getById(planId);++ if (plan?.method === 'rescue') {+ // Since rescue does not do a dry run, we backfill the taskStats with the summary data+ // from the completion event, so that it can be used in notifications and elsewhere.+ const shouldBackfillTaskStats = success && summaryData;+ if (shouldBackfillTaskStats) {+ backupPayload.taskStats = { ...summaryData, dry_run: false } as any;+ }+ }++ const backup = await this.backupStore.update(backupId, backupPayload);if (!backup) {throw new Error('Failed to update Backup entry in Database.');}// Send Notification- const plan = await this.planStore.getById(data.planId);if (plan && plan.settings.notification) {// Include replication failures in the success notification if any mirrors failedconst replicationFailures = (backup.mirrors || [])diff --git a/backend/src/types/plans.ts b/backend/src/types/plans.tsindex fe12ea7..15a23f6 100644--- a/backend/src/types/plans.ts+++ b/backend/src/types/plans.ts@@ -109,6 +109,7 @@ export type PlanScript = {logOutput: boolean;timeout?: number;abortOnError?: boolean; // only when event type is onBackupStart+ runAsRoot?: boolean;};export type PlanPerformanceSettings = {diff --git a/backend/src/types/restores.ts b/backend/src/types/restores.tsindex 6ec9fd1..493c07a 100644--- a/backend/src/types/restores.ts+++ b/backend/src/types/restores.ts@@ -29,6 +29,7 @@ export interface RestoreConfig {delete: boolean;storageId?: string;replicationId?: string;+ sources?: string[];}export interface RestoreStats {diff --git a/backend/src/utils/AppPaths.ts b/backend/src/utils/AppPaths.tsindex 0ca1a43..7b9cbab 100644--- a/backend/src/utils/AppPaths.ts+++ b/backend/src/utils/AppPaths.ts@@ -1,8 +1,7 @@-// src/utils/AppPaths.ts-import path from 'path';import os from 'os';import fs from 'fs'; // Use the synchronous fs module+import { isLinuxInstalledRuntime } from './linuxHelper';/*** Defines the structure for all application paths.@@ -31,9 +30,11 @@ class AppPaths {private static instance: AppPaths;private paths!: IAppPaths;private isInitialized = false;+ private isLinuxRuntime: boolean = false;// The constructor is now responsible for immediate, synchronous initialization.private constructor() {+ this.isLinuxRuntime = isLinuxInstalledRuntime();this.initializeSync();}@@ -108,7 +109,7 @@ class AppPaths {}const baseDir = this.getTheBaseDir();- const tempBase = os.tmpdir();+ const tempBase = this.isLinuxRuntime ? baseDir : os.tmpdir();this.paths = {base: baseDir,@@ -118,7 +119,7 @@ class AppPaths {logs: path.join(baseDir, 'logs'),progress: path.join(baseDir, 'progress'),stats: path.join(baseDir, 'stats'),- temp: path.join(tempBase, 'pluton'),+ temp: this.isLinuxRuntime ? path.join(baseDir, 'temp') : path.join(tempBase, 'pluton'),cache: path.join(tempBase, 'pluton', 'cache'),downloads: path.join(tempBase, 'pluton', 'downloads'),restores: path.join(tempBase, 'pluton', 'restores'),@@ -149,7 +150,9 @@ class AppPaths {} catch (error: any) {if (error.code !== 'EEXIST') {console.error(- `FATAL: Could not create directory ${dir}. Please ensure you have the correct permissions (run with sudo/administrator).`+ this.isLinuxRuntime+ ? `FATAL: Could not create directory ${dir}. Check that the installer created it and that it is owned by the pluton user.`+ : `FATAL: Could not create directory ${dir}. Please ensure you have the correct permissions (run with sudo/administrator).`);throw error; // Halt execution}@@ -237,6 +240,9 @@ class AppPaths {public getEncEnvFilePath(): string {this.checkInitialized();+ if (this.isLinuxRuntime) {+ return path.join('/etc/pluton', 'pluton.enc.env');+ }return path.join(this.paths.base, 'pluton.enc.env');}}diff --git a/backend/src/utils/envFileHelpers.ts b/backend/src/utils/envFileHelpers.tsindex 9057144..1040f41 100644--- a/backend/src/utils/envFileHelpers.ts+++ b/backend/src/utils/envFileHelpers.ts@@ -2,6 +2,7 @@ import fs from 'fs';import path from 'path';import os from 'os';import { execSync } from 'child_process';+import { isBinaryMode, isDockerMode } from './installHelpers';const ENV_FILE_NAME = 'pluton.enc.env';@@ -9,9 +10,16 @@ const ENV_FILE_NAME = 'pluton.enc.env';* Get the full path to the pluton.enc.env file in the given data directory.*/export function getEncEnvFilePath(dataDir: string): string {+ if (isLinuxInstalledRuntime()) {+ return path.join('/etc/pluton', ENV_FILE_NAME);+ }return path.join(dataDir, ENV_FILE_NAME);}+export function isLinuxInstalledRuntime(): boolean {+ return os.platform() === 'linux' && isBinaryMode() && !isDockerMode();+}+/*** Check whether the pluton.enc.env file exists in the given data directory.*/diff --git a/backend/src/utils/executeUserScript.ts b/backend/src/utils/executeUserScript.tsindex fb31d99..1c954ce 100644--- a/backend/src/utils/executeUserScript.ts+++ b/backend/src/utils/executeUserScript.ts@@ -3,6 +3,7 @@ import os from 'os';import path from 'path';import fs from 'fs';import { PlanScript } from '../types/plans';+import { isLinuxInstalledRuntime, runRootHelper } from './linuxHelper';/*** Executes a user-defined script file, capturing its output@@ -13,38 +14,39 @@ import { PlanScript } from '../types/plans';* @returns A promise that resolves with the stdout and stderr of the script.* @throws An error if the script fails (non-zero exit code) or times out.*/-export function executeUserScript(script: PlanScript): Promise<{ stdout: string; stderr: string }> {- return new Promise((resolve, reject) => {- const { scriptPath, timeout } = script;-- if (!scriptPath || !scriptPath.trim()) {- reject(new Error('Script path is empty.'));- return;- }-- // Validate path safety- if (scriptPath.includes('..')) {- reject(new Error('Script path contains ".." traversal sequences.'));- return;- }-- if (!path.isAbsolute(scriptPath)) {- reject(new Error(`Script path must be absolute, got: ${scriptPath}`));- return;- }+export async function executeUserScript(+ script: PlanScript+): Promise<{ stdout: string; stderr: string }> {+ const { scriptPath, timeout } = script;+ validateScriptPath(scriptPath);- // Verify the file exists- if (!fs.existsSync(scriptPath)) {- reject(new Error(`Script file does not exist: ${scriptPath}`));- return;- }+ if (script.runAsRoot && isLinuxInstalledRuntime()) {+ let stdout = '';+ let stderr = '';+ const scriptArgs = getScriptArgs(script);- const stat = fs.statSync(scriptPath);- if (stat.isDirectory()) {- reject(new Error(`Script path is a directory, not a file: ${scriptPath}`));- return;+ try {+ stdout = await runRootHelper('run-script', [scriptPath, ...scriptArgs], {+ timeoutMs: timeout ? timeout * 1000 : undefined,+ onStdout: data => {+ stdout += data.toString();+ },+ onStderr: data => {+ stderr += data.toString();+ },+ });+ return { stdout, stderr };+ } catch (error: any) {+ if (isSudoersAuthorizationError(error)) {+ throw new Error(+ `Root script requires an explicit sudoers rule for this script. Ask an administrator to grant NOPASSWD access for: /usr/bin/pluton-helper run-script ${scriptPath}`+ );+ }+ throw error;}+ }+ return new Promise((resolve, reject) => {// Determine how to execute based on file extensionconst { executable, args } = determineScriptExecution(scriptPath);@@ -86,6 +88,46 @@ export function executeUserScript(script: PlanScript): Promise<{ stdout: string;});}+function isSudoersAuthorizationError(error: unknown): boolean {+ const candidate = error as { message?: string; stderr?: string };+ const text = `${candidate?.message || ''}\n${candidate?.stderr || ''}`;+ return (+ /\ba password is required\b/i.test(text) ||+ /\bno tty present and no askpass program specified\b/i.test(text) ||+ /\ba terminal is required\b/i.test(text) ||+ /\bis not in the sudoers file\b/i.test(text) ||+ /\bmay not run sudo\b/i.test(text) ||+ /\bnot allowed to execute\b/i.test(text) ||+ /\bsudoers\b/i.test(text)+ );+}++function validateScriptPath(scriptPath: string): void {+ if (!scriptPath || !scriptPath.trim()) {+ throw new Error('Script path is empty.');+ }++ if (scriptPath.includes('..')) {+ throw new Error('Script path contains ".." traversal sequences.');+ }++ if (!path.isAbsolute(scriptPath)) {+ throw new Error(`Script path must be absolute, got: ${scriptPath}`);+ }++ const stat = fs.statSync(scriptPath);+ if (stat.isDirectory()) {+ throw new Error(`Script path is a directory, not a file: ${scriptPath}`);+ }+}++function getScriptArgs(script: PlanScript): string[] {+ const candidate =+ (script as PlanScript & { args?: unknown; scriptArgs?: unknown }).args ??+ (script as PlanScript & { scriptArgs?: unknown }).scriptArgs;+ return Array.isArray(candidate) ? candidate.map(String) : [];+}+/*** Determines how to execute a script based on its file extension and the current OS.*/diff --git a/backend/src/utils/linuxHelper.ts b/backend/src/utils/linuxHelper.tsnew file mode 100644index 0000000..2daeda5--- /dev/null+++ b/backend/src/utils/linuxHelper.ts@@ -0,0 +1,178 @@+import { ChildProcess, spawn } from 'child_process';+import path from 'path';+import { constants } from 'fs';+import { access, stat } from 'fs/promises';+import { isBinaryMode, isDockerMode } from './installHelpers';++export const INSTALLED_HELPER_PATH = '/usr/bin/pluton-helper';++export type HelperCommandError = Error & {+ code?: number | null;+ stdout?: string;+ stderr?: string;+};++export type HelperRunOptions = {+ env?: Record<string, string>;+ cwd?: string;+ onStdout?: (data: Buffer) => void;+ onStderr?: (data: Buffer) => void;+ onComplete?: (code: number | null) => void;+ onProcess?: (process: ChildProcess) => void;+ timeoutMs?: number;+};++const helperDeniedTargets = new Set([+ '/',+ '/bin',+ '/boot',+ '/dev',+ '/etc',+ '/lib',+ '/lib64',+ '/proc',+ '/run',+ '/sbin',+ '/sys',+ '/usr',+]);++export function isLinuxInstalledRuntime(): boolean {+ return process.platform === 'linux' && isBinaryMode() && !isDockerMode();+}++export function getHelperPath(): string {+ if (!isLinuxInstalledRuntime() && process.env.PLUTON_HELPER_PATH) {+ return process.env.PLUTON_HELPER_PATH;+ }+ if (process.env.NODE_ENV === 'test' && process.env.PLUTON_HELPER_PATH) {+ return process.env.PLUTON_HELPER_PATH;+ }+ return INSTALLED_HELPER_PATH;+}++export function runHelper(+ subcommand: string,+ args: string[] = [],+ options: HelperRunOptions = {}+): Promise<string> {+ return runHelperProcess(getHelperPath(), [subcommand, ...args], options);+}++export function runRootHelper(+ subcommand: string,+ args: string[] = [],+ options: HelperRunOptions = {}+): Promise<string> {+ return runHelperProcess('sudo', ['-n', getHelperPath(), subcommand, ...args], options);+}++function runHelperProcess(+ command: string,+ args: string[],+ options: HelperRunOptions+): Promise<string> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, {+ cwd: options.cwd,+ env: { ...process.env, ...options.env },+ timeout: options.timeoutMs,+ });++ options.onProcess?.(child);++ let stdout = '';+ let stderr = '';+ let settled = false;++ child.stdout?.on('data', (data: Buffer) => {+ stdout += data.toString();+ options.onStdout?.(data);+ });++ child.stderr?.on('data', (data: Buffer) => {+ stderr += data.toString();+ options.onStderr?.(data);+ });++ child.on('error', error => {+ settled = true;+ const helperError: HelperCommandError = new Error(+ `Failed to run pluton-helper: ${error.message}`+ );+ helperError.stdout = stdout.trim();+ helperError.stderr = stderr.trim();+ reject(helperError);+ });++ child.on('close', code => {+ if (settled) return;+ options.onComplete?.(code);+ if (code === 0) {+ resolve(stdout.trim());+ return;+ }++ const message = stderr.trim() || stdout.trim() || `pluton-helper failed with code ${code}`;+ const error: HelperCommandError = new Error(message);+ error.code = code;+ error.stdout = stdout.trim();+ error.stderr = stderr.trim();+ reject(error);+ });+ });+}++export function isPermissionDeniedError(error: unknown): boolean {+ const candidate = error as { code?: string | number; message?: string; stderr?: string };+ const text = `${candidate?.message || ''}\n${candidate?.stderr || ''}`;+ return (+ candidate?.code === 'EACCES' ||+ candidate?.code === 'EPERM' ||+ /\b(EACCES|EPERM)\b/i.test(text) ||+ /permission denied|operation not permitted/i.test(text)+ );+}++export function isHelperDeniedTarget(target: string, allowRootTarget: boolean = false): boolean {+ const normalized = normalizeLinuxPath(target);+ for (const deniedTarget of helperDeniedTargets) {+ if (deniedTarget === '/') {+ if (normalized === '/' && !allowRootTarget) return true;+ continue;+ }+ if (normalized === deniedTarget || normalized.startsWith(`${deniedTarget}/`)) {+ return true;+ }+ }+ return false;+}++export async function canWriteTargetOrParent(target: string): Promise<boolean> {+ const normalized = path.resolve(target);+ try {+ const targetStat = await stat(normalized);+ const writablePath = targetStat.isDirectory() ? normalized : path.dirname(normalized);+ await access(writablePath, constants.W_OK);+ return true;+ } catch (error: any) {+ if (error?.code !== 'ENOENT') {+ return false;+ }+ }++ try {+ await access(path.dirname(normalized), constants.W_OK);+ return true;+ } catch {+ return false;+ }+}++function normalizeLinuxPath(target: string): string {+ let normalized = path.posix.normalize(target.replace(/\\/g, '/'));+ if (!normalized.startsWith('/')) {+ normalized = path.posix.resolve('/', normalized);+ }+ return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized;+}diff --git a/backend/src/utils/restic/restic.ts b/backend/src/utils/restic/restic.tsindex b65c8d5..9a34aa4 100644--- a/backend/src/utils/restic/restic.ts+++ b/backend/src/utils/restic/restic.ts@@ -9,6 +9,7 @@ import { generateResticRepoPath } from './helpers';import { configService } from '../../services/ConfigService';import { buildResticEnvFromSettings, buildRcloneEnvFromSettings } from '../globalSettings';import { BackupVerifiedResult } from '../../types/plans';+import { runHelper } from '../linuxHelper';export type ResticCommandError = Error & {code?: number;@@ -158,6 +159,22 @@ export function runResticCommand(});}+export function runHelperRestore(+ args: string[],+ onProgress?: (data: Buffer) => void,+ onError?: (data: Buffer) => void,+ onComplete?: (code: number | null) => void,+ onProcess?: (process: any) => void+): Promise<string> {+ const helperArgs = args[0] === 'restore' ? args.slice(1) : args;+ return runHelper('restore', helperArgs, {+ onStdout: onProgress,+ onStderr: onError,+ onComplete,+ onProcess,+ });+}+export async function getBackupPlanStats(planId: string,storageName: string,diff --git a/backend/src/utils/restic/restoreArgs.ts b/backend/src/utils/restic/restoreArgs.tsnew file mode 100644index 0000000..89cf54e--- /dev/null+++ b/backend/src/utils/restic/restoreArgs.ts@@ -0,0 +1,175 @@+import path from 'path';+import { z } from 'zod';+import { RestoreOptions } from '../../types/restores';+import { appPaths } from '../AppPaths';+import { generateResticRepoPath } from './helpers';++const performanceSettingsSchema = z+ .object({+ maxProcessor: z.number().int().nonnegative().optional(),+ transfers: z.number().int().nonnegative().optional(),+ bufferSize: z.string().min(1).optional(),+ multiThreadStream: z.number().int().nonnegative().optional(),+ })+ .partial();++const restoreRequestSchema = z.object({+ backupId: z.string().min(1),+ snapshotId: z.string().min(1),+ repoPath: z.string().min(1),+ repoPassword: z.string(),+ encryption: z.boolean(),+ target: z.string().min(1),+ overwrite: z.enum(['always', 'if-changed', 'if-newer', 'never']),+ includes: z.array(z.string().min(1)),+ excludes: z.array(z.string().min(1)),+ delete: z.boolean(),+ dryRun: z.boolean(),+ performanceSettings: performanceSettingsSchema.optional(),+ sources: z.array(z.string().min(1)).optional(),+});++export type NormalizedRestoreRequest = z.infer<typeof restoreRequestSchema>;++export function createNormalizedRestoreRequest(+ backupId: string,+ snapshotId: string,+ options: RestoreOptions,+ repoPassword: string,+ dryRun: boolean = false,+ platform: NodeJS.Platform = process.platform+): NormalizedRestoreRequest {+ const repoPath = generateResticRepoPath(options.storageName, options.storagePath || '');+ let target = options.target || '/';++ if (target === '/' && platform === 'win32') {+ target = path.join(appPaths.getRestoresDir(), `backup-${backupId}`);+ }++ return restoreRequestSchema.parse({+ backupId,+ snapshotId,+ repoPath,+ repoPassword,+ encryption: options.encryption,+ target,+ sources: options.sources || [],+ overwrite: options.overwrite || 'always',+ includes: options.includes || [],+ excludes: options.excludes || [],+ delete: options.delete || false,+ dryRun,+ performanceSettings: options.performanceSettings,+ });+}++export function buildResticRestoreCommand(request: NormalizedRestoreRequest): {+ args: string[];+ env: Record<string, string>;+} {+ const overwriteArgs = request.overwrite === 'always' ? [] : ['--overwrite', request.overwrite];+ const resticArgs = [+ 'restore',+ '-r',+ request.repoPath,+ request.snapshotId,+ '--target',+ request.target,+ ...overwriteArgs,+ '--verbose=2',+ '--json',+ ];++ for (const item of request.includes) {+ resticArgs.push('--include', item);+ }+ for (const item of request.excludes) {+ resticArgs.push('--exclude', item);+ }+ if (request.delete) {+ resticArgs.push('--delete');+ }+ if (!request.encryption) {+ resticArgs.push('--insecure-no-password');+ }+ if (request.dryRun) {+ resticArgs.push('--dry-run');+ }++ const env: Record<string, string> = {+ RESTIC_PASSWORD: request.repoPassword,+ };+ if (request.performanceSettings?.maxProcessor) {+ env.GOMAXPROCS = request.performanceSettings.maxProcessor.toString();+ }+ if (request.performanceSettings?.transfers) {+ env.RCLONE_TRANSFERS = request.performanceSettings.transfers.toString();+ }+ if (request.performanceSettings?.bufferSize) {+ env.RCLONE_BUFFER_SIZE = request.performanceSettings.bufferSize;+ }+ if (request.performanceSettings?.multiThreadStream) {+ env.RCLONE_MULTI_THREAD_STREAMS = request.performanceSettings.multiThreadStream.toString();+ }++ return { args: resticArgs, env };+}++export function buildHelperRestoreArgs(request: NormalizedRestoreRequest): string[] {+ const helperArgs = [+ 'restore',+ '--repo',+ request.repoPath,+ '--snapshot',+ request.snapshotId,+ '--target',+ request.target,+ ];++ if (+ (request.target === '/' || !request.target) &&+ request.includes.length === 0 &&+ request.sources &&+ request.sources.length > 0+ ) {+ for (const item of request.sources) {+ helperArgs.push('--include', item);+ }+ }++ if (request.overwrite !== 'always') {+ helperArgs.push('--overwrite', request.overwrite);+ }+ for (const item of request.includes) {+ helperArgs.push('--include', item);+ }+ for (const item of request.excludes) {+ helperArgs.push('--exclude', item);+ }+ if (request.delete) {+ helperArgs.push('--delete');+ }+ if (!request.encryption) {+ helperArgs.push('--insecure-no-password');+ }+ if (request.dryRun) {+ helperArgs.push('--dry-run');+ }+ if (request.performanceSettings?.maxProcessor) {+ helperArgs.push('--gomaxprocs', request.performanceSettings.maxProcessor.toString());+ }+ if (request.performanceSettings?.transfers) {+ helperArgs.push('--rclone-transfers', request.performanceSettings.transfers.toString());+ }+ if (request.performanceSettings?.bufferSize) {+ helperArgs.push('--rclone-buffer-size', request.performanceSettings.bufferSize);+ }+ if (request.performanceSettings?.multiThreadStream) {+ helperArgs.push(+ '--rclone-multi-thread-streams',+ request.performanceSettings.multiThreadStream.toString()+ );+ }++ return helperArgs;+}diff --git a/frontend/src/@types/plans.ts b/frontend/src/@types/plans.tsindex 53ad36b..021a1c7 100644--- a/frontend/src/@types/plans.ts+++ b/frontend/src/@types/plans.ts@@ -119,6 +119,7 @@ export type PlanScript = {logOutput: boolean;timeout?: number;abortOnError?: boolean;+ runAsRoot?: boolean;};export interface PlanReplicationStorage {diff --git a/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx b/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsxindex a7d76e2..58bf4c9 100644--- a/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx+++ b/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx@@ -1,6 +1,6 @@import classes from './PlanSettings.module.scss';import { useState } from 'react';-import { NewPlanSettings } from '../../../@types/plans';+import { NewPlanSettings, PlanScript } from '../../../@types/plans';import Icon from '../../common/Icon/Icon';import Toggle from '../../common/form/Toggle/Toggle';import { secondsToMinutes } from '../../../utils/helpers';@@ -45,7 +45,7 @@ const PlanScriptsSettings = ({onBackupFailure: [],onBackupComplete: [],},- platform,+ platform = '',onUpdate,}: PlanScriptsSettingsProps) => {const [showTimeoutSettings, setShowTimeoutSettings] = useState<string | false>(false);@@ -56,8 +56,18 @@ const PlanScriptsSettings = ({onBackupFailure: false,onBackupComplete: false,});- console.log('settings :', settings);- console.log('### platform :', platform);++ const showRootOption = platform.toLowerCase().includes('linux');+ // const showRootOption = true;++ const updateScriptBool = (eventKey: ScriptEventKey, index: number, key: keyof PlanScript, value: boolean) => {+ const updatedScripts = [...(settings[eventKey] || [])];+ updatedScripts[index] = {+ ...updatedScripts[index],+ [key]: value,+ };+ onUpdate({ ...settings, [eventKey]: updatedScripts });+ };return (<div className={classes.eventTabs}>@@ -171,48 +181,36 @@ const PlanScriptsSettings = ({// label="Enabled"fieldValue={script?.enabled || false}inline={true}- onUpdate={(checked: boolean) => {- const updatedScripts = [...(scripts || [])];- updatedScripts[index] = {- ...updatedScripts[index],- enabled: checked,- };- onUpdate({ ...settings, [eventKey]: updatedScripts });- }}+ onUpdate={(checked: boolean) => updateScriptBool(key, index, 'enabled', checked)}/><span>Enabled</span></div>- <div className={classes.scriptOptionCheckbox}>+ {/* <div className={classes.scriptOptionCheckbox}><TogglefieldValue={script?.logOutput || false}inline={true}- onUpdate={(checked: boolean) => {- const updatedScripts = [...(scripts || [])];- updatedScripts[index] = {- ...updatedScripts[index],- logOutput: checked,- };- onUpdate({ ...settings, [eventKey]: updatedScripts });- }}+ onUpdate={(checked: boolean) => updateScriptBool(key, index, 'logOutput', checked)}/><span>Log Output</span>- </div>+ </div> */}<div className={classes.scriptOptionCheckbox}><Toggle- // label="Abort On Error"fieldValue={script?.abortOnError || false}inline={true}- onUpdate={(checked: boolean) => {- const updatedScripts = [...(scripts || [])];- updatedScripts[index] = {- ...updatedScripts[index],- abortOnError: checked,- };- onUpdate({ ...settings, [eventKey]: updatedScripts });- }}+ onUpdate={(checked: boolean) => updateScriptBool(key, index, 'abortOnError', checked)}/><span>Abort on Error</span></div>+ {showRootOption && (+ <div className={classes.scriptOptionCheckbox}>+ <Toggle+ fieldValue={script?.runAsRoot || false}+ inline={true}+ onUpdate={(checked: boolean) => updateScriptBool(key, index, 'runAsRoot', checked)}+ />+ <span>Run as Root</span>+ </div>+ )}<i className="pipe">|</i><divtitle="Timeout Settings"diff --git a/installers/linux-server/install.sh b/installers/linux-server/install.shindex 7fa6479..5605a9a 100644--- a/installers/linux-server/install.sh+++ b/installers/linux-server/install.sh@@ -25,6 +25,7 @@ GITHUB_RELEASES_URL="https://github.com/${GITHUB_REPO}/releases"# CDN base URL (for installer scripts only)CDN_BASE_URL="https://dl.usepluton.com/server"+HELPER_BASE_URL="https://dl.usepluton.com/deps/pluton-helper/linux-helper"# Installation pathsINSTALL_DIR="/opt/pluton"@@ -32,6 +33,10 @@ DATA_DIR="/var/lib/pluton"CONFIG_DIR="/etc/pluton"SERVICE_FILE="/etc/systemd/system/pluton.service"ENV_FILE="${CONFIG_DIR}/pluton.env"+ENC_ENV_FILE="${CONFIG_DIR}/pluton.enc.env"+HELPER_PATH="/usr/bin/pluton-helper"+PLUTON_USER="pluton"+PLUTON_GROUP="pluton"# Temp directory for downloadsTMP_DIR=$(mktemp -d)@@ -147,7 +152,7 @@ parse_args() {check_dependencies() {local missing=()- for cmd in curl tar; do+ for cmd in curl tar setcap; doif ! command -v $cmd &> /dev/null; thenmissing+=($cmd)fi@@ -178,6 +183,105 @@ detect_architecture() {esac}+helper_url_for_arch() {+ local arch="$1"+ case "$arch" in+ x64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ arm64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ *)+ echo -e "${RED}Error: Unsupported helper architecture: $arch${NC}" >&2+ exit 1+ ;;+ esac+}++create_pluton_user() {+ echo " Ensuring ${PLUTON_USER} system user exists..."++ if ! getent group "${PLUTON_GROUP}" >/dev/null 2>&1; then+ groupadd --system "${PLUTON_GROUP}"+ fi++ if ! id -u "${PLUTON_USER}" >/dev/null 2>&1; then+ useradd --system --gid "${PLUTON_GROUP}" --home-dir "${DATA_DIR}" --shell /usr/sbin/nologin "${PLUTON_USER}"+ fi+}++ensure_runtime_ownership() {+ echo " Setting runtime directory ownership..."++ mkdir -p "${DATA_DIR}"/{config,db,logs,progress,stats,sync,cache,cache/restic,downloads,restores,rescue,backups}+ mkdir -p "${CONFIG_DIR}"++ chown -R "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 700 "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 700 "${DATA_DIR}/config"+ chmod 755 "${DATA_DIR}/logs" "${DATA_DIR}/progress" "${DATA_DIR}/stats" "${DATA_DIR}/sync" "${DATA_DIR}/cache" "${DATA_DIR}/cache/restic" "${DATA_DIR}/downloads" "${DATA_DIR}/restores" "${DATA_DIR}/rescue" "${DATA_DIR}/backups"+}++install_pluton_helper() {+ local arch="$1"+ local helper_url+ helper_url=$(helper_url_for_arch "$arch")+ local helper_tmp="${TMP_DIR}/pluton-helper-${arch}"++ echo " Installing pluton-helper from ${helper_url}..."+ if ! curl -fSL --progress-bar -o "${helper_tmp}" "${helper_url}"; then+ echo -e "${RED}Error: Failed to download pluton-helper from ${helper_url}${NC}"+ exit 1+ fi++ install -o root -g "${PLUTON_GROUP}" -m 750 "${helper_tmp}" "${HELPER_PATH}"+ setcap cap_dac_override,cap_chown,cap_fowner+ep "${HELPER_PATH}"++ if ! getcap "${HELPER_PATH}" | grep -q 'cap_chown,cap_dac_override,cap_fowner=ep'; then+ echo -e "${RED}Error: Failed to apply required capabilities to ${HELPER_PATH}${NC}"+ exit 1+ fi++ if ! "${HELPER_PATH}" version >/dev/null 2>&1; then+ echo -e "${RED}Error: ${HELPER_PATH} failed version verification${NC}"+ exit 1+ fi+}++create_tool_wrappers() {+ local arch="$1"+ local platform_id="linux-${arch}"+ local restic_bin="${INSTALL_DIR}/binaries/${platform_id}/restic"+ local rclone_bin="${INSTALL_DIR}/binaries/${platform_id}/rclone"+ local rclone_config="${DATA_DIR}/config/rclone.conf"+ local system_bin_dir="/usr/local/bin"++ echo " Creating system-wide wrappers 'prclone' and 'prestic'..."++ if [ ! -x "${restic_bin}" ] || [ ! -x "${rclone_bin}" ]; then+ echo -e "${YELLOW}Warning: Bundled restic/rclone binaries were not found for ${platform_id}; skipping wrappers.${NC}"+ return 0+ fi++ mkdir -p "${system_bin_dir}"++ cat > "${system_bin_dir}/prclone" << EOF+#!/bin/sh+# Pluton Wrapper for rclone+exec "${rclone_bin}" --config "${rclone_config}" "\$@"+EOF++ cat > "${system_bin_dir}/prestic" << EOF+#!/bin/sh+# Pluton Wrapper for restic+export RCLONE_CONFIG="${rclone_config}"+exec "${restic_bin}" -o rclone.program="${rclone_bin}" "\$@"+EOF++ chmod +x "${system_bin_dir}/prclone" "${system_bin_dir}/prestic"+}+# Check for root privilegescheck_root() {if [ "$EUID" -ne 0 ]; then@@ -236,14 +340,20 @@ load_existing_credentials() {fi# Read encryption key from /etc/pluton/pluton.enc.env (current location)- local enc_env_file="${CONFIG_DIR}/pluton.enc.env"- if [ -f "${enc_env_file}" ]; then- echo -e "${GREEN}Loading encryption key from: ${enc_env_file}${NC}"+ if [ -f "${ENC_ENV_FILE}" ]; then+ echo -e "${GREEN}Loading encryption key from: ${ENC_ENV_FILE}${NC}"while IFS='=' read -r key value; docase "$key" in '#'*|'') continue;; esackey=$(echo "$key" | xargs)[ "$key" = "PLUTON_ENCRYPTION_KEY" ] && CLI_ENCRYPTION_KEY="$value"- done < "${enc_env_file}"+ done < "${ENC_ENV_FILE}"+ elif [ -f "${DATA_DIR}/pluton.enc.env" ]; then+ echo -e "${GREEN}Loading legacy encryption key from: ${DATA_DIR}/pluton.enc.env${NC}"+ while IFS='=' read -r key value; do+ case "$key" in '#'*|'') continue;; esac+ key=$(echo "$key" | xargs)+ [ "$key" = "PLUTON_ENCRYPTION_KEY" ] || [ "$key" = "ENCRYPTION_KEY" ] && CLI_ENCRYPTION_KEY="$value"+ done < "${DATA_DIR}/pluton.enc.env"fiif [ -f "${DATA_DIR}/config/config.json" ]; then@@ -448,20 +558,7 @@ install_files() {mkdir -p "${INSTALL_DIR}/node_modules"mkdir -p "${INSTALL_DIR}/drizzle"- echo " Creating data directory: ${DATA_DIR}"- mkdir -p "${DATA_DIR}/config"- mkdir -p "${DATA_DIR}/db"- mkdir -p "${DATA_DIR}/logs"- mkdir -p "${DATA_DIR}/backups"- mkdir -p "${DATA_DIR}/progress"- mkdir -p "${DATA_DIR}/rescue"- mkdir -p "${DATA_DIR}/restore"- mkdir -p "${DATA_DIR}/stats"- mkdir -p "${DATA_DIR}/sync"-- echo " Creating config directory: ${CONFIG_DIR}"- mkdir -p "${CONFIG_DIR}"- chmod 700 "${CONFIG_DIR}"+ ensure_runtime_ownership# Copy executableecho " Copying executable..."@@ -486,6 +583,13 @@ install_files() {if [ -d "${source_dir}/drizzle" ]; thencp -r "${source_dir}/drizzle"/* "${INSTALL_DIR}/drizzle/"fi++ chown -R root:root "${INSTALL_DIR}"+ chmod 755 "${INSTALL_DIR}"+ find "${INSTALL_DIR}" -type d -exec chmod 755 {} \;+ find "${INSTALL_DIR}" -type f -exec chmod 644 {} \;+ chmod 755 "${INSTALL_DIR}/pluton"+ find "${INSTALL_DIR}/binaries" -type f -exec chmod 755 {} \; 2>/dev/null || true# Copy documentation[ -f "${source_dir}/LICENSE" ] && cp "${source_dir}/LICENSE" "${INSTALL_DIR}/" || true@@ -504,28 +608,28 @@ write_configuration() {printf 'PLUTON_USER_NAME=%s\n' "${CLI_USER_NAME}"printf 'PLUTON_USER_PASSWORD=%s\n' "${CLI_USER_PASSWORD}"} > "${ENV_FILE}"+ chown "${PLUTON_USER}:${PLUTON_GROUP}" "${ENV_FILE}"chmod 600 "${ENV_FILE}"# Write encryption key to config directory (created once, never overwritten)- local enc_env_file="${CONFIG_DIR}/pluton.enc.env"- if [ ! -f "${enc_env_file}" ]; then- echo " Writing encryption key to ${enc_env_file}..."+ if [ ! -f "${ENC_ENV_FILE}" ] && [ -f "${DATA_DIR}/pluton.enc.env" ]; then+ echo " Migrating legacy encryption key to ${ENC_ENV_FILE}..."+ mv "${DATA_DIR}/pluton.enc.env" "${ENC_ENV_FILE}"+ fi++ if [ ! -f "${ENC_ENV_FILE}" ]; then+ echo " Writing encryption key to ${ENC_ENV_FILE}..."{printf '# %s Encryption Key — DO NOT SHARE\n' "${PRODUCT_NAME}"printf '# This file is created once and never overwritten by the installer.\n'printf '# Generated by installer on %s\n' "$(date)"printf 'PLUTON_ENCRYPTION_KEY=%s\n' "${CLI_ENCRYPTION_KEY}"- } > "${enc_env_file}"- chmod 600 "${enc_env_file}"+ } > "${ENC_ENV_FILE}"else- echo " Encryption key file already exists at ${enc_env_file} (preserved)"- fi-- # Clean up legacy encryption key file from data directory- if [ -f "${DATA_DIR}/pluton.enc.env" ]; then- rm -f "${DATA_DIR}/pluton.enc.env"- echo " Removed legacy encryption key file from ${DATA_DIR}/pluton.enc.env"+ echo " Encryption key file already exists at ${ENC_ENV_FILE} (preserved)"fi+ chown "${PLUTON_USER}:${PLUTON_GROUP}" "${ENC_ENV_FILE}"+ chmod 600 "${ENC_ENV_FILE}"local config_json="${DATA_DIR}/config/config.json"if [ ! -f "$config_json" ] || [ "$CLI_UPGRADE" = false ]; then@@ -539,6 +643,8 @@ EOFelseecho " Preserving existing configuration at ${config_json}"fi+ chown -R "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 600 "${ENV_FILE}" "${ENC_ENV_FILE}"}# Install systemd service@@ -554,11 +660,14 @@ After=network.targetType=simpleExecStart=${INSTALL_DIR}/plutonWorkingDirectory=${DATA_DIR}-User=root+User=${PLUTON_USER}+Group=${PLUTON_GROUP}Restart=on-failureRestartSec=5StandardOutput=append:${DATA_DIR}/logs/stdout.logStandardError=append:${DATA_DIR}/logs/stderr.log+CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_CHOWN CAP_FOWNER CAP_SETUID CAP_SETGID+AmbientCapabilities=CAP_DAC_READ_SEARCH# Load sensitive credentials from environment filesEnvironmentFile=${ENV_FILE}@@ -624,11 +733,14 @@ if [ "$NON_INTERACTIVE" = false ] && [ "$REMOVE_DATA" = false ]; thenfirm -rf "${INSTALL_DIR}"+rm -f "/usr/bin/pluton-helper"+rm -f /usr/local/bin/prclone /usr/local/bin/presticrm -rf "${CONFIG_DIR}"[ "$REMOVE_DATA" = true ] && rm -rf "${DATA_DIR}"echo -e "${GREEN}Pluton uninstalled successfully!${NC}"[ "$REMOVE_DATA" = false ] && echo "Data preserved at: ${DATA_DIR}"+echo "System user 'pluton' was preserved."UNINSTALL_EOFchmod +x "${INSTALL_DIR}/uninstall.sh"@@ -747,7 +859,10 @@ main() {echo ""download_files "$arch" "$CLI_VERSION"+ create_pluton_userinstall_files "$arch"+ create_tool_wrappers "$arch"+ install_pluton_helper "$arch"write_configurationinstall_servicediff --git a/installers/linux-server/install_dev.sh b/installers/linux-server/install_dev.shnew file mode 100644index 0000000..d5982ee--- /dev/null+++ b/installers/linux-server/install_dev.sh@@ -0,0 +1,886 @@+#!/bin/bash+# Pluton Server Remote Installation Script for local dev archives+# Installs Pluton from a locally available tar.gz archive+# Usage: sudo bash install_dev.sh --archive-path /path/to/pluton-linux-x64.tar.gz+#+# For non-interactive install:+# sudo bash install_dev.sh \+# --archive-path /path/to/pluton-linux-x64.tar.gz \+# --port 5173 --encryption-key "key" --user admin --password "pass" --non-interactive++set -e++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[38;2;5;109;255m'+NC='\033[0m' # No Color++# Product name+PRODUCT_NAME="Pluton"++# CDN base URL+CDN_BASE_URL="https://dl.usepluton.com/server"+HELPER_BASE_URL="https://dl.usepluton.com/deps/pluton-helper/linux-helper"++# Installation paths+INSTALL_DIR="/opt/pluton"+DATA_DIR="/var/lib/pluton"+CONFIG_DIR="/etc/pluton"+SERVICE_FILE="/etc/systemd/system/pluton.service"+ENV_FILE="${CONFIG_DIR}/pluton.env"+ENC_ENV_FILE="${CONFIG_DIR}/pluton.enc.env"+HELPER_PATH="/usr/bin/pluton-helper"+PLUTON_USER="pluton"+PLUTON_GROUP="pluton"++# Temp directory for downloads+TMP_DIR=$(mktemp -d)+trap "rm -rf ${TMP_DIR}" EXIT++# Default configuration+DEFAULT_PORT=5173+DEFAULT_MAX_CONCURRENT=2++# CLI argument variables+CLI_ARCHIVE_PATH=""+CLI_PORT=""+CLI_MAX_CONCURRENT=""+CLI_ENCRYPTION_KEY=""+CLI_USER_NAME=""+CLI_USER_PASSWORD=""+CLI_CONFIG_FILE=""+CLI_UPGRADE=false+CLI_NON_INTERACTIVE=false++# Extracted archive directory+EXTRACTED_SOURCE_DIR=""++# Print banner+print_banner() {+ echo -e "${BLUE}"+ echo "╔═══════════════════════════════════════════════════════════╗"+ echo "║ ☄️ ${PRODUCT_NAME} Backup Service - Dev Installer ║"+ echo "╚═══════════════════════════════════════════════════════════╝"+ echo -e "${NC}"+}++# Print usage+print_usage() {+ echo "Usage: sudo bash install_dev.sh [OPTIONS]"+ echo ""+ echo "Options:"+ echo " --archive-path <path> Local path to Pluton dev tar.gz archive"+ echo " --port <port> Server port (default: 5173)"+ echo " --max-concurrent <num> Max concurrent backups (default: 2)"+ echo " --encryption-key <key> Encryption key for backups (min 12 chars)"+ echo " --user <username> Admin username"+ echo " --password <password> Admin password"+ echo " --config <file> Path to .env config file"+ echo " --upgrade Upgrade existing installation (preserve data)"+ echo " --non-interactive Run without prompts (requires all credentials)"+ echo " --help Show this help message"+ echo ""+ echo "Examples:"+ echo " Interactive install:"+ echo " sudo bash install_dev.sh --archive-path /tmp/pluton-linux-x64.tar.gz"+ echo ""+ echo " Non-interactive install:"+ echo " sudo bash install_dev.sh \\"+ echo " --archive-path /tmp/pluton-linux-x64.tar.gz \\"+ echo " --port 5173 --encryption-key 'mysecretkey123' \\"+ echo " --user admin --password 'mypassword' --non-interactive"+ echo ""+ echo " Upgrade existing installation:"+ echo " sudo bash install_dev.sh --archive-path /tmp/pluton-linux-x64.tar.gz --upgrade"+}++# Parse command line arguments+parse_args() {+ while [[ $# -gt 0 ]]; do+ case $1 in+ --archive-path)+ CLI_ARCHIVE_PATH="$2"+ shift 2+ ;;+ --port)+ CLI_PORT="$2"+ shift 2+ ;;+ --max-concurrent)+ CLI_MAX_CONCURRENT="$2"+ shift 2+ ;;+ --encryption-key)+ CLI_ENCRYPTION_KEY="$2"+ shift 2+ ;;+ --user)+ CLI_USER_NAME="$2"+ shift 2+ ;;+ --password)+ CLI_USER_PASSWORD="$2"+ shift 2+ ;;+ --config)+ CLI_CONFIG_FILE="$2"+ shift 2+ ;;+ --upgrade)+ CLI_UPGRADE=true+ shift+ ;;+ --non-interactive)+ CLI_NON_INTERACTIVE=true+ shift+ ;;+ --help)+ print_usage+ exit 0+ ;;+ *)+ echo -e "${RED}Error: Unknown option: $1${NC}"+ print_usage+ exit 1+ ;;+ esac+ done+}++# Check for required commands+check_dependencies() {+ local missing=()++ for cmd in curl tar setcap; do+ if ! command -v $cmd &> /dev/null; then+ missing+=($cmd)+ fi+ done++ if [ ${#missing[@]} -gt 0 ]; then+ echo -e "${RED}Error: Missing required commands: ${missing[*]}${NC}"+ echo "Please install them and try again."+ exit 1+ fi+}++# Detect system architecture+detect_architecture() {+ local arch=$(uname -m)+ case $arch in+ x86_64|amd64)+ echo "x64"+ ;;+ aarch64|arm64)+ echo "arm64"+ ;;+ *)+ echo -e "${RED}Error: Unsupported architecture: $arch${NC}" >&2+ echo "${PRODUCT_NAME} supports x86_64 (amd64) and aarch64 (arm64) architectures." >&2+ exit 1+ ;;+ esac+}++helper_url_for_arch() {+ local arch="$1"+ case "$arch" in+ x64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ arm64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ *)+ echo -e "${RED}Error: Unsupported helper architecture: $arch${NC}" >&2+ exit 1+ ;;+ esac+}++create_pluton_user() {+ echo " Ensuring ${PLUTON_USER} system user exists..."++ if ! getent group "${PLUTON_GROUP}" >/dev/null 2>&1; then+ groupadd --system "${PLUTON_GROUP}"+ fi++ if ! id -u "${PLUTON_USER}" >/dev/null 2>&1; then+ useradd --system --gid "${PLUTON_GROUP}" --home-dir "${DATA_DIR}" --shell /usr/sbin/nologin "${PLUTON_USER}"+ fi+}++ensure_runtime_ownership() {+ echo " Setting runtime directory ownership..."++ mkdir -p "${DATA_DIR}"/{config,db,logs,progress,stats,sync,cache,cache/restic,downloads,restores,rescue,backups}+ mkdir -p "${CONFIG_DIR}"++ chown -R "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 700 "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 700 "${DATA_DIR}/config"+ chmod 755 "${DATA_DIR}/logs" "${DATA_DIR}/progress" "${DATA_DIR}/stats" "${DATA_DIR}/sync" "${DATA_DIR}/cache" "${DATA_DIR}/cache/restic" "${DATA_DIR}/downloads" "${DATA_DIR}/restores" "${DATA_DIR}/rescue" "${DATA_DIR}/backups"+}++install_pluton_helper() {+ local arch="$1"+ local helper_url+ helper_url=$(helper_url_for_arch "$arch")+ local helper_tmp="${TMP_DIR}/pluton-helper-${arch}"++ echo " Installing pluton-helper from ${helper_url}..."+ if ! curl -fSL --progress-bar -o "${helper_tmp}" "${helper_url}"; then+ echo -e "${RED}Error: Failed to download pluton-helper from ${helper_url}${NC}"+ exit 1+ fi++ install -o root -g "${PLUTON_GROUP}" -m 750 "${helper_tmp}" "${HELPER_PATH}"+ setcap cap_dac_override,cap_chown,cap_fowner+ep "${HELPER_PATH}"++ if ! getcap "${HELPER_PATH}" | grep -q 'cap_chown,cap_dac_override,cap_fowner=ep'; then+ echo -e "${RED}Error: Failed to apply required capabilities to ${HELPER_PATH}${NC}"+ exit 1+ fi++ if ! "${HELPER_PATH}" version >/dev/null 2>&1; then+ echo -e "${RED}Error: ${HELPER_PATH} failed version verification${NC}"+ exit 1+ fi+}++create_tool_wrappers() {+ local arch="$1"+ local platform_id="linux-${arch}"+ local restic_bin="${INSTALL_DIR}/binaries/${platform_id}/restic"+ local rclone_bin="${INSTALL_DIR}/binaries/${platform_id}/rclone"+ local rclone_config="${DATA_DIR}/config/rclone.conf"+ local system_bin_dir="/usr/local/bin"++ echo " Creating system-wide wrappers 'prclone' and 'prestic'..."++ if [ ! -x "${restic_bin}" ] || [ ! -x "${rclone_bin}" ]; then+ echo -e "${YELLOW}Warning: Bundled restic/rclone binaries were not found for ${platform_id}; skipping wrappers.${NC}"+ return 0+ fi++ mkdir -p "${system_bin_dir}"++ cat > "${system_bin_dir}/prclone" << EOF+#!/bin/sh+# Pluton Wrapper for rclone+exec "${rclone_bin}" --config "${rclone_config}" "\$@"+EOF++ cat > "${system_bin_dir}/prestic" << EOF+#!/bin/sh+# Pluton Wrapper for restic+export RCLONE_CONFIG="${rclone_config}"+exec "${restic_bin}" -o rclone.program="${rclone_bin}" "\$@"+EOF++ chmod +x "${system_bin_dir}/prclone" "${system_bin_dir}/prestic"+}++# Check for root privileges+check_root() {+ if [ "$EUID" -ne 0 ]; then+ echo -e "${RED}Error: This script must be run as root.${NC}"+ echo "Please run with sudo or as root user."+ exit 1+ fi+}++# Check if this is an upgrade+check_existing_installation() {+ if systemctl is-active --quiet pluton 2>/dev/null || [ -f "${ENV_FILE}" ]; then+ return 0+ fi+ return 1+}++# Load config from file+load_config_file() {+ local config_file="$1"++ if [ ! -f "$config_file" ]; then+ echo -e "${RED}Error: Config file not found: $config_file${NC}"+ exit 1+ fi++ echo -e "${GREEN}Loading configuration from: ${config_file}${NC}"++ set -a+ source "$config_file"+ set +a++ [ -n "${PLUTON_ENCRYPTION_KEY:-}" ] && CLI_ENCRYPTION_KEY="$PLUTON_ENCRYPTION_KEY"+ [ -n "${PLUTON_USER_NAME:-}" ] && CLI_USER_NAME="$PLUTON_USER_NAME"+ [ -n "${PLUTON_USER_PASSWORD:-}" ] && CLI_USER_PASSWORD="$PLUTON_USER_PASSWORD"+ [ -n "${SERVER_PORT:-}" ] && CLI_PORT="$SERVER_PORT"+ [ -n "${MAX_CONCURRENT_BACKUPS:-}" ] && CLI_MAX_CONCURRENT="$MAX_CONCURRENT_BACKUPS" || true+}++# Load existing credentials (for upgrade)+load_existing_credentials() {+ if [ -f "${ENV_FILE}" ]; then+ echo -e "${GREEN}Loading existing credentials from: ${ENV_FILE}${NC}"+ while IFS='=' read -r key value; do+ case "$key" in '#'*|'') continue;; esac+ key=$(echo "$key" | xargs)+ case "$key" in+ PLUTON_ENCRYPTION_KEY) CLI_ENCRYPTION_KEY="$value" ;;+ PLUTON_USER_NAME) CLI_USER_NAME="$value" ;;+ PLUTON_USER_PASSWORD) CLI_USER_PASSWORD="$value" ;;+ esac+ done < "${ENV_FILE}"+ fi++ if [ -f "${ENC_ENV_FILE}" ]; then+ echo -e "${GREEN}Loading encryption key from: ${ENC_ENV_FILE}${NC}"+ while IFS='=' read -r key value; do+ case "$key" in '#'*|'') continue;; esac+ key=$(echo "$key" | xargs)+ [ "$key" = "PLUTON_ENCRYPTION_KEY" ] && CLI_ENCRYPTION_KEY="$value"+ done < "${ENC_ENV_FILE}"+ elif [ -f "${DATA_DIR}/pluton.enc.env" ]; then+ echo -e "${GREEN}Loading legacy encryption key from: ${DATA_DIR}/pluton.enc.env${NC}"+ while IFS='=' read -r key value; do+ case "$key" in '#'*|'') continue;; esac+ key=$(echo "$key" | xargs)+ [ "$key" = "PLUTON_ENCRYPTION_KEY" ] || [ "$key" = "ENCRYPTION_KEY" ] && CLI_ENCRYPTION_KEY="$value"+ done < "${DATA_DIR}/pluton.enc.env"+ fi++ if [ -f "${DATA_DIR}/config/config.json" ]; then+ local port=$(grep -o '"SERVER_PORT"[[:space:]]*:[[:space:]]*[0-9]*' "${DATA_DIR}/config/config.json" 2>/dev/null | grep -o '[0-9]*' || echo "")+ local max_concurrent=$(grep -o '"MAX_CONCURRENT_BACKUPS"[[:space:]]*:[[:space:]]*[0-9]*' "${DATA_DIR}/config/config.json" 2>/dev/null | grep -o '[0-9]*' || echo "")++ [ -n "$port" ] && CLI_PORT="$port"+ [ -n "$max_concurrent" ] && CLI_MAX_CONCURRENT="$max_concurrent" || true+ fi+}++# Prompt for archive path (interactive mode)+prompt_archive_path() {+ echo -e "${BLUE}Dev Archive${NC}"+ echo "Please enter the local path to the Pluton dev archive (.tar.gz)."+ echo ""++ while [ -z "$CLI_ARCHIVE_PATH" ]; do+ printf "Archive Path: "+ read CLI_ARCHIVE_PATH < /dev/tty+ if [ -z "$CLI_ARCHIVE_PATH" ]; then+ echo -e "${RED}Error: Archive path is required.${NC}"+ fi+ done+ echo ""+}++# Prompt for configuration (interactive mode)+prompt_configuration() {+ echo -e "${BLUE}Configuration Setup${NC}"+ echo "Press Enter to accept default values."+ echo ""++ local default_port="${CLI_PORT:-$DEFAULT_PORT}"+ printf "Server Port [${default_port}]: "+ read input_port < /dev/tty+ CLI_PORT="${input_port:-$default_port}"++ if ! [[ "$CLI_PORT" =~ ^[0-9]+$ ]] || [ "$CLI_PORT" -lt 1024 ] || [ "$CLI_PORT" -gt 65535 ]; then+ echo -e "${RED}Error: Invalid port. Must be between 1024 and 65535.${NC}"+ exit 1+ fi++ local default_max="${CLI_MAX_CONCURRENT:-$DEFAULT_MAX_CONCURRENT}"+ printf "Max Concurrent Backups [${default_max}]: "+ read input_max < /dev/tty+ CLI_MAX_CONCURRENT="${input_max:-$default_max}"++ if ! [[ "$CLI_MAX_CONCURRENT" =~ ^[0-9]+$ ]] || [ "$CLI_MAX_CONCURRENT" -lt 1 ] || [ "$CLI_MAX_CONCURRENT" -gt 10 ]; then+ echo -e "${RED}Error: Invalid value. Must be between 1 and 10.${NC}"+ exit 1+ fi+}++# Prompt for credentials (interactive mode)+prompt_credentials() {+ echo ""+ echo -e "${BLUE}Security Credentials${NC}"+ echo "These credentials are required for ${PRODUCT_NAME} to function."+ echo ""++ while [ -z "$CLI_ENCRYPTION_KEY" ] || [ ${#CLI_ENCRYPTION_KEY} -lt 12 ]; do+ printf "Encryption Key (min 12 characters): "+ read CLI_ENCRYPTION_KEY < /dev/tty+ if [ ${#CLI_ENCRYPTION_KEY} -lt 12 ]; then+ echo -e "${RED}Error: Encryption key must be at least 12 characters.${NC}"+ CLI_ENCRYPTION_KEY=""+ fi+ done++ while [ -z "$CLI_USER_NAME" ]; do+ printf "Admin Username: "+ read CLI_USER_NAME < /dev/tty+ if [ -z "$CLI_USER_NAME" ]; then+ echo -e "${RED}Error: Username is required.${NC}"+ fi+ done++ while true; do+ printf "Admin Password (min 6 characters): "+ stty -echo < /dev/tty+ read CLI_USER_PASSWORD < /dev/tty+ stty echo < /dev/tty+ echo ""++ if [ -z "$CLI_USER_PASSWORD" ]; then+ echo -e "${RED}Error: Password is required.${NC}"+ continue+ fi++ if [ ${#CLI_USER_PASSWORD} -lt 6 ]; then+ echo -e "${RED}Error: Password must be at least 6 characters.${NC}"+ CLI_USER_PASSWORD=""+ continue+ fi++ printf "Confirm Admin Password: "+ stty -echo < /dev/tty+ read CLI_USER_PASSWORD_CONFIRM < /dev/tty+ stty echo < /dev/tty+ echo ""++ if [ "$CLI_USER_PASSWORD" != "$CLI_USER_PASSWORD_CONFIRM" ]; then+ echo -e "${RED}Error: Passwords do not match. Please try again.${NC}"+ CLI_USER_PASSWORD=""+ continue+ fi++ break+ done+}++# Validate archive path+validate_archive_path() {+ local errors=0++ if [ -z "$CLI_ARCHIVE_PATH" ]; then+ echo -e "${RED}Error: Archive path is required (use --archive-path).${NC}"+ errors=$((errors + 1))+ elif [ ! -f "$CLI_ARCHIVE_PATH" ]; then+ echo -e "${RED}Error: Archive file not found: ${CLI_ARCHIVE_PATH}${NC}"+ errors=$((errors + 1))+ elif [ ! -r "$CLI_ARCHIVE_PATH" ]; then+ echo -e "${RED}Error: Archive file is not readable: ${CLI_ARCHIVE_PATH}${NC}"+ errors=$((errors + 1))+ fi++ return $errors+}++# Validate all required values are set+validate_configuration() {+ local errors=0++ if ! validate_archive_path; then+ errors=$((errors + 1))+ fi++ if [ -z "$CLI_ENCRYPTION_KEY" ] || [ ${#CLI_ENCRYPTION_KEY} -lt 12 ]; then+ echo -e "${RED}Error: Encryption key is required (min 12 characters).${NC}"+ errors=$((errors + 1))+ fi++ if [ -z "$CLI_USER_NAME" ]; then+ echo -e "${RED}Error: Username is required.${NC}"+ errors=$((errors + 1))+ fi++ if [ -z "$CLI_USER_PASSWORD" ]; then+ echo -e "${RED}Error: Password is required.${NC}"+ errors=$((errors + 1))+ elif [ ${#CLI_USER_PASSWORD} -lt 6 ]; then+ echo -e "${RED}Error: Password must be at least 6 characters.${NC}"+ errors=$((errors + 1))+ fi++ if [ $errors -gt 0 ]; then+ echo ""+ echo "Use --help for usage information."+ exit 1+ fi++ CLI_PORT="${CLI_PORT:-$DEFAULT_PORT}"+ CLI_MAX_CONCURRENT="${CLI_MAX_CONCURRENT:-$DEFAULT_MAX_CONCURRENT}"+}++# Stop existing service+stop_existing_service() {+ if systemctl is-active --quiet pluton 2>/dev/null; then+ echo "Stopping existing ${PRODUCT_NAME} service..."+ systemctl stop pluton+ fi+}++# Extract files from local archive+extract_archive() {+ local arch="$1"+ local archive_path="$2"++ echo -e "${BLUE}Installing ${PRODUCT_NAME} from local dev archive...${NC}"+ echo " Archive: ${archive_path}"++ if [ ! -f "${archive_path}" ]; then+ echo -e "${RED}Error: Archive file not found: ${archive_path}${NC}"+ exit 1+ fi++ echo " Extracting..."+ if ! tar -xzf "${archive_path}" -C "${TMP_DIR}"; then+ echo -e "${RED}Error: Failed to extract archive: ${archive_path}${NC}"+ exit 1+ fi++ if [ -d "${TMP_DIR}/pluton-linux-${arch}" ]; then+ EXTRACTED_SOURCE_DIR="${TMP_DIR}/pluton-linux-${arch}"+ elif [ -d "${TMP_DIR}/pluton" ]; then+ EXTRACTED_SOURCE_DIR="${TMP_DIR}/pluton"+ else+ echo -e "${RED}Error: Unexpected archive structure${NC}"+ echo "Expected the archive to extract to pluton-linux-${arch}/ or pluton/."+ exit 1+ fi++ echo -e " ${GREEN}✓${NC} Archive extracted"+}++# Install files+install_files() {+ local source_dir="$1"++ echo -e "${BLUE}Installing ${PRODUCT_NAME}...${NC}"++ echo " Creating installation directory: ${INSTALL_DIR}"+ mkdir -p "${INSTALL_DIR}"+ mkdir -p "${INSTALL_DIR}/binaries"+ mkdir -p "${INSTALL_DIR}/node_modules"+ mkdir -p "${INSTALL_DIR}/drizzle"++ ensure_runtime_ownership++ echo " Copying executable..."+ cp "${source_dir}/pluton" "${INSTALL_DIR}/pluton"+ chmod +x "${INSTALL_DIR}/pluton"++ echo " Copying binaries..."+ if [ -d "${source_dir}/binaries" ]; then+ cp -r "${source_dir}/binaries"/* "${INSTALL_DIR}/binaries/"+ find "${INSTALL_DIR}/binaries" -type f -exec chmod +x {} \;+ fi++ echo " Copying native modules..."+ if [ -d "${source_dir}/node_modules" ]; then+ cp -r "${source_dir}/node_modules"/* "${INSTALL_DIR}/node_modules/"+ fi++ echo " Copying database migrations..."+ if [ -d "${source_dir}/drizzle" ]; then+ cp -r "${source_dir}/drizzle"/* "${INSTALL_DIR}/drizzle/"+ fi++ chown -R root:root "${INSTALL_DIR}"+ chmod 755 "${INSTALL_DIR}"+ find "${INSTALL_DIR}" -type d -exec chmod 755 {} \;+ find "${INSTALL_DIR}" -type f -exec chmod 644 {} \;+ chmod 755 "${INSTALL_DIR}/pluton"+ find "${INSTALL_DIR}/binaries" -type f -exec chmod 755 {} \; 2>/dev/null || true++ [ -f "${source_dir}/LICENSE" ] && cp "${source_dir}/LICENSE" "${INSTALL_DIR}/" || true+ [ -f "${source_dir}/README.md" ] && cp "${source_dir}/README.md" "${INSTALL_DIR}/" || true+}++# Write configuration files+write_configuration() {+ echo " Writing credentials to ${ENV_FILE}..."+ {+ printf '# %s Server Credentials\n' "${PRODUCT_NAME}"+ printf '# Generated by installer on %s\n' "$(date)"+ printf '# WARNING: This file contains sensitive credentials. Keep it secure.\n\n'+ printf 'PLUTON_USER_NAME=%s\n' "${CLI_USER_NAME}"+ printf 'PLUTON_USER_PASSWORD=%s\n' "${CLI_USER_PASSWORD}"+ } > "${ENV_FILE}"+ chown "${PLUTON_USER}:${PLUTON_GROUP}" "${ENV_FILE}"+ chmod 600 "${ENV_FILE}"++ if [ ! -f "${ENC_ENV_FILE}" ] && [ -f "${DATA_DIR}/pluton.enc.env" ]; then+ echo " Migrating legacy encryption key to ${ENC_ENV_FILE}..."+ mv "${DATA_DIR}/pluton.enc.env" "${ENC_ENV_FILE}"+ fi++ if [ ! -f "${ENC_ENV_FILE}" ]; then+ echo " Writing encryption key to ${ENC_ENV_FILE}..."+ {+ printf '# %s Encryption Key - DO NOT SHARE\n' "${PRODUCT_NAME}"+ printf '# This file is created once and never overwritten by the installer.\n'+ printf '# Generated by installer on %s\n' "$(date)"+ printf 'PLUTON_ENCRYPTION_KEY=%s\n' "${CLI_ENCRYPTION_KEY}"+ } > "${ENC_ENV_FILE}"+ else+ echo " Encryption key file already exists at ${ENC_ENV_FILE} (preserved)"+ fi+ chown "${PLUTON_USER}:${PLUTON_GROUP}" "${ENC_ENV_FILE}"+ chmod 600 "${ENC_ENV_FILE}"++ local config_json="${DATA_DIR}/config/config.json"+ if [ ! -f "$config_json" ] || [ "$CLI_UPGRADE" = false ]; then+ echo " Writing configuration to ${config_json}..."+ cat > "${config_json}" << EOF+{+ "SERVER_PORT": ${CLI_PORT},+ "MAX_CONCURRENT_BACKUPS": ${CLI_MAX_CONCURRENT}+}+EOF+ else+ echo " Preserving existing configuration at ${config_json}"+ fi+ chown -R "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 600 "${ENV_FILE}" "${ENC_ENV_FILE}"+}++# Install systemd service+install_service() {+ echo " Creating systemd service..."++ cat > "${SERVICE_FILE}" << EOF+[Unit]+Description=${PRODUCT_NAME} Backup Service+After=network.target++[Service]+Type=simple+ExecStart=${INSTALL_DIR}/pluton+WorkingDirectory=${DATA_DIR}+User=${PLUTON_USER}+Group=${PLUTON_GROUP}+Restart=on-failure+RestartSec=5+StandardOutput=append:${DATA_DIR}/logs/stdout.log+StandardError=append:${DATA_DIR}/logs/stderr.log+CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_CHOWN CAP_FOWNER CAP_SETUID CAP_SETGID+AmbientCapabilities=CAP_DAC_READ_SEARCH++# Load sensitive credentials from environment files+EnvironmentFile=${ENV_FILE}+EnvironmentFile=${CONFIG_DIR}/pluton.enc.env++# Non-sensitive environment variables+Environment="PLUTON_DATA_DIR=${DATA_DIR}"+Environment="NODE_ENV=production"++[Install]+WantedBy=multi-user.target+EOF++ echo " Installing uninstall script..."+ curl -fsSL -o "${INSTALL_DIR}/uninstall.sh" "${CDN_BASE_URL}/scripts/uninstall.sh" 2>/dev/null || \+ cat > "${INSTALL_DIR}/uninstall.sh" << 'UNINSTALL_EOF'+#!/bin/bash+# Pluton Server Uninstallation Script+set -e+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m'++INSTALL_DIR="/opt/pluton"+DATA_DIR="/var/lib/pluton"+CONFIG_DIR="/etc/pluton"+SERVICE_FILE="/etc/systemd/system/pluton.service"++REMOVE_DATA=false+NON_INTERACTIVE=false++while [[ $# -gt 0 ]]; do+ case $1 in+ --remove-data) REMOVE_DATA=true; shift ;;+ --non-interactive) NON_INTERACTIVE=true; shift ;;+ --help) echo "Usage: $0 [--remove-data] [--non-interactive]"; exit 0 ;;+ *) shift ;;+ esac+done++if [ "$EUID" -ne 0 ]; then+ echo -e "${RED}Error: This script must be run as root.${NC}"+ exit 1+fi++echo -e "${BLUE}Uninstalling Pluton...${NC}"++if [ -f "${SERVICE_FILE}" ]; then+ systemctl stop pluton 2>/dev/null || true+ systemctl disable pluton 2>/dev/null || true+ rm -f "${SERVICE_FILE}"+ systemctl daemon-reload+fi++if [ "$NON_INTERACTIVE" = false ] && [ "$REMOVE_DATA" = false ]; then+ printf "Remove all data (database, logs, backups)? [y/N] "+ read -n 1 REPLY < /dev/tty+ echo+ [[ $REPLY =~ ^[Yy]$ ]] && REMOVE_DATA=true+fi++rm -rf "${INSTALL_DIR}"+rm -f "/usr/bin/pluton-helper"+rm -f /usr/local/bin/prclone /usr/local/bin/prestic+rm -rf "${CONFIG_DIR}"+[ "$REMOVE_DATA" = true ] && rm -rf "${DATA_DIR}"++echo -e "${GREEN}Pluton uninstalled successfully!${NC}"+[ "$REMOVE_DATA" = false ] && echo "Data preserved at: ${DATA_DIR}"+echo "System user 'pluton' was preserved."+UNINSTALL_EOF+ chmod +x "${INSTALL_DIR}/uninstall.sh"++ echo " Enabling service..."+ systemctl daemon-reload+ systemctl enable pluton+}++# Start service and verify+start_service() {+ echo " Starting service..."+ systemctl start pluton+ sleep 3++ if systemctl is-active --quiet pluton; then+ return 0+ else+ return 1+ fi+}++# Print success message+print_success() {+ local install_type="$1"++ echo ""+ echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"+ if [ "$install_type" = "upgrade" ]; then+ echo -e "${GREEN}║ ${PRODUCT_NAME} upgraded successfully! ║${NC}"+ else+ echo -e "${GREEN}║ ${PRODUCT_NAME} installed successfully! ║${NC}"+ fi+ echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"+ echo ""+ echo -e " ${BLUE}Access ${PRODUCT_NAME} at:${NC} http://localhost:${CLI_PORT}"+ echo ""+ echo -e " ${BLUE}Service commands:${NC}"+ echo " sudo systemctl status pluton - Check status"+ echo " sudo systemctl stop pluton - Stop service"+ echo " sudo systemctl start pluton - Start service"+ echo " sudo systemctl restart pluton - Restart service"+ echo ""+ echo -e " ${BLUE}Logs:${NC}"+ echo " ${DATA_DIR}/logs/stdout.log"+ echo " ${DATA_DIR}/logs/stderr.log"+ echo " sudo journalctl -u pluton -f"+ echo ""+ echo -e " ${BLUE}Uninstall:${NC}"+ echo " sudo ${INSTALL_DIR}/uninstall.sh"+ echo ""+}++# Print failure message+print_failure() {+ echo ""+ echo -e "${RED}Warning: Service may not have started correctly.${NC}"+ echo "Check status with: sudo systemctl status pluton"+ echo "Check logs with: sudo journalctl -u pluton -f"+}++# Main installation flow+main() {+ parse_args "$@"+ print_banner+ check_root+ check_dependencies++ local arch=$(detect_architecture)+ echo -e "Detected architecture: ${GREEN}${arch}${NC}"+ echo ""++ local is_upgrade=false+ if check_existing_installation; then+ if [ "$CLI_UPGRADE" = true ]; then+ is_upgrade=true+ echo -e "${YELLOW}Upgrade mode: Preserving existing configuration and data.${NC}"+ load_existing_credentials+ else+ echo -e "${YELLOW}${PRODUCT_NAME} is already installed.${NC}"+ if [ "$CLI_NON_INTERACTIVE" = true ]; then+ echo "Use --upgrade flag to upgrade existing installation."+ exit 1+ fi+ printf "Do you want to reinstall? This will stop the current service. [y/N] "+ read -n 1 REPLY < /dev/tty+ echo+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then+ echo "Installation cancelled."+ exit 0+ fi+ fi+ stop_existing_service+ fi++ if [ -n "$CLI_CONFIG_FILE" ]; then+ load_config_file "$CLI_CONFIG_FILE"+ fi++ if [ "$CLI_NON_INTERACTIVE" = true ]; then+ validate_configuration+ else+ if [ -z "$CLI_ARCHIVE_PATH" ]; then+ prompt_archive_path+ fi++ if [ "$is_upgrade" = false ]; then+ prompt_configuration+ if [ -z "$CLI_ENCRYPTION_KEY" ] || [ -z "$CLI_USER_NAME" ] || [ -z "$CLI_USER_PASSWORD" ]; then+ prompt_credentials+ fi+ else+ if [ -z "$CLI_ENCRYPTION_KEY" ] || [ -z "$CLI_USER_NAME" ] || [ -z "$CLI_USER_PASSWORD" ]; then+ echo -e "${YELLOW}Existing credentials not found. Please enter new credentials:${NC}"+ prompt_credentials+ fi+ fi+ validate_configuration+ fi++ echo ""++ extract_archive "$arch" "$CLI_ARCHIVE_PATH"+ create_pluton_user+ install_files "$EXTRACTED_SOURCE_DIR"+ create_tool_wrappers "$arch"+ install_pluton_helper "$arch"+ write_configuration+ install_service++ if start_service; then+ if [ "$is_upgrade" = true ]; then+ print_success "upgrade"+ else+ print_success "install"+ fi+ else+ print_failure+ fi+}++main "$@"\ No newline at end of filediff --git a/installers/linux-server/pluton.service.template b/installers/linux-server/pluton.service.templateindex 3bd5486..285daef 100644--- a/installers/linux-server/pluton.service.template+++ b/installers/linux-server/pluton.service.template@@ -6,11 +6,14 @@ After=network.targetType=simpleExecStart=/opt/pluton/plutonWorkingDirectory=/var/lib/pluton-User=root+User=pluton+Group=plutonRestart=on-failureRestartSec=5StandardOutput=append:/var/lib/pluton/logs/stdout.logStandardError=append:/var/lib/pluton/logs/stderr.log+CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_CHOWN CAP_FOWNER CAP_SETUID CAP_SETGID+AmbientCapabilities=CAP_DAC_READ_SEARCH# Load sensitive credentials from environment filesEnvironmentFile=/etc/pluton/pluton.envdiff --git a/installers/linux-server/uninstall.sh b/installers/linux-server/uninstall.shindex c185a3a..1bdc951 100644--- a/installers/linux-server/uninstall.sh+++ b/installers/linux-server/uninstall.sh@@ -23,6 +23,7 @@ DATA_DIR="/var/lib/pluton"CONFIG_DIR="/etc/pluton"SERVICE_FILE="/etc/systemd/system/pluton.service"ENV_FILE="${CONFIG_DIR}/pluton.env"+HELPER_PATH="/usr/bin/pluton-helper"# CLI argument variablesREMOVE_DATA=false@@ -144,6 +145,14 @@ main() {echo "Removing installation directory: ${INSTALL_DIR}"rm -rf "${INSTALL_DIR}"fi++ if [ -f "${HELPER_PATH}" ]; then+ echo "Removing helper binary: ${HELPER_PATH}"+ rm -f "${HELPER_PATH}"+ fi++ echo "Removing wrapper commands..."+ rm -f /usr/local/bin/prclone /usr/local/bin/prestic# Remove credentials directoryif [ -d "${CONFIG_DIR}" ]; then@@ -171,6 +180,7 @@ main() {echo -e "${BLUE}Note:${NC} Your data has been preserved at: ${DATA_DIR}"echo "To completely remove all data, run: sudo rm -rf ${DATA_DIR}"fi+ echo "System user 'pluton' was preserved."echo ""}diff --git a/installers/linux/AppDir/pluton.desktop b/installers/linux/AppDir/pluton.desktopindex d0bb38e..cfb4591 100644--- a/installers/linux/AppDir/pluton.desktop+++ b/installers/linux/AppDir/pluton.desktop@@ -7,4 +7,4 @@ Type=ApplicationCategories=Utility;Terminal=falseStartupNotify=true-X-AppImage-Version=0.13.0+X-AppImage-Version=0.14.0diff --git a/installers/linux/AppDir/usr/share/pluton/install.sh b/installers/linux/AppDir/usr/share/pluton/install.shindex 5238697..eb702d3 100644--- a/installers/linux/AppDir/usr/share/pluton/install.sh+++ b/installers/linux/AppDir/usr/share/pluton/install.sh@@ -1,6 +1,6 @@#!/bin/bash# Pluton Installation Script-# Installs Pluton as a systemd service running with root privileges+# Installs Pluton as a systemd service running as the pluton system userset -e@@ -14,7 +14,14 @@ NC='\033[0m' # No Color# Installation pathsINSTALL_DIR="/opt/pluton"DATA_DIR="/var/lib/pluton"+CONFIG_DIR="/etc/pluton"SERVICE_FILE="/etc/systemd/system/pluton.service"+ENV_FILE="${CONFIG_DIR}/pluton.env"+ENC_ENV_FILE="${CONFIG_DIR}/pluton.enc.env"+HELPER_BASE_URL="https://dl.usepluton.com/deps/pluton-helper/linux-helper"+HELPER_PATH="/usr/bin/pluton-helper"+PLUTON_USER="pluton"+PLUTON_GROUP="pluton"# Default configurationDEFAULT_PORT=5173@@ -33,6 +40,133 @@ if [ "$EUID" -ne 0 ]; thenexit 1fi+missing=()+for cmd in curl setcap; do+ if ! command -v "$cmd" >/dev/null 2>&1; then+ missing+=("$cmd")+ fi+done++if [ ${#missing[@]} -gt 0 ]; then+ echo -e "${RED}Error: Missing required commands: ${missing[*]}${NC}"+ echo "Please install them and try again."+ exit 1+fi++detect_architecture() {+ local arch+ arch=$(uname -m)+ case "$arch" in+ x86_64|amd64)+ echo "x64"+ ;;+ aarch64|arm64)+ echo "arm64"+ ;;+ *)+ echo -e "${RED}Error: Unsupported architecture: $arch${NC}" >&2+ exit 1+ ;;+ esac+}++helper_url_for_arch() {+ local arch="$1"+ case "$arch" in+ x64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ arm64)+ echo "${HELPER_BASE_URL}-${arch}"+ ;;+ *)+ echo -e "${RED}Error: Unsupported helper architecture: $arch${NC}" >&2+ exit 1+ ;;+ esac+}++create_pluton_user() {+ echo " Ensuring ${PLUTON_USER} system user exists..."+ if ! getent group "${PLUTON_GROUP}" >/dev/null 2>&1; then+ groupadd --system "${PLUTON_GROUP}"+ fi+ if ! id -u "${PLUTON_USER}" >/dev/null 2>&1; then+ useradd --system --gid "${PLUTON_GROUP}" --home-dir "${DATA_DIR}" --shell /usr/sbin/nologin "${PLUTON_USER}"+ fi+}++ensure_runtime_ownership() {+ echo " Setting runtime directory ownership..."+ mkdir -p "${DATA_DIR}"/{config,db,logs,progress,stats,sync,cache,cache/restic,downloads,restores,rescue,backups}+ mkdir -p "${CONFIG_DIR}"+ chown -R "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}" "${CONFIG_DIR}"+ chmod 700 "${DATA_DIR}" "${CONFIG_DIR}" "${DATA_DIR}/config"+ chmod 755 "${DATA_DIR}/logs" "${DATA_DIR}/progress" "${DATA_DIR}/stats" "${DATA_DIR}/sync" "${DATA_DIR}/cache" "${DATA_DIR}/cache/restic" "${DATA_DIR}/downloads" "${DATA_DIR}/restores" "${DATA_DIR}/rescue" "${DATA_DIR}/backups"+}++install_pluton_helper() {+ local arch="$1"+ local helper_url+ helper_url=$(helper_url_for_arch "$arch")+ local helper_tmp+ helper_tmp=$(mktemp)++ echo " Installing pluton-helper from ${helper_url}..."+ if ! curl -fSL --progress-bar -o "${helper_tmp}" "${helper_url}"; then+ rm -f "${helper_tmp}"+ echo -e "${RED}Error: Failed to download pluton-helper from ${helper_url}${NC}"+ exit 1+ fi++ install -o root -g "${PLUTON_GROUP}" -m 750 "${helper_tmp}" "${HELPER_PATH}"+ rm -f "${helper_tmp}"+ setcap cap_dac_override,cap_chown,cap_fowner+ep "${HELPER_PATH}"++ if ! getcap "${HELPER_PATH}" | grep -q 'cap_chown,cap_dac_override,cap_fowner=ep'; then+ echo -e "${RED}Error: Failed to apply required capabilities to ${HELPER_PATH}${NC}"+ exit 1+ fi++ if ! "${HELPER_PATH}" version >/dev/null 2>&1; then+ echo -e "${RED}Error: ${HELPER_PATH} failed version verification${NC}"+ exit 1+ fi+}++create_tool_wrappers() {+ local arch="$1"+ local platform_id="linux-${arch}"+ local restic_bin="${INSTALL_DIR}/binaries/${platform_id}/restic"+ local rclone_bin="${INSTALL_DIR}/binaries/${platform_id}/rclone"+ local rclone_config="${DATA_DIR}/config/rclone.conf"+ local system_bin_dir="/usr/local/bin"++ echo " Creating system-wide wrappers 'prclone' and 'prestic'..."++ if [ ! -x "${restic_bin}" ] || [ ! -x "${rclone_bin}" ]; then+ echo -e "${YELLOW}Warning: Bundled restic/rclone binaries were not found for ${platform_id}; skipping wrappers.${NC}"+ return 0+ fi++ mkdir -p "${system_bin_dir}"++ cat > "${system_bin_dir}/prclone" << EOF+#!/bin/sh+# Pluton Wrapper for rclone+exec "${rclone_bin}" --config "${rclone_config}" "\$@"+EOF++ cat > "${system_bin_dir}/prestic" << EOF+#!/bin/sh+# Pluton Wrapper for restic+export RCLONE_CONFIG="${rclone_config}"+exec "${restic_bin}" -o rclone.program="${rclone_bin}" "\$@"+EOF++ chmod +x "${system_bin_dir}/prclone" "${system_bin_dir}/prestic"+}+# Get APPDIR (set by AppRun or passed as argument)if [ -z "$APPDIR" ]; thenAPPDIR="$(dirname "$(readlink -f "$0")")/.."@@ -87,6 +221,8 @@ fiecho ""echo -e "${BLUE}Installing Pluton...${NC}"+ARCH=$(detect_architecture)+create_pluton_user# Create installation directoryecho " Creating installation directory: ${INSTALL_DIR}"@@ -95,17 +231,8 @@ mkdir -p "${INSTALL_DIR}/binaries"mkdir -p "${INSTALL_DIR}/node_modules"mkdir -p "${INSTALL_DIR}/drizzle"-# Create data directory with subdirectories-echo " Creating data directory: ${DATA_DIR}"-mkdir -p "${DATA_DIR}/config"-mkdir -p "${DATA_DIR}/db"-mkdir -p "${DATA_DIR}/logs"-mkdir -p "${DATA_DIR}/backups"-mkdir -p "${DATA_DIR}/progress"-mkdir -p "${DATA_DIR}/rescue"-mkdir -p "${DATA_DIR}/restore"-mkdir -p "${DATA_DIR}/stats"-mkdir -p "${DATA_DIR}/sync"+# Create data and config directories with subdirectories+ensure_runtime_ownership# Copy executableecho " Copying executable..."@@ -131,6 +258,16 @@ if [ -d "${APPDIR}/usr/bin/drizzle" ]; thencp -r "${APPDIR}/usr/bin/drizzle"/* "${INSTALL_DIR}/drizzle/"fi+chown -R root:root "${INSTALL_DIR}"+chmod 755 "${INSTALL_DIR}"+find "${INSTALL_DIR}" -type d -exec chmod 755 {} \;+find "${INSTALL_DIR}" -type f -exec chmod 644 {} \;+chmod 755 "${INSTALL_DIR}/pluton"+find "${INSTALL_DIR}/binaries" -type f -exec chmod 755 {} \; 2>/dev/null || true++create_tool_wrappers "${ARCH}"+install_pluton_helper "${ARCH}"+# Write configuration fileecho " Writing configuration..."cat > "${DATA_DIR}/config/config.json" << EOF@@ -139,6 +276,25 @@ cat > "${DATA_DIR}/config/config.json" << EOF"MAX_CONCURRENT_BACKUPS": ${MAX_CONCURRENT_BACKUPS}}EOF+chown "${PLUTON_USER}:${PLUTON_GROUP}" "${DATA_DIR}/config/config.json"+chmod 600 "${DATA_DIR}/config/config.json"++echo " Writing environment placeholders..."+{+ printf '# Pluton credentials\n'+ printf 'PLUTON_USER_NAME=%s\n' "${PLUTON_USER_NAME:-}"+ printf 'PLUTON_USER_PASSWORD=%s\n' "${PLUTON_USER_PASSWORD:-}"+} > "${ENV_FILE}"+chmod 600 "${ENV_FILE}"++if [ ! -f "${ENC_ENV_FILE}" ]; then+ {+ printf '# Pluton Encryption Key - setup wizard may populate this file\n'+ printf 'PLUTON_ENCRYPTION_KEY=%s\n' "${PLUTON_ENCRYPTION_KEY:-}"+ } > "${ENC_ENV_FILE}"+fi+chown "${PLUTON_USER}:${PLUTON_GROUP}" "${ENV_FILE}" "${ENC_ENV_FILE}"+chmod 600 "${ENV_FILE}" "${ENC_ENV_FILE}"# Create systemd service fileecho " Creating systemd service..."@@ -151,11 +307,16 @@ After=network.targetType=simpleExecStart=${INSTALL_DIR}/plutonWorkingDirectory=${DATA_DIR}-User=root+User=${PLUTON_USER}+Group=${PLUTON_GROUP}Restart=on-failureRestartSec=5StandardOutput=append:${DATA_DIR}/logs/stdout.logStandardError=append:${DATA_DIR}/logs/stderr.log+CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_CHOWN CAP_FOWNER CAP_SETUID CAP_SETGID+AmbientCapabilities=CAP_DAC_READ_SEARCH+EnvironmentFile=${ENV_FILE}+EnvironmentFile=${ENC_ENV_FILE}Environment="PLUTON_DATA_DIR=${DATA_DIR}"Environment="NODE_ENV=production"Environment="PLUTON_LINUX_DESKTOP=true"diff --git a/installers/linux/AppDir/usr/share/pluton/pluton.service.template b/installers/linux/AppDir/usr/share/pluton/pluton.service.templateindex 5e64a2d..3597e44 100644--- a/installers/linux/AppDir/usr/share/pluton/pluton.service.template+++ b/installers/linux/AppDir/usr/share/pluton/pluton.service.template@@ -6,11 +6,16 @@ After=network.targetType=simpleExecStart=/opt/pluton/plutonWorkingDirectory=/var/lib/pluton-User=root+User=pluton+Group=plutonRestart=on-failureRestartSec=5StandardOutput=append:/var/lib/pluton/logs/stdout.logStandardError=append:/var/lib/pluton/logs/stderr.log+CapabilityBoundingSet=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_CHOWN CAP_FOWNER CAP_SETUID CAP_SETGID+AmbientCapabilities=CAP_DAC_READ_SEARCH+EnvironmentFile=/etc/pluton/pluton.env+EnvironmentFile=/etc/pluton/pluton.enc.envEnvironment="PLUTON_DATA_DIR=/var/lib/pluton"Environment="NODE_ENV=production"Environment="PLUTON_LINUX_DESKTOP=true"diff --git a/installers/linux/AppDir/usr/share/pluton/uninstall.sh b/installers/linux/AppDir/usr/share/pluton/uninstall.shindex 43f9414..2675d75 100644--- a/installers/linux/AppDir/usr/share/pluton/uninstall.sh+++ b/installers/linux/AppDir/usr/share/pluton/uninstall.sh@@ -17,6 +17,7 @@ DATA_DIR="/var/lib/pluton"SERVICE_FILE="/etc/systemd/system/pluton.service"DESKTOP_FILE="/usr/share/applications/pluton.desktop"ICON_FILE="/usr/share/icons/hicolor/256x256/apps/pluton.png"+HELPER_PATH="/usr/bin/pluton-helper"echo -e "${BLUE}"echo "╔═══════════════════════════════════════════════════════════╗"@@ -80,6 +81,14 @@ if [ -d "${INSTALL_DIR}" ]; thenrm -rf "${INSTALL_DIR}"fi+if [ -f "${HELPER_PATH}" ]; then+ echo "Removing helper binary: ${HELPER_PATH}"+ rm -f "${HELPER_PATH}"+fi++echo "Removing wrapper commands..."+rm -f /usr/local/bin/prclone /usr/local/bin/prestic+# Remove desktop shortcut and iconif [ -f "${DESKTOP_FILE}" ]; thenecho "Removing desktop shortcut..."@@ -116,5 +125,6 @@ if [ "$REMOVE_DATA" = false ]; thenecho -e "${BLUE}Note:${NC} Your data has been preserved at: ${DATA_DIR}"echo "To completely remove all data, run: sudo rm -rf ${DATA_DIR}"fi+echo "System user 'pluton' was preserved."echo ""diff --git a/package.json b/package.jsonindex ed22b4d..a7dba66 100644--- a/package.json+++ b/package.json@@ -8,7 +8,7 @@"setup:hooks": "node ./scripts/setup-git-hooks.js","build": "turbo run build","build:executables": "node ./scripts/build-executables.js",- "build:executables:local": "node ./scripts/build-executables.js --platform windows",+ "build:executables:local": "node ./scripts/build-executables.js --platform win-x64,linux-x64","build:appimage:local": "wsl -e bash -c \"cd /mnt/f/JS/apps/pluton/codebase/pluton-app/pluton/installers/linux && ./build-appimage.sh all pluton\"","build:exe:local": "node ./installers/windows/build-installer.js","dev:backend": "pnpm --filter @plutonhq/core-backend dev",