Skip to content

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

fix: resolves malicious command execution vulnerability

towfiqi2e0fb5fe7e47
diff --git a/backend/__tests__/stores/PlanStore.test.ts b/backend/__tests__/stores/PlanStore.test.ts
index e3236c2..7a1f29c 100644
--- a/backend/__tests__/stores/PlanStore.test.ts
+++ b/backend/__tests__/stores/PlanStore.test.ts
@@ -31,7 +31,7 @@ describe('PlanStore', () => {
],
settings: {
scripts: {
- onBackupStart: [{ id: 's1', command: 'echo "start"' }],
+ onBackupStart: [{ id: 's1', scriptPath: '/scripts/start.sh' }],
},
},
} as any,
@@ -85,9 +85,6 @@ describe('PlanStore', () => {
};
planStore = new PlanStore(mockDb as DatabaseType);
-
- jest.spyOn(planStore, 'decryptScripts').mockImplementation(async scripts => scripts);
- jest.spyOn(planStore, 'encryptScripts').mockImplementation(async scripts => scripts);
});
describe('getAll', () => {
@@ -128,15 +125,16 @@ describe('PlanStore', () => {
});
it('should decrypt scripts when retrieving plans', async () => {
+ // Scripts are now plain scriptPath fields (no encryption) — this test
+ // verifies plans with scripts can be retrieved without errors.
// Arrange
mockDb.query.plans.findMany.mockResolvedValue(mockPlans);
// Act
- await planStore.getAll();
+ const result = await planStore.getAll();
// Assert
- // We just need to confirm the method was called. The spy is set up in beforeEach.
- expect(planStore.decryptScripts).toHaveBeenCalledWith(mockPlans[0].settings.scripts);
+ expect(result).toBeDefined();
});
});
@@ -303,13 +301,10 @@ describe('PlanStore', () => {
expect(setPayload.id).toBeUndefined(); // Crucial check
});
- it('should encrypt scripts before updating', async () => {
- // Arrange
- const encryptSpy = jest
- .spyOn(planStore, 'encryptScripts')
- .mockResolvedValue({ onBackupStart: [{ id: 's1', command: 'encrypted-command' }] } as any);
+ it('should handle update with scripts settings', async () => {
+ // Scripts are now plain scriptPath fields (no encryption needed)
const updates = {
- settings: { scripts: { onBackupStart: [{ id: 's1', command: 'decrypted' }] } },
+ settings: { scripts: { onBackupStart: [{ id: 's1', scriptPath: '/scripts/backup.sh' }] } },
};
mockDb.update().returning.mockResolvedValue([{}]);
@@ -317,9 +312,8 @@ describe('PlanStore', () => {
await planStore.update('plan-1', updates as any);
// Assert
- expect(encryptSpy).toHaveBeenCalled();
const setPayload = mockDb.update().set.mock.calls[0][0];
- expect(setPayload.settings.scripts.onBackupStart[0].command).toBe('encrypted-command');
+ expect(setPayload.settings.scripts.onBackupStart[0].scriptPath).toBe('/scripts/backup.sh');
});
});
@@ -377,28 +371,4 @@ describe('PlanStore', () => {
});
});
- describe('encryptScripts and decryptScripts (real implementation)', () => {
- // This block ensures the original methods are restored ONLY for the test(s) inside this describe.
- beforeEach(() => {
- (planStore.encryptScripts as jest.Mock).mockRestore();
- (planStore.decryptScripts as jest.Mock).mockRestore();
- });
-
- it('should correctly encrypt and then decrypt script commands', async () => {
- // Arrange
- const originalScripts = {
- onBackupStart: [{ id: 's1', command: 'echo "hello world"' }],
- onBackupEnd: [{ id: 's2', command: '/usr/bin/my_script.sh' }],
- };
-
- // Act
- const encrypted = await planStore.encryptScripts(originalScripts as any);
- const decrypted = await planStore.decryptScripts(encrypted);
-
- // Assert
- expect(encrypted!.onBackupStart![0].command).not.toBe('echo "hello world"');
- expect(encrypted!.onBackupEnd![0].command).not.toBe('/usr/bin/my_script.sh');
- expect(decrypted).toEqual(originalScripts);
- });
- });
});
diff --git a/backend/__tests__/utils/executeUserScript.test.ts b/backend/__tests__/utils/executeUserScript.test.ts
index 770578e..ca7acf9 100644
--- a/backend/__tests__/utils/executeUserScript.test.ts
+++ b/backend/__tests__/utils/executeUserScript.test.ts
@@ -1,4 +1,7 @@
-import { EventEmitter } from 'events';
+import { EventEmitter } from 'events';
+import path from 'path';
+import fs from 'fs';
+import os from 'os';
import { PlanScript } from '../../src/types/plans';
// --- Mocks ---
@@ -6,375 +9,410 @@ import { PlanScript } from '../../src/types/plans';
const mockStdout = new EventEmitter();
const mockStderr = new EventEmitter();
const mockChild = Object.assign(new EventEmitter(), {
- stdout: mockStdout,
- stderr: mockStderr,
+stdout: mockStdout,
+stderr: mockStderr,
});
const mockSpawn = jest.fn().mockReturnValue(mockChild);
jest.mock('child_process', () => ({
- spawn: (...args: any[]) => mockSpawn(...args),
+spawn: (...args: any[]) => mockSpawn(...args),
}));
-const mockDecrypt = jest.fn((val: string) => val);
-jest.mock('cryptr', () => {
- return jest.fn().mockImplementation(() => ({
- decrypt: mockDecrypt,
- }));
-});
+jest.mock('fs', () => ({
+existsSync: jest.fn().mockReturnValue(true),
+statSync: jest.fn().mockReturnValue({ isDirectory: () => false }),
+}));
+
+jest.mock('os');
import { executeUserScript, runScriptsForEvent } from '../../src/utils/executeUserScript';
// --- Helpers ---
function buildScript(overrides: Partial<PlanScript> = {}): PlanScript {
- return {
- id: 'script-1',
- type: 'command',
- enabled: true,
- command: 'echo hello',
- logOutput: false,
- ...overrides,
- };
+return {
+id: 'script-1',
+type: 'script',
+enabled: true,
+scriptPath: '/scripts/backup.sh',
+logOutput: false,
+...overrides,
+};
}
function freshChild() {
- const stdout = new EventEmitter();
- const stderr = new EventEmitter();
- const child = Object.assign(new EventEmitter(), { stdout, stderr });
- mockSpawn.mockReturnValue(child);
- return child;
+const stdout = new EventEmitter();
+const stderr = new EventEmitter();
+const child = Object.assign(new EventEmitter(), { stdout, stderr });
+mockSpawn.mockReturnValue(child);
+return child;
}
// --- Tests ---
describe('executeUserScript', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- // Shell selection tests
- describe('shell selection', () => {
- const shellCases: { shell: string | undefined; expectedExe: string; expectedArgs: string[] }[] =
- [
- { shell: 'bash', expectedExe: 'bash', expectedArgs: ['-c', 'echo hello'] },
- { shell: '/bin/bash', expectedExe: '/bin/bash', expectedArgs: ['-c', 'echo hello'] },
- { shell: 'zsh', expectedExe: 'zsh', expectedArgs: ['-c', 'echo hello'] },
- { shell: '/bin/sh', expectedExe: '/bin/sh', expectedArgs: ['-c', 'echo hello'] },
- {
- shell: 'powershell',
- expectedExe: 'powershell.exe',
- expectedArgs: ['-NoProfile', '-NonInteractive', '-Command', 'echo hello'],
- },
- { shell: 'cmd', expectedExe: 'cmd.exe', expectedArgs: ['/c', 'echo hello'] },
- ];
-
- it.each(shellCases)(
- 'spawns $expectedExe when shell is "$shell"',
- async ({ shell, expectedExe, expectedArgs }) => {
- const child = freshChild();
- const script = buildScript({ shell });
- const promise = executeUserScript(script);
-
- child.emit('close', 0, null);
- await promise;
-
- expect(mockSpawn).toHaveBeenCalledWith(expectedExe, expectedArgs, expect.any(Object));
- }
- );
-
- it('defaults to /bin/sh when shell is not specified', async () => {
- const child = freshChild();
- const script = buildScript({ shell: undefined });
- const promise = executeUserScript(script);
-
- child.emit('close', 0, null);
- await promise;
-
- expect(mockSpawn).toHaveBeenCalledWith('/bin/sh', ['-c', 'echo hello'], expect.any(Object));
- });
- });
-
- // Success case
- it('resolves with stdout and stderr on exit code 0', async () => {
- const child = freshChild();
- const script = buildScript();
- const promise = executeUserScript(script);
-
- child.stdout.emit('data', Buffer.from('out'));
- child.stderr.emit('data', Buffer.from('err'));
- child.emit('close', 0, null);
-
- const result = await promise;
- expect(result).toEqual({ stdout: 'out', stderr: 'err' });
- });
-
- // Failure cases
- it('rejects on non-zero exit code', async () => {
- const child = freshChild();
- const script = buildScript();
- const promise = executeUserScript(script);
-
- child.stderr.emit('data', Buffer.from('bad'));
- child.emit('close', 1, null);
-
- await expect(promise).rejects.toThrow('bad');
- });
-
- it('rejects with generic message when stderr and stdout are empty and exit code is non-zero', async () => {
- const child = freshChild();
- const script = buildScript();
- const promise = executeUserScript(script);
-
- child.emit('close', 2, null);
-
- await expect(promise).rejects.toThrow('Script exited with code 2');
- });
-
- it('rejects on SIGTERM (timeout)', async () => {
- const child = freshChild();
- const script = buildScript({ timeout: 5000 });
- const promise = executeUserScript(script);
-
- child.emit('close', null, 'SIGTERM');
-
- await expect(promise).rejects.toThrow('Script timed out after 5000ms');
- });
-
- it('uses default timeout message when timeout is not set', async () => {
- const child = freshChild();
- const script = buildScript();
- const promise = executeUserScript(script);
-
- child.emit('close', null, 'SIGTERM');
-
- await expect(promise).rejects.toThrow('Script timed out after 60000ms');
- });
-
- it('rejects on spawn error', async () => {
- const child = freshChild();
- const script = buildScript();
- const promise = executeUserScript(script);
-
- child.emit('error', new Error('ENOENT'));
-
- await expect(promise).rejects.toThrow('Failed to start script process: ENOENT');
- });
+let isAbsoluteSpy: jest.SpyInstance;
+
+beforeEach(() => {
+jest.clearAllMocks();
+isAbsoluteSpy = jest.spyOn(path, 'isAbsolute').mockReturnValue(true);
+(fs.existsSync as jest.Mock).mockReturnValue(true);
+(fs.statSync as jest.Mock).mockReturnValue({ isDirectory: () => false });
+(os.platform as jest.Mock).mockReturnValue('linux');
+});
+
+afterEach(() => {
+isAbsoluteSpy.mockRestore();
+});
+
+// Path validation
+describe('path validation', () => {
+it('rejects when scriptPath is empty', async () => {
+await expect(executeUserScript(buildScript({ scriptPath: '' }))).rejects.toThrow(
+'Script path is empty.'
+);
+});
+
+it('rejects when scriptPath is whitespace', async () => {
+await expect(executeUserScript(buildScript({ scriptPath: ' ' }))).rejects.toThrow(
+'Script path is empty.'
+);
+});
+
+it('rejects when scriptPath contains ".." traversal', async () => {
+await expect(
+executeUserScript(buildScript({ scriptPath: '/scripts/../etc/passwd' }))
+).rejects.toThrow('contains ".." traversal');
+});
+
+it('rejects when scriptPath is not absolute', async () => {
+isAbsoluteSpy.mockReturnValue(false);
+await expect(
+executeUserScript(buildScript({ scriptPath: 'scripts/backup.sh' }))
+).rejects.toThrow('Script path must be absolute');
+});
+
+it('rejects when script file does not exist', async () => {
+(fs.existsSync as jest.Mock).mockReturnValue(false);
+await expect(
+executeUserScript(buildScript({ scriptPath: '/scripts/missing.sh' }))
+).rejects.toThrow('Script file does not exist');
+});
+
+it('rejects when scriptPath is a directory', async () => {
+(fs.statSync as jest.Mock).mockReturnValue({ isDirectory: () => true });
+await expect(
+executeUserScript(buildScript({ scriptPath: '/scripts/dir/' }))
+).rejects.toThrow('Script path is a directory');
+});
+});
+
+// Extension-based execution
+describe('extension-based execution', () => {
+const extensionCases = [
+{ ext: '.sh', platform: 'linux', expectedExe: '/bin/bash', scriptPath: '/scripts/backup.sh' },
+{ ext: '.sh', platform: 'win32', expectedExe: 'bash', scriptPath: '/scripts/backup.sh' },
+{ ext: '.bash', platform: 'linux', expectedExe: '/bin/bash', scriptPath: '/scripts/backup.bash' },
+{ ext: '.ps1', platform: 'win32', expectedExe: 'powershell.exe', scriptPath: '/scripts/backup.ps1' },
+{ ext: '.bat', platform: 'win32', expectedExe: 'cmd.exe', scriptPath: '/scripts/backup.bat' },
+{ ext: '.cmd', platform: 'win32', expectedExe: 'cmd.exe', scriptPath: '/scripts/backup.cmd' },
+{ ext: '.py', platform: 'linux', expectedExe: 'python3', scriptPath: '/scripts/backup.py' },
+{ ext: '.py', platform: 'win32', expectedExe: 'python', scriptPath: '/scripts/backup.py' },
+{ ext: '.rb', platform: 'linux', expectedExe: 'ruby', scriptPath: '/scripts/backup.rb' },
+{ ext: '.pl', platform: 'linux', expectedExe: 'perl', scriptPath: '/scripts/backup.pl' },
+{ ext: '.zsh', platform: 'linux', expectedExe: 'zsh', scriptPath: '/scripts/backup.zsh' },
+];
+
+it.each(extensionCases)(
+'spawns $expectedExe for $ext on $platform',
+async ({ platform, expectedExe, scriptPath: sp }) => {
+(os.platform as jest.Mock).mockReturnValue(platform);
+const child = freshChild();
+const promise = executeUserScript(buildScript({ scriptPath: sp }));
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith(
+expectedExe,
+expect.arrayContaining([sp]),
+expect.any(Object)
+);
+}
+);
+
+it('defaults to /bin/sh for unknown extension on Linux', async () => {
+(os.platform as jest.Mock).mockReturnValue('linux');
+const child = freshChild();
+const promise = executeUserScript(buildScript({ scriptPath: '/scripts/backup.xyz' }));
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith('/bin/sh', ['/scripts/backup.xyz'], expect.any(Object));
+});
+
+it('defaults to powershell for unknown extension on Windows', async () => {
+(os.platform as jest.Mock).mockReturnValue('win32');
+const child = freshChild();
+const promise = executeUserScript(buildScript({ scriptPath: '/scripts/backup.xyz' }));
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith(
+'powershell.exe',
+['-NoProfile', '-NonInteractive', '-File', '/scripts/backup.xyz'],
+expect.any(Object)
+);
+});
+});
+
+// Spawn options
+describe('spawn options', () => {
+it('sets cwd to script directory', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript({ scriptPath: '/scripts/sub/backup.sh' }));
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith(
+expect.any(String),
+expect.any(Array),
+expect.objectContaining({ cwd: path.dirname('/scripts/sub/backup.sh') })
+);
+});
+
+it('sets shell to false', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith(
+expect.any(String),
+expect.any(Array),
+expect.objectContaining({ shell: false })
+);
+});
+
+it('passes timeout option to spawn', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript({ timeout: 3000 }));
+
+child.emit('close', 0, null);
+await promise;
+
+expect(mockSpawn).toHaveBeenCalledWith(
+expect.any(String),
+expect.any(Array),
+expect.objectContaining({ timeout: 3000 })
+);
+});
+});
+
+// Success
+it('resolves with stdout and stderr on exit code 0', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
+
+child.stdout.emit('data', Buffer.from('out'));
+child.stderr.emit('data', Buffer.from('err'));
+child.emit('close', 0, null);
+
+const result = await promise;
+expect(result).toEqual({ stdout: 'out', stderr: 'err' });
+});
+
+// Failures
+it('rejects on non-zero exit code', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
+
+child.stderr.emit('data', Buffer.from('bad'));
+child.emit('close', 1, null);
+
+await expect(promise).rejects.toThrow('bad');
+});
+
+it('rejects with generic message when stderr and stdout are empty', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
+
+child.emit('close', 2, null);
+
+await expect(promise).rejects.toThrow('Script exited with code 2');
+});
+
+it('rejects on SIGTERM (timeout)', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript({ timeout: 5000 }));
+
+child.emit('close', null, 'SIGTERM');
+
+await expect(promise).rejects.toThrow('Script timed out after 5000ms');
+});
+
+it('uses default timeout message when timeout is not set', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
+
+child.emit('close', null, 'SIGTERM');
- it('passes the timeout option to spawn', async () => {
- const child = freshChild();
- const script = buildScript({ timeout: 3000 });
- const promise = executeUserScript(script);
+await expect(promise).rejects.toThrow('Script timed out after 60000ms');
+});
+
+it('rejects on spawn error', async () => {
+const child = freshChild();
+const promise = executeUserScript(buildScript());
- child.emit('close', 0, null);
- await promise;
+child.emit('error', new Error('ENOENT'));
- expect(mockSpawn).toHaveBeenCalledWith(
- expect.any(String),
- expect.any(Array),
- expect.objectContaining({ timeout: 3000 })
- );
- });
+await expect(promise).rejects.toThrow('Failed to start script process: ENOENT');
+});
});
describe('runScriptsForEvent', () => {
- let onStart: jest.Mock;
- let onComplete: jest.Mock;
- let onError: jest.Mock;
-
- beforeEach(() => {
- jest.clearAllMocks();
- onStart = jest.fn().mockResolvedValue(undefined);
- onComplete = jest.fn().mockResolvedValue(undefined);
- onError = jest.fn().mockResolvedValue(undefined);
- });
-
- it('returns early when no scripts are provided', async () => {
- await runScriptsForEvent(
- 'onBackupStart',
- [] as PlanScript[],
- 'secret',
- onStart,
- onComplete,
- onError
- );
-
- expect(onStart).not.toHaveBeenCalled();
- expect(onComplete).not.toHaveBeenCalled();
- expect(mockSpawn).not.toHaveBeenCalled();
- });
-
- it('returns early when eventName is empty', async () => {
- await runScriptsForEvent('', [buildScript()], 'secret', onStart, onComplete, onError);
-
- expect(onStart).not.toHaveBeenCalled();
- expect(mockSpawn).not.toHaveBeenCalled();
- });
-
- it('skips disabled scripts', async () => {
- const child = freshChild();
- const scripts = [buildScript({ enabled: false })];
-
- await runScriptsForEvent('onBackupStart', scripts, 'secret', onStart, onComplete, onError);
-
- expect(onStart).not.toHaveBeenCalled();
- expect(mockSpawn).not.toHaveBeenCalled();
- });
-
- it('skips scripts with empty command', async () => {
- const scripts = [buildScript({ command: ' ' })];
-
- await runScriptsForEvent('onBackupStart', scripts, 'secret', onStart, onComplete, onError);
-
- expect(onStart).not.toHaveBeenCalled();
- expect(mockSpawn).not.toHaveBeenCalled();
- });
-
- it('calls onStart and onComplete callbacks on success', async () => {
- const child = freshChild();
- const scripts = [buildScript()];
-
- mockDecrypt.mockReturnValue('echo hello');
-
- const promise = runScriptsForEvent(
- 'onBackupStart',
- scripts,
- 'secret',
- onStart,
- onComplete,
- onError
- );
-
- // Simulate successful child process
- child.emit('close', 0, null);
-
- await promise;
-
- expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
- expect(onComplete).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
- expect(onError).not.toHaveBeenCalled();
- });
-
- it('calls onError callback on script failure', async () => {
- const child = freshChild();
- const scripts = [buildScript({ abortOnError: false })];
-
- mockDecrypt.mockReturnValue('echo hello');
-
- const promise = runScriptsForEvent(
- 'onBackupStart',
- scripts,
- 'secret',
- onStart,
- onComplete,
- onError
- );
-
- child.stderr.emit('data', Buffer.from('something went wrong'));
- child.emit('close', 1, null);
-
- await promise;
-
- expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
- expect(onError).toHaveBeenCalledWith(
- 'ONBACKUPSTART_SCRIPT_1',
- expect.stringContaining('something went wrong')
- );
- expect(onComplete).not.toHaveBeenCalled();
- });
-
- it('throws when abortOnError is true and script fails', async () => {
- const child = freshChild();
- const scripts = [buildScript({ abortOnError: true })];
-
- mockDecrypt.mockReturnValue('echo hello');
-
- const promise = runScriptsForEvent(
- 'onBackupStart',
- scripts,
- 'secret',
- onStart,
- onComplete,
- onError
- );
-
- child.stderr.emit('data', Buffer.from('fatal'));
- child.emit('close', 1, null);
-
- await expect(promise).rejects.toThrow("Critical 'beforeBackup' hook failed");
- expect(onError).toHaveBeenCalled();
- });
-
- it('decrypts commands using Cryptr with the provided secret', async () => {
- const child = freshChild();
- const scripts = [buildScript({ command: 'encrypted-cmd' })];
-
- mockDecrypt.mockReturnValue('decrypted-cmd');
-
- const promise = runScriptsForEvent(
- 'onBackupStart',
- scripts,
- 'my-secret',
- onStart,
- onComplete,
- onError
- );
-
- child.emit('close', 0, null);
-
- await promise;
-
- expect(mockDecrypt).toHaveBeenCalledWith('encrypted-cmd');
- expect(mockSpawn).toHaveBeenCalledWith(
- expect.any(String),
- expect.arrayContaining(['decrypted-cmd']),
- expect.any(Object)
- );
- });
-
- it('processes multiple scripts in order', async () => {
- const children = [freshChild()];
- const scripts = [
- buildScript({ id: 's1', command: 'cmd1' }),
- buildScript({ id: 's2', command: 'cmd2' }),
- ];
-
- mockDecrypt.mockImplementation((v: string) => v);
-
- // For the second script, we need a new child since the first will close
- const child2 = freshChild();
-
- // Reset to return children in order
- let callCount = 0;
- mockSpawn.mockImplementation(() => {
- callCount++;
- if (callCount === 1) return children[0];
- return child2;
- });
-
- const promise = runScriptsForEvent(
- 'onBackupStart',
- scripts,
- 'secret',
- onStart,
- onComplete,
- onError
- );
-
- // Complete first script
- children[0].emit('close', 0, null);
-
- // Wait a tick for the next iteration
- await new Promise(r => setTimeout(r, 0));
-
- // Complete second script
- child2.emit('close', 0, null);
-
- await promise;
-
- expect(onStart).toHaveBeenCalledTimes(2);
- expect(onComplete).toHaveBeenCalledTimes(2);
- expect(onStart).toHaveBeenNthCalledWith(1, 'ONBACKUPSTART_SCRIPT_1');
- expect(onStart).toHaveBeenNthCalledWith(2, 'ONBACKUPSTART_SCRIPT_2');
- });
+let onStart: jest.Mock;
+let onComplete: jest.Mock;
+let onError: jest.Mock;
+let isAbsoluteSpy: jest.SpyInstance;
+
+beforeEach(() => {
+jest.clearAllMocks();
+onStart = jest.fn().mockResolvedValue(undefined);
+onComplete = jest.fn().mockResolvedValue(undefined);
+onError = jest.fn().mockResolvedValue(undefined);
+isAbsoluteSpy = jest.spyOn(path, 'isAbsolute').mockReturnValue(true);
+(fs.existsSync as jest.Mock).mockReturnValue(true);
+(fs.statSync as jest.Mock).mockReturnValue({ isDirectory: () => false });
+(os.platform as jest.Mock).mockReturnValue('linux');
+});
+
+afterEach(() => {
+isAbsoluteSpy.mockRestore();
+});
+
+it('returns early when no scripts are provided', async () => {
+await runScriptsForEvent('onBackupStart', [], onStart, onComplete, onError);
+
+expect(onStart).not.toHaveBeenCalled();
+expect(onComplete).not.toHaveBeenCalled();
+expect(mockSpawn).not.toHaveBeenCalled();
+});
+
+it('returns early when eventName is empty', async () => {
+await runScriptsForEvent('', [buildScript()], onStart, onComplete, onError);
+
+expect(onStart).not.toHaveBeenCalled();
+expect(mockSpawn).not.toHaveBeenCalled();
+});
+
+it('skips disabled scripts', async () => {
+const scripts = [buildScript({ enabled: false })];
+await runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+expect(onStart).not.toHaveBeenCalled();
+expect(mockSpawn).not.toHaveBeenCalled();
+});
+
+it('skips scripts with empty scriptPath', async () => {
+const scripts = [buildScript({ scriptPath: ' ' })];
+await runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+expect(onStart).not.toHaveBeenCalled();
+expect(mockSpawn).not.toHaveBeenCalled();
+});
+
+it('calls onStart and onComplete callbacks on success', async () => {
+const child = freshChild();
+const scripts = [buildScript()];
+
+const promise = runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+// Defer emission: runScriptsForEvent does await onStart() before calling
+// executeUserScript, so the child's 'close' listener isn't set up yet.
+setImmediate(() => {
+child.emit('close', 0, null);
+});
+
+await promise;
+
+expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+expect(onComplete).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+expect(onError).not.toHaveBeenCalled();
+});
+
+it('calls onError callback on script failure', async () => {
+const child = freshChild();
+const scripts = [buildScript({ abortOnError: false })];
+
+const promise = runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+setImmediate(() => {
+child.stderr.emit('data', Buffer.from('something went wrong'));
+child.emit('close', 1, null);
+});
+
+await promise;
+
+expect(onStart).toHaveBeenCalledWith('ONBACKUPSTART_SCRIPT_1');
+expect(onError).toHaveBeenCalledWith(
+'ONBACKUPSTART_SCRIPT_1',
+expect.stringContaining('something went wrong')
+);
+expect(onComplete).not.toHaveBeenCalled();
+});
+
+it('throws when abortOnError is true and script fails', async () => {
+const child = freshChild();
+const scripts = [buildScript({ abortOnError: true })];
+
+const promise = runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+setImmediate(() => {
+child.stderr.emit('data', Buffer.from('fatal'));
+child.emit('close', 1, null);
+});
+
+await expect(promise).rejects.toThrow("Critical 'beforeBackup' hook failed");
+expect(onError).toHaveBeenCalled();
+});
+
+it('processes multiple scripts in order', async () => {
+const children = [freshChild()];
+const scripts = [
+buildScript({ id: 's1', scriptPath: '/scripts/first.sh' }),
+buildScript({ id: 's2', scriptPath: '/scripts/second.sh' }),
+];
+
+const child2 = freshChild();
+let callCount = 0;
+mockSpawn.mockImplementation(() => {
+callCount++;
+if (callCount === 1) return children[0];
+return child2;
+});
+
+const promise = runScriptsForEvent('onBackupStart', scripts, onStart, onComplete, onError);
+
+// Complete first script
+setImmediate(() => {
+children[0].emit('close', 0, null);
+// Complete second script after first is done
+setImmediate(() => {
+child2.emit('close', 0, null);
+});
+});
+
+await promise;
+
+expect(onStart).toHaveBeenCalledTimes(2);
+expect(onComplete).toHaveBeenCalledTimes(2);
+expect(onStart).toHaveBeenNthCalledWith(1, 'ONBACKUPSTART_SCRIPT_1');
+expect(onStart).toHaveBeenNthCalledWith(2, 'ONBACKUPSTART_SCRIPT_2');
+});
});
diff --git a/backend/src/managers/handlers/BackupHandler.ts b/backend/src/managers/handlers/BackupHandler.ts
index 70f658c..c637536 100644
--- a/backend/src/managers/handlers/BackupHandler.ts
+++ b/backend/src/managers/handlers/BackupHandler.ts
@@ -716,12 +716,10 @@ export class BackupHandler {
) {
const phase = this.getPhaseFromScriptEvent(eventName);
const scripts = options?.settings?.scripts?.[eventName] || [];
- const secret = configService.config.SECRET as string;
await runScriptsForEvent(
eventName,
scripts,
- secret,
async scriptName => {
await this.updateProgress(planId, backupId, phase, scriptName + '_START', false);
},
diff --git a/backend/src/stores/PlanStore.ts b/backend/src/stores/PlanStore.ts
index 1df8ae6..4160c9c 100644
--- a/backend/src/stores/PlanStore.ts
+++ b/backend/src/stores/PlanStore.ts
@@ -4,8 +4,6 @@ import { DatabaseType } from '../db';
import { NewPlan, Plan, plans } from '../db/schema/plans';
import { backups } from '../db/schema/backups';
import { PlanBackupSettings, PlanFull } from '../types/plans';
-import Cryptr from 'cryptr';
-import { configService } from '../services/ConfigService';
import { restores } from '../db/schema/restores';
/**
@@ -68,9 +66,6 @@ export class PlanStore {
if (result) {
const plans = result.map(async plan => {
- if (plan?.settings?.scripts) {
- plan.settings.scripts = await this.decryptScripts(plan.settings.scripts);
- }
return {
...plan,
backups: this.handleBackupStats(plan.method, plan.backups, plan.stats),
@@ -139,9 +134,6 @@ export class PlanStore {
if (thePlan && thePlan.backups) {
thePlan.backups = this.handleBackupStats(thePlan.method, thePlan.backups, thePlan.stats);
}
- if (thePlan?.settings?.scripts) {
- thePlan.settings.scripts = await this.decryptScripts(thePlan.settings.scripts);
- }
return thePlan || null;
}
@@ -220,13 +212,6 @@ export class PlanStore {
return null;
}
- // Encrypt scripts if they are present
- if ((updatedPlan.settings as PlanBackupSettings)?.scripts) {
- (updatedPlan.settings as PlanBackupSettings).scripts = await this.encryptScripts(
- (updatedPlan.settings as PlanBackupSettings).scripts
- );
- }
-
const result = await this.db
.update(plans)
.set({
@@ -268,50 +253,4 @@ export class PlanStore {
async setActive(id: string, isActive: boolean): Promise<Plan | null> {
return this.update(id, { isActive });
}
-
- async encryptScripts(scripts: Plan['settings']['scripts']): Promise<Plan['settings']['scripts']> {
- try {
- const planScripts = { ...scripts };
- const cryptr = new Cryptr(configService.config.SECRET as string);
-
- for (const [scriptType, scriptArray] of Object.entries(planScripts)) {
- if (scriptArray && Array.isArray(scriptArray)) {
- planScripts[scriptType as keyof typeof planScripts] = scriptArray.map(script => {
- const encryptedCommand = cryptr.encrypt(script.command);
- return {
- ...script,
- command: encryptedCommand,
- };
- });
- }
- }
- return planScripts;
- } catch (error) {
- console.error('Error encrypting scripts:', error);
- throw new Error('Failed to encrypt Plan scripts');
- }
- }
-
- async decryptScripts(scripts: Plan['settings']['scripts']): Promise<Plan['settings']['scripts']> {
- try {
- const planScripts = { ...scripts };
- const cryptr = new Cryptr(configService.config.SECRET as string);
-
- for (const [scriptType, scriptArray] of Object.entries(planScripts)) {
- if (scriptArray && Array.isArray(scriptArray)) {
- planScripts[scriptType as keyof typeof planScripts] = scriptArray.map(script => {
- const decryptedCommand = cryptr.decrypt(script.command);
- return {
- ...script,
- command: decryptedCommand,
- };
- });
- }
- }
- return planScripts;
- } catch (error) {
- console.error('Error decrypting scripts:', error);
- throw new Error('Failed to decrypt Plan scripts');
- }
- }
}
diff --git a/backend/src/types/plans.ts b/backend/src/types/plans.ts
index 24dd79a..13a70ee 100644
--- a/backend/src/types/plans.ts
+++ b/backend/src/types/plans.ts
@@ -112,9 +112,8 @@ export type PlanScript = {
id: string;
type: string;
enabled: boolean;
- command: string;
+ scriptPath: string; // Absolute path to a script file on the device
logOutput: boolean;
- shell?: string; // bash, powershell, cmd
timeout?: number;
abortOnError?: boolean; // only when event type is onBackupStart
};
diff --git a/backend/src/utils/executeUserScript.ts b/backend/src/utils/executeUserScript.ts
index 34e8e89..e6d37f7 100644
--- a/backend/src/utils/executeUserScript.ts
+++ b/backend/src/utils/executeUserScript.ts
@@ -1,68 +1,60 @@
-import Cryptr from 'cryptr';
import { spawn, ChildProcess } from 'child_process';
import os from 'os';
+import path from 'path';
+import fs from 'fs';
import { PlanScript } from '../types/plans';
/**
- * Executes a user-defined script in a specified shell, capturing its output
+ * Executes a user-defined script file, capturing its output
* and handling timeouts and errors gracefully.
+ * Security: Only local file paths are accepted — no arbitrary commands.
*
- * @param script The PlanScript object containing the command and options.
- * @returns A promise that resolves with the stdout and stderr of the command.
- * @throws An error if the command fails (non-zero exit code) or times out.
+ * @param script The PlanScript object containing the scriptPath and options.
+ * @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 { command, shell, timeout } = script;
-
- let executable: string;
- let args: string[];
-
- // Determine the correct executable and arguments based on the chosen shell
- switch (shell) {
- case 'powershell':
- executable = 'powershell.exe';
- // Using -Command is robust for complex commands. -NoProfile speeds up startup.
- args = ['-NoProfile', '-NonInteractive', '-Command', command];
- break;
- case 'cmd':
- executable = 'cmd.exe';
- args = ['/c', command];
- break;
- case 'bash':
- executable = 'bash';
- args = ['-c', command];
- break;
- case '/bin/bash':
- executable = '/bin/bash';
- args = ['-c', command];
- break;
- case 'zsh':
- executable = 'zsh';
- args = ['-c', command];
- break;
- case '/bin/sh':
- default: // Default to the most basic, universally available shell
- executable = '/bin/sh';
- args = ['-c', command];
- break;
+ 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;
}
- // On Windows, if a Unix-style shell is requested, but the executable is cmd.exe, adjust.
- // This handles the 'default' case on Windows more gracefully.
- if (os.platform() === 'win32' && shell === 'default') {
- executable = 'powershell.exe';
- args = ['-NoProfile', '-NonInteractive', '-Command', command];
+ // Verify the file exists
+ if (!fs.existsSync(scriptPath)) {
+ reject(new Error(`Script file does not exist: ${scriptPath}`));
+ return;
}
+ const stat = fs.statSync(scriptPath);
+ if (stat.isDirectory()) {
+ reject(new Error(`Script path is a directory, not a file: ${scriptPath}`));
+ return;
+ }
+
+ // Determine how to execute based on file extension
+ const { executable, args } = determineScriptExecution(scriptPath);
+
let stdout = '';
let stderr = '';
const child: ChildProcess = spawn(executable, args, {
- timeout: timeout || undefined, // Default to a 60-second timeout
- // 'shell: false' is important for security and predictability,
- // as we are already explicitly invoking the desired shell.
+ timeout: timeout || undefined,
shell: false,
+ cwd: path.dirname(scriptPath),
});
child.stdout?.on('data', data => {
@@ -73,22 +65,18 @@ export function executeUserScript(script: PlanScript): Promise<{ stdout: string;
stderr += data.toString();
});
- // Handle timeout and other spawn errors
child.on('error', err => {
reject(new Error(`Failed to start script process: ${err.message}`));
});
child.on('close', (code, signal) => {
if (signal === 'SIGTERM') {
- // This indicates the process was killed due to timeout
reject(new Error(`Script timed out after ${timeout || 60000}ms.`));
return;
}
if (code === 0) {
- // Success
resolve({ stdout, stderr });
} else {
- // Failure
const errorMessage = stderr.trim() || stdout.trim() || `Script exited with code ${code}`;
reject(new Error(errorMessage));
}
@@ -96,10 +84,52 @@ export function executeUserScript(script: PlanScript): Promise<{ stdout: string;
});
}
+/**
+ * Determines how to execute a script based on its file extension and the current OS.
+ */
+function determineScriptExecution(scriptPath: string): { executable: string; args: string[] } {
+ const ext = path.extname(scriptPath).toLowerCase();
+
+ switch (ext) {
+ case '.ps1':
+ return {
+ executable: 'powershell.exe',
+ args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
+ };
+ case '.bat':
+ case '.cmd':
+ return { executable: 'cmd.exe', args: ['/c', scriptPath] };
+ case '.py':
+ return {
+ executable: os.platform() === 'win32' ? 'python' : 'python3',
+ args: [scriptPath],
+ };
+ case '.rb':
+ return { executable: 'ruby', args: [scriptPath] };
+ case '.pl':
+ return { executable: 'perl', args: [scriptPath] };
+ case '.sh':
+ case '.bash':
+ if (os.platform() === 'win32') {
+ return { executable: 'bash', args: [scriptPath] };
+ }
+ return { executable: '/bin/bash', args: [scriptPath] };
+ case '.zsh':
+ return { executable: 'zsh', args: [scriptPath] };
+ default:
+ if (os.platform() === 'win32') {
+ return {
+ executable: 'powershell.exe',
+ args: ['-NoProfile', '-NonInteractive', '-File', scriptPath],
+ };
+ }
+ return { executable: '/bin/sh', args: [scriptPath] };
+ }
+}
+
export async function runScriptsForEvent(
eventName: string,
scripts: PlanScript[],
- secret: string,
onStart: (scriptName: string) => Promise<void>,
onComplete: (scriptName: string) => Promise<void>,
onError: (scriptName: string, message: string) => Promise<void>
@@ -112,41 +142,26 @@ export async function runScriptsForEvent(
return; // No scripts to run for this event
}
- // get index from this for loop
-
for (let i = 0; i < scripts.length; i++) {
const script = scripts[i];
- // Skip if no command is provided or script is disabled
- if (!script.command.trim() || script.enabled === false) {
+ // Skip if no script path is provided or script is disabled
+ if (!script.scriptPath?.trim() || script.enabled === false) {
continue;
}
const scriptActionName = eventName.toUpperCase() + '_SCRIPT_' + (i + 1);
try {
- if (script.type === 'command' && script.command) {
- // await updateProgress(planId, backupId, phase, scriptActionName + '_START', false);
- onStart(scriptActionName);
- const cryptr = new Cryptr(secret);
- const decryptedCommand = cryptr.decrypt(script.command);
- const { stdout, stderr } = await executeUserScript({
- ...script,
- command: decryptedCommand,
- });
- console.log(`Executed script for '${eventName}': ${script.command}`);
- console.log('stdout :', stdout);
- console.log('stderr :', stderr);
- if (script.logOutput) {
- // if(stdout) planLogger('script', options.id).info(`Script stdout: ${stdout}`);
- // if(stderr) planLogger('script', options.id).warn(`Script stderr: ${stderr}`);
- }
- await onComplete(scriptActionName);
- }
+ await onStart(scriptActionName);
+ const { stdout, stderr } = await executeUserScript(script);
+ console.log(`Executed script for '${eventName}': ${script.scriptPath}`);
+ console.log('stdout :', stdout);
+ console.log('stderr :', stderr);
+ await onComplete(scriptActionName);
} catch (error: any) {
- const errorMessage = `Script for '${eventName}' failed: "${script.command}". Error: ${error.message}`;
+ const errorMessage = `Script for '${eventName}' failed: "${script.scriptPath}". Error: ${error.message}`;
console.log(errorMessage);
await onError(scriptActionName, errorMessage);
if (script.abortOnError) {
- // This throw will be caught by the CORE execute() method's main try/catch block.
throw new Error(`Critical 'beforeBackup' hook failed: ${error.message}`);
}
}
diff --git a/frontend/src/@types/plans.ts b/frontend/src/@types/plans.ts
index bae0c5f..6ade2f0 100644
--- a/frontend/src/@types/plans.ts
+++ b/frontend/src/@types/plans.ts
@@ -122,9 +122,8 @@ export type PlanScript = {
id: string;
type: string;
enabled: boolean;
- command: string;
+ scriptPath: string; // Absolute path to a script file on the device
logOutput: boolean;
- shell?: string;
timeout?: number;
abortOnError?: boolean;
};
diff --git a/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx b/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx
index 37fd49f..a7d76e2 100644
--- a/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx
+++ b/frontend/src/components/Plan/PlanSettings/PlanScriptsSettings.tsx
@@ -3,8 +3,7 @@ import { useState } from 'react';
import { NewPlanSettings } from '../../../@types/plans';
import Icon from '../../common/Icon/Icon';
import Toggle from '../../common/form/Toggle/Toggle';
-import Select from '../../common/form/Select/Select';
-import { getAvailableCliApps, secondsToMinutes } from '../../../utils/helpers';
+import { secondsToMinutes } from '../../../utils/helpers';
import NumberInput from '../../common/form/NumberInput/NumberInput';
interface PlanScriptsSettingsProps {
@@ -77,10 +76,9 @@ const PlanScriptsSettings = ({
onClick={() => {
const newScript = {
id: Math.random().toString(36).substring(2, 15),
- type: 'command',
+ type: 'script',
enabled: true,
- command: '',
- shell: 'default',
+ scriptPath: '',
logOutput: false,
abortOnError: false,
};
@@ -152,15 +150,16 @@ const PlanScriptsSettings = ({
)}
</div>
- <textarea
- value={script?.command || ''}
- data-gramm="false" // Disable Grammarly
- placeholder="Enter script command here..."
+ <input
+ type="text"
+ className={classes.scriptPathInput}
+ value={script?.scriptPath || ''}
+ placeholder="Enter absolute path to script file (e.g. /opt/scripts/pre-backup.sh)"
onChange={(e) => {
const updatedScripts = [...(scripts || [])];
updatedScripts[index] = {
...updatedScripts[index],
- command: e.target.value,
+ scriptPath: e.target.value,
};
onUpdate({ ...settings, [eventKey]: updatedScripts });
}}
@@ -215,23 +214,6 @@ const PlanScriptsSettings = ({
<span>Abort on Error</span>
</div>
<i className="pipe">|</i>
- <div className={classes.scriptOptionCheckbox}>
- {/* <span>Shell</span> */}
- <Select
- size="mini"
- options={getAvailableCliApps(platform)}
- fieldValue={script?.shell || 'default'}
- onUpdate={(value) => {
- const updatedScripts = [...(scripts || [])];
- updatedScripts[index] = {
- ...updatedScripts[index],
- shell: value,
- };
- onUpdate({ ...settings, [eventKey]: updatedScripts });
- }}
- inline={true}
- />
- </div>
<div
title="Timeout Settings"
className={`${classes.scriptOptionTimeout} ${script.id === showTimeoutSettings ? classes.hasTimeOutSettings : ''}`}
diff --git a/frontend/src/components/Plan/PlanSettings/PlanSettings.module.scss b/frontend/src/components/Plan/PlanSettings/PlanSettings.module.scss
index 7629f88..b2d38ae 100644
--- a/frontend/src/components/Plan/PlanSettings/PlanSettings.module.scss
+++ b/frontend/src/components/Plan/PlanSettings/PlanSettings.module.scss
@@ -387,9 +387,9 @@
}
}
- textarea {
+ .scriptPathInput {
border: 1px solid var(--line-color);
- padding: 15px;
+ padding: 10px;
border-radius: 6px;
color: var(--content-text-color);
background-color: var(--content-background-color);