A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: adds the ability to backup & restore pluton itself
towfiqi9eb13f49b120
diff --git a/backend/__tests__/controllers/StorageController.test.ts b/backend/__tests__/controllers/StorageController.test.tsindex 8bfb5fb..3d34819 100644--- a/backend/__tests__/controllers/StorageController.test.ts+++ b/backend/__tests__/controllers/StorageController.test.ts@@ -19,6 +19,7 @@ describe('StorageController', () => {null as any,null as any,null as any,+ null as any,null as any) as jest.Mocked<StorageService>;diff --git a/backend/__tests__/jobs/tasks/SelfBackupTask.test.ts b/backend/__tests__/jobs/tasks/SelfBackupTask.test.tsnew file mode 100644index 0000000..3d970ed--- /dev/null+++ b/backend/__tests__/jobs/tasks/SelfBackupTask.test.ts@@ -0,0 +1,68 @@+jest.mock('../../../src/utils/logger', () => ({+ cronLogger: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },+ logger: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },+}));++import { SelfBackupTask } from '../../../src/jobs/tasks/SelfBackupTask';+import { Job } from '../../../src/jobs/JobQueue';++function makeJob(payload?: any): Job {+ return {+ id: 'job-1',+ name: 'SelfBackup',+ payload,+ attempts: 0,+ maxAttempts: 3,+ retryDelay: 600000,+ lastAttempt: 0,+ };+}++describe('SelfBackupTask', () => {+ let service: { isDue: jest.Mock; run: jest.Mock };+ let task: SelfBackupTask;++ beforeEach(() => {+ service = {+ isDue: jest.fn().mockResolvedValue(false),+ run: jest.fn().mockResolvedValue({ status: 'uploaded', blobName: 'b.pluton' }),+ };+ task = new SelfBackupTask(service as any);+ });++ it('registers under the name the system job entry uses', () => {+ // A mismatch here yields "No task registered for job name" and a permanent fail.+ expect(task.name).toBe('SelfBackup');+ });++ it('does not run when the interval gate says it is not due', async () => {+ await task.run(makeJob());+ expect(service.run).not.toHaveBeenCalled();+ });++ it('runs when due', async () => {+ service.isDue.mockResolvedValue(true);+ await task.run(makeJob());+ expect(service.run).toHaveBeenCalledWith({ force: false });+ });++ it('force in the payload bypasses the gate entirely', async () => {+ service.isDue.mockResolvedValue(false);+ await task.run(makeJob({ force: true }));++ expect(service.isDue).not.toHaveBeenCalled();+ expect(service.run).toHaveBeenCalledWith({ force: true });+ });++ it('tolerates a job with no payload (the cron tick)', async () => {+ service.isDue.mockResolvedValue(true);+ await task.run(makeJob(undefined));+ expect(service.run).toHaveBeenCalledWith({ force: false });+ });++ it('propagates a failure so JobQueue retries', async () => {+ service.isDue.mockResolvedValue(true);+ service.run.mockRejectedValue(new Error('upload failed'));+ await expect(task.run(makeJob())).rejects.toThrow('upload failed');+ });+});diff --git a/backend/__tests__/services/ConfigService.test.ts b/backend/__tests__/services/ConfigService.test.tsindex c220aec..952df2d 100644--- a/backend/__tests__/services/ConfigService.test.ts+++ b/backend/__tests__/services/ConfigService.test.ts@@ -183,6 +183,78 @@ describe('ConfigService', () => {expect(mockConsoleError).toHaveBeenCalledWith(expect.stringContaining('ENCRYPTION_KEY'));});+ describe('CLI command invocations', () => {+ // The fail-fast exists to stop the *app* booting broken. A CLI command never boots the+ // app, and on docker/server installs the server's credentials are legitimately absent+ // from the invoking shell, so exiting here made --restore-pluton unreachable there.+ const originalArgv = process.argv;+ afterEach(() => {+ process.argv = originalArgv;+ });++ it.each([['--restore-pluton'], ['--reset-password']])(+ 'does not exit when credentials are missing but %s was passed',+ async flag => {+ process.env = { NODE_ENV: 'production' };+ process.argv = ['node', 'pluton', flag];+ mockExistsSync.mockReturnValue(false);++ const { configService } = await import('../../src/services/ConfigService');++ expect(mockExit).not.toHaveBeenCalled();+ expect(configService.isSetupPending()).toBe(true);+ }+ );++ it('still exposes SERVER_PORT, which the restore guard probes', async () => {+ process.env = { NODE_ENV: 'production', SERVER_PORT: '8080' };+ process.argv = ['node', 'pluton', '--restore-pluton', './b.pluton'];+ mockExistsSync.mockReturnValue(false);++ const { configService } = await import('../../src/services/ConfigService');++ expect(configService.config.SERVER_PORT).toBe(8080);+ });++ it('reproduces the docker restore command: only PLUTON_ENCRYPTION_KEY is passed', async () => {+ // Design doc 5.6 passes the key and nothing else. Before the escape hatch this+ // exited 1 during import and the restore was impossible on docker.+ process.env = {+ NODE_ENV: 'production',+ IS_DOCKER: 'true',+ PLUTON_ENCRYPTION_KEY: 'a-real-encryption-key-123',+ };+ process.argv = ['node', 'pluton', '--restore-pluton', '/tmp/blob'];+ mockExistsSync.mockReturnValue(false);++ await import('../../src/services/ConfigService');++ expect(mockExit).not.toHaveBeenCalled();+ });++ it('STILL fail-fasts for a real server boot with no CLI flag', async () => {+ // The guard must only be scoped, never weakened.+ process.env = { NODE_ENV: 'production' };+ process.argv = ['node', 'pluton'];+ mockExistsSync.mockReturnValue(false);++ await expect(import('../../src/services/ConfigService')).rejects.toThrow(+ 'process.exit called'+ );+ expect(mockExit).toHaveBeenCalledWith(1);+ });++ it('does not treat an unrelated flag as a CLI command', async () => {+ process.env = { NODE_ENV: 'production' };+ process.argv = ['node', 'pluton', '--verbose'];+ mockExistsSync.mockReturnValue(false);++ await expect(import('../../src/services/ConfigService')).rejects.toThrow(+ 'process.exit called'+ );+ });+ });+it('should exit the process for invalid data types', async () => {// Arrangeprocess.env = {diff --git a/backend/__tests__/services/SelfBackupService.test.ts b/backend/__tests__/services/SelfBackupService.test.tsnew file mode 100644index 0000000..2c80292--- /dev/null+++ b/backend/__tests__/services/SelfBackupService.test.ts@@ -0,0 +1,523 @@+import fs from 'fs';+import os from 'os';+import path from 'path';++let mockDataDir: string;++jest.mock('../../src/utils/AppPaths', () => ({+ appPaths: {+ getDataDir: () => mockDataDir,+ getConfigDir: () => path.join(mockDataDir, 'config'),+ getDbDir: () => path.join(mockDataDir, 'db'),+ getProgressDir: () => path.join(mockDataDir, 'progress'),+ getSyncDir: () => path.join(mockDataDir, 'sync'),+ getSchedulesPath: () => path.join(mockDataDir, 'schedules.json'),+ getTempDir: () => path.join(mockDataDir, 'temp'),+ },+}));++jest.mock('../../src/services/ConfigService', () => ({+ configService: { config: { ENCRYPTION_KEY: 'test-encryption-key-1234' } },+}));++const mockRunRcloneCommand = jest.fn();+jest.mock('../../src/utils/rclone/rclone', () => ({+ runRcloneCommand: (...args: any[]) => mockRunRcloneCommand(...args),+}));++jest.mock('../../src/utils/logger', () => ({+ cronLogger: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },+ logger: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },+}));++// Factory mocks keep the real modules — and the live `db/index` handle+// NotificationChannelResolver would otherwise open at import time — out of the graph.+const mockSend = jest.fn().mockResolvedValue({ success: true, result: 'ok' });+const mockGetChannel = jest.fn().mockResolvedValue({ send: mockSend });+jest.mock('../../src/notifications/channels/NotificationChannelResolver', () => ({+ NotificationChannelResolver: { getChannel: (...args: any[]) => mockGetChannel(...args) },+}));+jest.mock(+ '../../src/notifications/templates/email/backup/SelfBackupFailedNotification',+ () => ({+ SelfBackupFailedNotification: jest+ .fn()+ .mockImplementation((data: any) => ({ __data: data })),+ })+);++import { SelfBackupService } from '../../src/services/SelfBackupService';+import { jobQueue } from '../../src/jobs/JobQueue';+import { SELF_BACKUP_JOB_NAME } from '../../src/jobs/systemJobs';+import { writeSelfBackupState, readSelfBackupState } from '../../src/utils/selfBackup/state';+import { computeFingerprint } from '../../src/utils/selfBackup/payload';++/** Comfortably outside any interval a test uses, so "did this advance?" is unambiguous. */+const OLD_TIMESTAMP = '2020-01-01T00:00:00.000Z';++const ENABLED = {+ enabled: true,+ storageId: 'stor-1',+ storageName: 'mybackups',+ path: 'pluton/self',+ intervalHours: 12,+ retention: 10,+};++function makeService(+ overrides: {+ selfBackup?: any;+ storageName?: string | null;+ adminEmail?: string;+ integration?: Record<string, any>;+ } = {}+) {+ const settingsStore = {+ getFirst: jest.fn().mockResolvedValue({+ id: 1,+ settings: {+ title: 'Pluton',+ admin_email: overrides.adminEmail ?? '',+ integration: overrides.integration ?? {},+ // `in` rather than ?? so a test can pass an explicit undefined.+ selfBackup: 'selfBackup' in overrides ? overrides.selfBackup : ENABLED,+ },+ }),+ } as any;++ const storageStore = {+ getById: jest+ .fn()+ .mockResolvedValue(+ overrides.storageName === null ? null : { id: 'stor-1', name: overrides.storageName ?? 'mybackups' }+ ),+ } as any;++ // VACUUM INTO is exercised for real in the spike; here it only needs to produce a file.+ const sqlite = {+ pragma: jest.fn().mockReturnValue(7),+ prepare: jest.fn().mockReturnValue({+ run: (dest: string) => fs.writeFileSync(dest, 'vacuumed-db'),+ }),+ } as any;++ return {+ service: new SelfBackupService(settingsStore, storageStore, sqlite, 'core'),+ settingsStore,+ storageStore,+ sqlite,+ };+}++const rcloneCalls = (verb: string) =>+ mockRunRcloneCommand.mock.calls.filter(call => call[0][0] === verb);++describe('SelfBackupService', () => {+ let tmpDir: string;++ beforeEach(() => {+ jest.clearAllMocks();+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'selfbackup-svc-'));+ mockDataDir = tmpDir;+ fs.mkdirSync(path.join(tmpDir, 'config'), { recursive: true });+ fs.mkdirSync(path.join(tmpDir, 'db'), { recursive: true });+ fs.mkdirSync(path.join(tmpDir, 'temp'), { recursive: true });+ fs.writeFileSync(path.join(tmpDir, 'db', 'pluton.db'), 'db');+ mockRunRcloneCommand.mockResolvedValue('');+ });++ afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ });++ it('does nothing and makes zero rclone calls when disabled', async () => {+ const { service } = makeService({ selfBackup: { ...ENABLED, enabled: false } });+ await expect(service.run()).resolves.toEqual({ status: 'disabled' });+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('treats a missing selfBackup block as disabled (existing installs)', async () => {+ const { service } = makeService({ selfBackup: undefined });+ await expect(service.run()).resolves.toEqual({ status: 'disabled' });+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('skips with zero rclone calls when the fingerprint is unchanged', async () => {+ writeSelfBackupState({ lastFingerprint: computeFingerprint() });+ const { service } = makeService();++ await expect(service.run()).resolves.toEqual({ status: 'skipped' });+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('a completed run leaves a fingerprint that suppresses the next one', async () => {+ // Regression: the service writes self_backup_state.json at the end of every run. If+ // that file fed the fingerprint, each run would invalidate the fingerprint it had just+ // recorded and the skip path could never fire, so an idle instance would upload forever.+ const { service } = makeService();+ await expect(service.run()).resolves.toMatchObject({ status: 'uploaded' });++ mockRunRcloneCommand.mockClear();+ await expect(service.run()).resolves.toEqual({ status: 'skipped' });+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('force overrides an unchanged fingerprint', async () => {+ writeSelfBackupState({ lastFingerprint: computeFingerprint() });+ const { service } = makeService();++ const result = await service.run({ force: true });+ expect(result.status).toBe('uploaded');+ expect(rcloneCalls('copyto').length).toBeGreaterThan(0);+ });++ it('uploads the blob and the sidecar with the expected copyto argv', async () => {+ const { service } = makeService();+ const result = await service.run();++ expect(result.status).toBe('uploaded');+ expect(result.blobName).toMatch(/^pluton-.*\.pluton$/);++ const copytos = rcloneCalls('copyto');+ expect(copytos).toHaveLength(2);++ const [blobArgs] = copytos[0];+ expect(blobArgs[2]).toBe(`mybackups:pluton/self/${result.blobName}`);+ // A timeout is passed: an unbounded hang here would wedge the global job lock.+ expect(copytos[0][2]).toEqual({ timeoutMs: expect.any(Number) });++ const [sidecarArgs] = copytos[1];+ expect(sidecarArgs[2]).toBe('mybackups:pluton/self/pluton-recovery.json');+ });++ it('targets the remote root without a stray leading slash when path is empty', async () => {+ // `remote:/blob` would mean the filesystem root on a local remote, not the remote's root.+ const { service } = makeService({ selfBackup: { ...ENABLED, path: '' } });+ const result = await service.run();++ expect(rcloneCalls('copyto')[0][0][2]).toBe(`mybackups:${result.blobName}`);+ });++ it('tolerates leading and trailing slashes in the configured path', async () => {+ const { service } = makeService({ selfBackup: { ...ENABLED, path: '/pluton/self/' } });+ const result = await service.run();++ expect(rcloneCalls('copyto')[0][0][2]).toBe(`mybackups:pluton/self/${result.blobName}`);+ });++ it('records success state including the fingerprint it uploaded', async () => {+ const { service } = makeService();+ const result = await service.run();++ const state = readSelfBackupState();+ expect(state.lastSuccessAt).toBeTruthy();+ expect(state.lastError).toBeNull();+ expect(state.lastBlobName).toBe(result.blobName);+ expect(state.lastFingerprint).toBeTruthy();+ });++ it('stamps lastRunAt and lastSuccessAt from a single clock read', async () => {+ // A run that succeeded ran and succeeded at the same instant. Two separate `new Date()`+ // calls are equal almost always, so a drifting pair passes every test and then straddles+ // a millisecond in production, leaving the state file quietly self-contradictory.+ const { service } = makeService();+ await service.run();++ const state = readSelfBackupState();+ expect(state.lastRunAt).toBe(state.lastSuccessAt);+ });++ it('treats a skip as a success, so an idle instance never looks stale', async () => {+ // An unchanged fingerprint means the blob already on the remote still matches this+ // install: Pluton IS backed up as of now. Advancing only lastRunAt would leave an idle+ // instance -- behaving exactly as designed -- tripping the stale alarm after 2x the+ // interval, training the user to ignore the one alarm that has to be trustworthy.+ writeSelfBackupState({ lastFingerprint: computeFingerprint(), lastSuccessAt: OLD_TIMESTAMP });+ const { service } = makeService();++ await expect(service.run()).resolves.toEqual({ status: 'skipped' });++ const state = readSelfBackupState();+ expect(state.lastSuccessAt).not.toBe(OLD_TIMESTAMP);+ expect(state.lastRunAt).toBe(state.lastSuccessAt);+ expect(state.lastError).toBeNull();+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('deletes exactly the blobs beyond the retention count, oldest first', async () => {+ const names = [+ 'pluton-2026-01-01T00-00-00-000Z.pluton',+ 'pluton-2026-01-02T00-00-00-000Z.pluton',+ 'pluton-2026-01-03T00-00-00-000Z.pluton',+ 'pluton-2026-01-04T00-00-00-000Z.pluton',+ 'pluton-2026-01-05T00-00-00-000Z.pluton',+ ];+ mockRunRcloneCommand.mockImplementation((args: string[]) => {+ if (args[0] === 'lsjson') {+ return Promise.resolve(+ JSON.stringify([+ ...names.map(Name => ({ Name, Path: Name, Size: 10, IsDir: false })),+ // Neither the sidecar nor a directory is a retention candidate.+ { Name: 'pluton-recovery.json', Path: 'pluton-recovery.json', Size: 2, IsDir: false },+ { Name: 'pluton-olddir.pluton', Path: 'pluton-olddir.pluton', Size: 0, IsDir: true },+ ])+ );+ }+ return Promise.resolve('');+ });++ const { service } = makeService({ selfBackup: { ...ENABLED, retention: 2 } });+ await service.run();++ const deleted = rcloneCalls('deletefile').map(call => call[0][1]);+ expect(deleted).toEqual([+ 'mybackups:pluton/self/pluton-2026-01-03T00-00-00-000Z.pluton',+ 'mybackups:pluton/self/pluton-2026-01-02T00-00-00-000Z.pluton',+ 'mybackups:pluton/self/pluton-2026-01-01T00-00-00-000Z.pluton',+ ]);+ });++ it('does not fail the run when retention deletion rejects, since the blob is already safe', async () => {+ mockRunRcloneCommand.mockImplementation((args: string[]) => {+ if (args[0] === 'lsjson') {+ return Promise.resolve(+ JSON.stringify([+ { Name: 'pluton-a.pluton', Path: 'a', Size: 1, IsDir: false },+ { Name: 'pluton-b.pluton', Path: 'b', Size: 1, IsDir: false },+ ])+ );+ }+ if (args[0] === 'deletefile') return Promise.reject(new Error('remote said no'));+ return Promise.resolve('');+ });++ const { service } = makeService({ selfBackup: { ...ENABLED, retention: 1 } });+ await expect(service.run()).resolves.toMatchObject({ status: 'uploaded' });+ });++ it('does not fail the run when lsjson returns a warning instead of JSON', async () => {+ mockRunRcloneCommand.mockImplementation((args: string[]) =>+ args[0] === 'lsjson'+ ? Promise.resolve('NOTICE: config file not encrypted')+ : Promise.resolve('')+ );++ const { service } = makeService();+ await expect(service.run()).resolves.toMatchObject({ status: 'uploaded' });+ expect(rcloneCalls('deletefile')).toHaveLength(0);+ });++ it('throws and records the error when the upload fails, so the job retries', async () => {+ mockRunRcloneCommand.mockImplementation((args: string[]) =>+ args[0] === 'copyto' ? Promise.reject(new Error('network down')) : Promise.resolve('')+ );++ const { service } = makeService();+ await expect(service.run()).rejects.toThrow('network down');++ const state = readSelfBackupState();+ expect(state.lastError).toBe('network down');+ expect(state.lastSuccessAt).toBeUndefined();+ });++ it('passes a storage name with spaces through to rclone unquoted', async () => {+ // Safe because runRcloneCommand spawns with an argv array and no shell, so the name+ // reaches rclone as a single argument. Nothing needs to escape or reject it.+ const { service } = makeService({ storageName: 'My Backups' });++ const result = await service.run();+ expect(rcloneCalls('copyto')[0][0][2]).toBe(`My Backups:pluton/self/${result.blobName}`);+ });++ it('refuses when the selected storage no longer exists', async () => {+ const { service } = makeService({ storageName: null });+ await expect(service.run()).rejects.toThrow(/no longer exists/);+ });++ it('removes the temp dir on success', async () => {+ const { service } = makeService();+ await service.run();+ expect(fs.readdirSync(path.join(tmpDir, 'temp'))).toEqual([]);+ });++ it('removes the temp dir when the run throws', async () => {+ mockRunRcloneCommand.mockRejectedValue(new Error('boom'));+ const { service } = makeService();+ await expect(service.run()).rejects.toThrow('boom');+ expect(fs.readdirSync(path.join(tmpDir, 'temp'))).toEqual([]);+ });++ describe('isDue', () => {+ it('is false when disabled', async () => {+ const { service } = makeService({ selfBackup: { ...ENABLED, enabled: false } });+ expect(await service.isDue()).toBe(false);+ });++ it('is true when there has never been a successful run', async () => {+ const { service } = makeService();+ expect(await service.isDue()).toBe(true);+ });++ it('is false an hour after success with a 12h interval', async () => {+ writeSelfBackupState({ lastSuccessAt: new Date(Date.now() - 3600_000).toISOString() });+ const { service } = makeService();+ expect(await service.isDue()).toBe(false);+ });++ it('is true 13 hours after success with a 12h interval', async () => {+ writeSelfBackupState({ lastSuccessAt: new Date(Date.now() - 13 * 3600_000).toISOString() });+ const { service } = makeService();+ expect(await service.isDue()).toBe(true);+ });+ });++ describe('getStatus', () => {+ it('merges the resolved settings with the runtime state file', async () => {+ writeSelfBackupState({ lastSuccessAt: '2026-07-15T00:00:00.000Z', lastBlobName: 'b.pluton' });+ const { service } = makeService();++ const status = await service.getStatus();+ expect(status).toMatchObject({+ enabled: true,+ intervalHours: 12,+ retention: 10,+ lastSuccessAt: '2026-07-15T00:00:00.000Z',+ lastBlobName: 'b.pluton',+ });+ });++ it('reports running straight from the job queue, in both directions', async () => {+ // The UI polls on this. It used to be inferred by comparing lastRunAt against+ // lastSuccessAt, which cannot tell a running job apart from a skipped one and never+ // fires on the first-ever run, when there is no lastRunAt to compare against yet.+ const { service } = makeService();+ expect((await service.getStatus()).running).toBe(false);++ jobQueue.add(SELF_BACKUP_JOB_NAME, { force: true }, 1, 0);+ expect((await service.getStatus()).running).toBe(true);+ });+ });++ describe('listBackups', () => {+ it('returns only blobs, newest first, with size and modTime', async () => {+ mockRunRcloneCommand.mockImplementation((args: string[]) => {+ if (args[0] === 'lsjson') {+ return Promise.resolve(+ JSON.stringify([+ { Name: 'pluton-2026-01-01T00-00-00-000Z.pluton', Size: 10, ModTime: 't1', IsDir: false },+ { Name: 'pluton-2026-01-03T00-00-00-000Z.pluton', Size: 30, ModTime: 't3', IsDir: false },+ { Name: 'pluton-2026-01-02T00-00-00-000Z.pluton', Size: 20, ModTime: 't2', IsDir: false },+ // Sidecar and a directory must be excluded.+ { Name: 'pluton-recovery.json', Size: 2, IsDir: false },+ { Name: 'pluton-dir.pluton', Size: 0, IsDir: true },+ ])+ );+ }+ return Promise.resolve('');+ });++ const { service } = makeService();+ const list = await service.listBackups();++ expect(list).toEqual([+ { name: 'pluton-2026-01-03T00-00-00-000Z.pluton', size: 30, modTime: 't3' },+ { name: 'pluton-2026-01-02T00-00-00-000Z.pluton', size: 20, modTime: 't2' },+ { name: 'pluton-2026-01-01T00-00-00-000Z.pluton', size: 10, modTime: 't1' },+ ]);+ });++ it('returns an empty list when no storage is configured', async () => {+ const { service } = makeService({ selfBackup: { ...ENABLED, storageId: '' } });+ expect(await service.listBackups()).toEqual([]);+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });+ });++ describe('downloadBackup', () => {+ const blob = 'pluton-2026-01-01T00-00-00-000Z.pluton';++ it('copies a valid blob to a temp file and cleans it up afterwards', async () => {+ const { service } = makeService();+ const { localPath, cleanup } = await service.downloadBackup(blob);++ const copytos = rcloneCalls('copyto');+ expect(copytos).toHaveLength(1);+ expect(copytos[0][0][1]).toBe(`mybackups:pluton/self/${blob}`);+ expect(copytos[0][0][2]).toBe(localPath);+ expect(fs.existsSync(path.dirname(localPath))).toBe(true);++ await cleanup();+ expect(fs.existsSync(path.dirname(localPath))).toBe(false);+ });++ it('rejects a blob name that is not a Pluton blob', async () => {+ const { service } = makeService();+ await expect(service.downloadBackup('../rclone.conf')).rejects.toThrow(/Invalid backup name/);+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();+ });++ it('cleans up the temp dir when the remote copy fails', async () => {+ mockRunRcloneCommand.mockRejectedValue(new Error('remote down'));+ const { service } = makeService();+ await expect(service.downloadBackup(blob)).rejects.toThrow('remote down');+ // Nothing left behind under the temp dir.+ expect(fs.readdirSync(path.join(tmpDir, 'temp'))).toEqual([]);+ });+ });++ describe('failure notification', () => {+ const failUpload = () =>+ mockRunRcloneCommand.mockImplementation((args: string[]) =>+ args[0] === 'copyto' ? Promise.reject(new Error('network down')) : Promise.resolve('')+ );++ it('emails the admin via the first connected email integration on failure', async () => {+ failUpload();+ const { service } = makeService({+ selfBackup: { ...ENABLED, notifyOnFailure: true },+ adminEmail: '[email protected]',+ integration: { smtp: { connected: true } },+ });++ await expect(service.run()).rejects.toThrow('network down');+ expect(mockGetChannel).toHaveBeenCalledWith('smtp');+ expect(mockSend).toHaveBeenCalledWith(expect.anything(), { emails: '[email protected]' });+ });++ it('does not email when the toggle is off', async () => {+ failUpload();+ const { service } = makeService({+ selfBackup: { ...ENABLED, notifyOnFailure: false },+ adminEmail: '[email protected]',+ integration: { smtp: { connected: true } },+ });++ await expect(service.run()).rejects.toThrow('network down');+ expect(mockGetChannel).not.toHaveBeenCalled();+ });++ it('does not email when no email integration is connected', async () => {+ failUpload();+ const { service } = makeService({+ selfBackup: { ...ENABLED, notifyOnFailure: true },+ adminEmail: '[email protected]',+ integration: { smtp: { connected: false } },+ });++ await expect(service.run()).rejects.toThrow('network down');+ expect(mockGetChannel).not.toHaveBeenCalled();+ });++ it('still surfaces the backup error even if the email send throws', async () => {+ failUpload();+ mockGetChannel.mockRejectedValueOnce(new Error('smtp boom'));+ const { service } = makeService({+ selfBackup: { ...ENABLED, notifyOnFailure: true },+ adminEmail: '[email protected]',+ integration: { smtp: { connected: true } },+ });++ await expect(service.run()).rejects.toThrow('network down');+ });+ });+});diff --git a/backend/__tests__/services/StorageService.test.ts b/backend/__tests__/services/StorageService.test.tsindex 57bdf49..e234a22 100644--- a/backend/__tests__/services/StorageService.test.ts+++ b/backend/__tests__/services/StorageService.test.ts@@ -2,6 +2,7 @@ import Cryptr from 'cryptr';import { StorageService } from '../../src/services/StorageService';import { StorageStore } from '../../src/stores/StorageStore';import { PlanStore } from '../../src/stores/PlanStore';+import { SettingsStore } from '../../src/stores/SettingsStore';import { BaseStorageManager } from '../../src/managers/BaseStorageManager';import { BaseSystemManager } from '../../src/managers/BaseSystemManager';import { LocalStrategy, RemoteStrategy } from '../../src/strategies/system';@@ -15,6 +16,7 @@ jest.mock('../../src/utils/rclone/helpers');// Mock dependenciesjest.mock('../../src/stores/StorageStore');jest.mock('../../src/stores/PlanStore');+jest.mock('../../src/stores/SettingsStore');jest.mock('../../src/managers/BaseStorageManager');jest.mock('../../src/managers/BaseSystemManager');jest.mock('../../src/strategies/system');@@ -37,6 +39,7 @@ describe('StorageService', () => {let storageService: StorageService;let mockStorageStore: jest.Mocked<StorageStore>;let mockPlanStore: jest.Mocked<PlanStore>;+ let mockSettingsStore: jest.Mocked<SettingsStore>;let mockStorageManager: jest.Mocked<BaseStorageManager>;let mockSystemManager: jest.Mocked<BaseSystemManager>;let mockLocalStrategy: jest.Mocked<LocalStrategy>;@@ -50,6 +53,7 @@ describe('StorageService', () => {// Instantiate mocksmockStorageStore = new StorageStore(null as any) as jest.Mocked<StorageStore>;mockPlanStore = new PlanStore(null as any) as jest.Mocked<PlanStore>;+ mockSettingsStore = new SettingsStore(null as any) as jest.Mocked<SettingsStore>;mockStorageManager = new BaseStorageManager() as jest.Mocked<BaseStorageManager>;mockSystemManager = new BaseSystemManager() as jest.Mocked<BaseSystemManager>;@@ -74,7 +78,8 @@ describe('StorageService', () => {mockStorageManager,mockSystemManager,mockStorageStore,- mockPlanStore+ mockPlanStore,+ mockSettingsStore);});@@ -278,6 +283,37 @@ describe('StorageService', () => {'This Storage is used as a replication target by the following plans: Plan B. Please remove it from their replication settings before deleting the storage.');});++ it('should throw AppError if an active self-backup uses the storage', async () => {+ mockStorageStore.getById.mockResolvedValue(mockStorage);+ mockPlanStore.getStoragePlans.mockResolvedValue([]);+ mockStorageStore.getReplicationPlans = jest.fn().mockResolvedValue([]);+ mockSettingsStore.getFirst.mockResolvedValue({+ settings: { selfBackup: { enabled: true, storageId } },+ } as any);++ await expect(storageService.deleteStorage(storageId)).rejects.toThrow(AppError);+ await expect(storageService.deleteStorage(storageId)).rejects.toThrow(+ "This Storage is used by Pluton's self-backup. Please disable self-backup or choose a different storage before deleting it."+ );+ expect(mockStorageManager.deleteRemote).not.toHaveBeenCalled();+ });++ it('should allow deletion when self-backup is disabled or uses a different storage', async () => {+ mockStorageStore.getById.mockResolvedValue(mockStorage);+ mockPlanStore.getStoragePlans.mockResolvedValue([]);+ mockStorageStore.getReplicationPlans = jest.fn().mockResolvedValue([]);+ mockSettingsStore.getFirst.mockResolvedValue({+ settings: { selfBackup: { enabled: true, storageId: 'a-different-storage' } },+ } as any);+ mockStorageManager.deleteRemote.mockResolvedValue({ success: true, result: 'Deleted' });+ mockStorageStore.delete.mockResolvedValue(true);++ const result = await storageService.deleteStorage(storageId);++ expect(result).toBe(true);+ expect(mockStorageManager.deleteRemote).toHaveBeenCalledWith('Old Storage');+ });});// ----------------------------------------diff --git a/backend/__tests__/utils/cliCommands.test.ts b/backend/__tests__/utils/cliCommands.test.tsnew file mode 100644index 0000000..06a0d33--- /dev/null+++ b/backend/__tests__/utils/cliCommands.test.ts@@ -0,0 +1,36 @@+import { isCliCommandInvocation, CLI_COMMAND_FLAGS } from '../../src/utils/cliCommands';++describe('isCliCommandInvocation', () => {+ it('detects every flag it claims to cover', () => {+ for (const flag of CLI_COMMAND_FLAGS) {+ expect(isCliCommandInvocation(['node', 'pluton', flag])).toBe(true);+ }+ });++ it('detects a flag that has arguments after it', () => {+ expect(isCliCommandInvocation(['node', 'pluton', '--restore-pluton', './b.pluton', '--force'])).toBe(+ true+ );+ });++ it('is false for a plain server start', () => {+ expect(isCliCommandInvocation(['node', 'pluton'])).toBe(false);+ });++ it('is false for unrelated flags, so a real boot still fail-fasts', () => {+ expect(isCliCommandInvocation(['node', 'pluton', '--verbose', '--port', '5173'])).toBe(false);+ });++ it('does not match a flag appearing as a value', () => {+ // Substring matching here would wrongly disarm the server's credential fail-fast.+ expect(isCliCommandInvocation(['node', 'pluton', '--title', 'my--restore-pluton-app'])).toBe(+ false+ );+ });++ it('covers the flags index.ts actually dispatches on', () => {+ // If these drift, ConfigService lets a command through that index.ts ignores, or vice+ // versa: the command exits 1 at import with a confusing credentials error.+ expect([...CLI_COMMAND_FLAGS]).toEqual(['--reset-password', '--restore-pluton']);+ });+});diff --git a/backend/__tests__/utils/cliSelfRestore.test.ts b/backend/__tests__/utils/cliSelfRestore.test.tsnew file mode 100644index 0000000..97b636a--- /dev/null+++ b/backend/__tests__/utils/cliSelfRestore.test.ts@@ -0,0 +1,431 @@+import fs from 'fs';+import os from 'os';+import path from 'path';++// cliSelfRestore imports payload -> AppPaths (an import-time singleton that mkdirSync's+// ~12 dirs) and ConfigService. Both are mocked so the pure pieces can be tested in isolation.+const mockDataDir = path.join(__dirname, '__unused__');++// writeEncryptionKeyToEnvFile applies a Windows ACL via icacls; keep it out of tests.+jest.mock('child_process', () => ({ execSync: jest.fn() }));++jest.mock('../../src/utils/AppPaths', () => ({+ appPaths: {+ getDataDir: () => mockDataDir,+ getConfigDir: () => path.join(mockDataDir, 'config'),+ getDbDir: () => path.join(mockDataDir, 'db'),+ getProgressDir: () => path.join(mockDataDir, 'progress'),+ getSyncDir: () => path.join(mockDataDir, 'sync'),+ getSchedulesPath: () => path.join(mockDataDir, 'schedules.json'),+ getTempDir: () => path.join(mockDataDir, 'temp'),+ },+}));++jest.mock('../../src/services/ConfigService', () => ({+ configService: { config: { SERVER_PORT: 5173 } },+}));++import Database from 'better-sqlite3';+import {+ parseRestoreArgs,+ checkVersionSkew,+ checkEdition,+ isServerRunning,+ evaluateInstanceGuard,+ buildCompletionMessage,+ applyEncryptionKey,+ releaseDatabaseFiles,+} from '../../src/utils/cliSelfRestore';++const local = { plutonVersion: '1.4.0', drizzleJournalTag: '0042_stable_tag' };++describe('parseRestoreArgs', () => {+ it('reads the blob path that follows the flag', () => {+ expect(parseRestoreArgs(['node', 'pluton', '--restore-pluton', './b.pluton'])).toEqual({+ blobPath: './b.pluton',+ force: false,+ });+ });++ it('picks up --force in any position', () => {+ expect(parseRestoreArgs(['node', 'pluton', '--force', '--restore-pluton', './b.pluton'])).toEqual(+ { blobPath: './b.pluton', force: true }+ );+ });++ it('returns a null path when the flag has no argument', () => {+ expect(parseRestoreArgs(['node', 'pluton', '--restore-pluton'])).toEqual({+ blobPath: null,+ force: false,+ });+ });++ it('does not swallow a following flag as the blob path', () => {+ expect(parseRestoreArgs(['node', 'pluton', '--restore-pluton', '--force'])).toEqual({+ blobPath: null,+ force: true,+ });+ });++ it('returns a null path when the flag is absent', () => {+ expect(parseRestoreArgs(['node', 'pluton']).blobPath).toBeNull();+ });+});++describe('evaluateInstanceGuard', () => {+ const base = { serverResponding: false, isDocker: false, force: false, port: 5173 };++ it('refuses when the server answers the probe', () => {+ const v = evaluateInstanceGuard({ ...base, serverResponding: true });+ expect(v.allowed).toBe(false);+ expect((v as any).reason).toMatch(/still running on port 5173/);+ });++ it('allows a responding server through --force, but warns', () => {+ const v = evaluateInstanceGuard({ ...base, serverResponding: true, force: true });+ expect(v.allowed).toBe(true);+ expect((v as any).warning).toMatch(/--force/);+ });++ it('allows a silent probe on a non-docker install, where loopback is trustworthy', () => {+ expect(evaluateInstanceGuard(base)).toEqual({ allowed: true });+ });++ it('refuses a silent probe under docker, where the restore container has its own loopback', () => {+ // The motivating bug: without this the guard fails OPEN in exactly the install type+ // where it cannot see the server, and the user silently corrupts a live database.+ const v = evaluateInstanceGuard({ ...base, isDocker: true });+ expect(v.allowed).toBe(false);+ expect((v as any).reason).toMatch(/docker compose down/);+ });++ it('tells the docker user what to do rather than just refusing', () => {+ const reason = (evaluateInstanceGuard({ ...base, isDocker: true }) as any).reason;+ expect(reason).toMatch(/cannot tell whether/i);+ expect(reason).toMatch(/--force/);+ });++ it('lets a docker user proceed with --force, warning that it could not verify', () => {+ const v = evaluateInstanceGuard({ ...base, isDocker: true, force: true });+ expect(v.allowed).toBe(true);+ expect((v as any).warning).toMatch(/[Cc]ould not verify/);+ });++ it('prefers the concrete "still running" message when docker DOES answer the probe', () => {+ // docker exec / --network=host land in the server's namespace, so the probe works+ // and the user deserves the specific message, not the generic docker one.+ const v = evaluateInstanceGuard({ ...base, isDocker: true, serverResponding: true });+ expect(v.allowed).toBe(false);+ expect((v as any).reason).toMatch(/still running on port/);+ expect((v as any).reason).not.toMatch(/docker compose down/);+ });+});++describe('applyEncryptionKey', () => {+ let dataDir: string;+ let encEnvPath: string;+ const KEY = 'the-key-from-the-blob';++ beforeEach(() => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'applykey-'));+ encEnvPath = path.join(dataDir, 'pluton.enc.env');+ });++ afterEach(() => {+ fs.rmSync(dataDir, { recursive: true, force: true });+ });++ it('writes the key on desktop/server, where nothing else supplies it', async () => {+ await applyEncryptionKey({ dataDir, key: KEY, isDocker: false });++ expect(fs.existsSync(encEnvPath)).toBe(true);+ expect(fs.readFileSync(encEnvPath, 'utf-8')).toContain(`ENCRYPTION_KEY=${KEY}`);+ });++ it('writes NOTHING into the data dir on docker', async () => {+ // ENCRYPTION_KEY is RESTIC_PASSWORD for every repo. Compose is the only source of+ // truth on docker, so a copy here would just be a plaintext master key at rest.+ await applyEncryptionKey({ dataDir, key: KEY, isDocker: true });++ expect(fs.existsSync(encEnvPath)).toBe(false);+ });++ it('removes a pre-existing key file on docker, rather than leaving it', async () => {+ fs.writeFileSync(encEnvPath, 'ENCRYPTION_KEY=a-stale-key-from-an-older-restore\n');++ await applyEncryptionKey({ dataDir, key: KEY, isDocker: true });++ // Left in place, ConfigService would silently prefer it whenever compose passes an+ // empty ENCRYPTION_KEY, booting Pluton against the WRONG key. Loud failure is better.+ expect(fs.existsSync(encEnvPath)).toBe(false);+ });++ it('never leaves the key on disk in docker, whatever was there before', async () => {+ fs.writeFileSync(encEnvPath, `ENCRYPTION_KEY=${KEY}\n`);++ await applyEncryptionKey({ dataDir, key: KEY, isDocker: true });++ const leaked = fs+ .readdirSync(dataDir)+ .filter(f => fs.readFileSync(path.join(dataDir, f), 'utf-8').includes(KEY));+ expect(leaked).toEqual([]);+ });++ it('is a no-op on docker when there is no key file to begin with', async () => {+ await expect(applyEncryptionKey({ dataDir, key: KEY, isDocker: true })).resolves.toBeUndefined();+ expect(fs.readdirSync(dataDir)).toEqual([]);+ });++ it('overwrites a stale key file on desktop/server instead of removing it', async () => {+ fs.writeFileSync(encEnvPath, 'ENCRYPTION_KEY=an-old-key\n');++ await applyEncryptionKey({ dataDir, key: KEY, isDocker: false });++ const content = fs.readFileSync(encEnvPath, 'utf-8');+ expect(content).toContain(`ENCRYPTION_KEY=${KEY}`);+ expect(content).not.toContain('an-old-key');+ });+});++describe('buildCompletionMessage', () => {+ // Measured: ConfigService only reads pluton.enc.env when ENCRYPTION_KEY is absent from the+ // env, and hashPasswordIfNeeded re-hashes USER_PASSWORD over the restored PASSWORD_HASH.+ // So the restored key/password only apply where nothing injects env vars.+ const docker = { isDocker: true, isLinuxInstalled: false };+ const server = { isDocker: false, isLinuxInstalled: true };+ const desktop = { isDocker: false, isLinuxInstalled: false };++ it('tells docker users to set ENCRYPTION_KEY in their compose .env', () => {+ const msg = buildCompletionMessage(docker);+ expect(msg).toMatch(/ENCRYPTION_KEY/);+ expect(msg).toMatch(/docker-compose\.yml/);+ expect(msg).toMatch(/same key you just entered/i);+ });++ it('presents the docker .env key as required, not advisory', () => {+ // There is no longer a key file in the volume to fall back on, so omitting it is+ // not a "you probably should" but a "the container will not start".+ const msg = buildCompletionMessage(docker);+ expect(msg).toMatch(/REQUIRED/);+ expect(msg).toMatch(/refuse to start/);+ });++ it('tells docker users the key is deliberately not in the volume', () => {+ expect(buildCompletionMessage(docker)).toMatch(/NOT stored in the data volume/);+ });++ it('warns docker users what a mismatched key costs them', () => {+ expect(buildCompletionMessage(docker)).toMatch(/no longer read/);+ });++ it('does NOT tell docker users to use their old password', () => {+ // It would be wrong: compose's USER_PASSWORD overwrites the restored hash on boot.+ const msg = buildCompletionMessage(docker);+ expect(msg).toMatch(/not your old password/);+ expect(msg).toMatch(/USER_PASSWORD/);+ });++ it('tells server users the key is already handled, since systemd reads the file we wrote', () => {+ const msg = buildCompletionMessage(server);+ expect(msg).toMatch(/etc\/pluton\/pluton\.enc\.env/);+ expect(msg).toMatch(/Nothing more to do for the key/);+ });++ it('points server users at pluton.env for credentials, not the old password', () => {+ const msg = buildCompletionMessage(server);+ expect(msg).toMatch(/etc\/pluton\/pluton\.env/);+ expect(msg).toMatch(/not the old ones/);+ });++ it('gives each install type its own start command', () => {+ expect(buildCompletionMessage(docker)).toMatch(/docker compose up -d/);+ expect(buildCompletionMessage(server)).toMatch(/systemctl start pluton/);+ });++ it('only promises the old password on desktop, where no env vars override it', () => {+ const msg = buildCompletionMessage(desktop);+ expect(msg).toMatch(/log in with your old password/i);+ expect(msg).not.toMatch(/docker compose/);+ expect(msg).not.toMatch(/systemctl/);+ });++ it('says restore is complete in every case', () => {+ for (const env of [docker, server, desktop]) {+ expect(buildCompletionMessage(env)).toMatch(/Restore complete/);+ }+ });+});++describe('checkEdition', () => {+ it('accepts a matching edition', () => {+ expect(checkEdition('core', 'core').ok).toBe(true);+ });++ it('refuses a foreign edition, in both directions', () => {+ const fromPro = checkEdition('pro', 'core');+ expect(fromPro.ok).toBe(false);+ expect(fromPro.reason).toMatch(/different|edition/i);+ expect(checkEdition('core', 'pro').ok).toBe(false);+ });++ it('refuses a blob that does not record its edition', () => {+ expect(checkEdition(undefined, 'core').ok).toBe(false);+ });++ it('says "edition", not "version", since a misleading message sends the user down the wrong path', () => {+ const result = checkEdition('pro', 'core');+ expect(result.reason).toContain('edition');+ expect(result.reason).not.toMatch(/upgrade pluton/i);+ });+});++describe('checkVersionSkew', () => {+ it('accepts an older blob, because migrations run forward. This is the normal path', () => {+ expect(+ checkVersionSkew({ plutonVersion: '1.2.0', drizzleJournalTag: '0031_older' }, local).ok+ ).toBe(true);+ });++ it('accepts an equal version', () => {+ expect(+ checkVersionSkew({ plutonVersion: '1.4.0', drizzleJournalTag: '0042_stable_tag' }, local).ok+ ).toBe(true);+ });++ it('refuses a newer blob version, because there are no down migrations', () => {+ const result = checkVersionSkew({ plutonVersion: '1.5.0', drizzleJournalTag: null }, local);+ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/newer/);+ });++ it('refuses a blob whose schema is ahead even when the version is not', () => {+ const result = checkVersionSkew(+ { plutonVersion: '1.4.0', drizzleJournalTag: '0043_newer' },+ local+ );+ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/schema/);+ });++ it('compares version segments numerically, not lexically', () => {+ // '1.10.0' < '1.9.0' as strings; it must not be treated as older.+ expect(+ checkVersionSkew({ plutonVersion: '1.10.0', drizzleJournalTag: null }, local).ok+ ).toBe(false);+ expect(+ checkVersionSkew(+ { plutonVersion: '1.9.0', drizzleJournalTag: null },+ { plutonVersion: '1.10.0', drizzleJournalTag: null }+ ).ok+ ).toBe(true);+ });++ it('does not block on an unparseable version (dev builds report "unknown")', () => {+ expect(checkVersionSkew({ plutonVersion: 'unknown', drizzleJournalTag: null }, local).ok).toBe(+ true+ );+ expect(+ checkVersionSkew(+ { plutonVersion: '9.9.9', drizzleJournalTag: null },+ { plutonVersion: 'unknown', drizzleJournalTag: null }+ ).ok+ ).toBe(true);+ });++ it('does not compare journal tags when either side is missing one', () => {+ expect(+ checkVersionSkew({ plutonVersion: '1.0.0', drizzleJournalTag: '0099_x' }, {+ plutonVersion: '1.4.0',+ drizzleJournalTag: null,+ }).ok+ ).toBe(true);+ });+});++describe('isServerRunning', () => {+ const realFetch = global.fetch;+ afterEach(() => {+ global.fetch = realFetch;+ });++ it('reports running on any HTTP response, since deleting the DB under a live server is corruption', async () => {+ global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 200 }) as any;+ expect(await isServerRunning(5173)).toBe(true);+ });++ it('reports running even on a non-200, since something is still holding the port', async () => {+ global.fetch = jest.fn().mockResolvedValue({ ok: false, status: 503 }) as any;+ expect(await isServerRunning(5173)).toBe(true);+ });++ it('reports not running on ECONNREFUSED', async () => {+ global.fetch = jest.fn().mockRejectedValue(new Error('ECONNREFUSED')) as any;+ expect(await isServerRunning(5173)).toBe(false);+ });++ it('probes the unauthenticated health endpoint on loopback', async () => {+ const fetchMock = jest.fn().mockResolvedValue({ ok: true, status: 200 });+ global.fetch = fetchMock as any;+ await isServerRunning(9999);+ expect(fetchMock).toHaveBeenCalledWith(+ 'http://127.0.0.1:9999/api/health',+ expect.objectContaining({ signal: expect.anything() })+ );+ });+});++// The automated form of the design doc's "sqlite.close() on Windows" spike (§9): open a REAL+// WAL database with a real handle, then assert releaseDatabaseFiles closes it and clears the+// file plus both sidecars, rather than racing close() against unlink.+describe('releaseDatabaseFiles', () => {+ let tmp: string;+ let dbPath: string;++ beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pluton-dbrelease-'));+ dbPath = path.join(tmp, 'pluton.db');+ });++ afterEach(() => {+ fs.rmSync(tmp, { recursive: true, force: true });+ });++ // Open a WAL db and force a -wal (and -shm) into existence with an uncheckpointed write.+ const openWalDbWithSidecars = () => {+ const sqlite = new Database(dbPath);+ sqlite.pragma('journal_mode = WAL');+ sqlite.pragma('wal_autocheckpoint = 0'); // keep the write in -wal so the sidecar survives+ sqlite.exec('CREATE TABLE t (id INTEGER); INSERT INTO t (id) VALUES (1);');+ return sqlite;+ };++ it('closes the handle and clears pluton.db, -wal and -shm', async () => {+ const sqlite = openWalDbWithSidecars();+ expect(fs.existsSync(`${dbPath}-wal`)).toBe(true);++ await releaseDatabaseFiles(sqlite, dbPath);++ expect(sqlite.open).toBe(false);+ expect(fs.existsSync(dbPath)).toBe(false);+ expect(fs.existsSync(`${dbPath}-wal`)).toBe(false);+ expect(fs.existsSync(`${dbPath}-shm`)).toBe(false);+ });++ it('is a no-op on the sidecars when the DB was never in WAL mode', async () => {+ const sqlite = new Database(dbPath);+ sqlite.exec('CREATE TABLE t (id INTEGER);');++ await expect(releaseDatabaseFiles(sqlite, dbPath)).resolves.toBeUndefined();+ expect(fs.existsSync(dbPath)).toBe(false);+ });++ it('leaves nothing that could replay a stale WAL onto the restored DB', async () => {+ // The whole point of clearing the sidecars: a leftover -wal beside a fresh pluton.db+ // would replay onto it at next open. Assert the db dir holds no db artifacts afterward.+ const sqlite = openWalDbWithSidecars();+ await releaseDatabaseFiles(sqlite, dbPath);++ const leftovers = fs.readdirSync(tmp).filter(f => f.startsWith('pluton.db'));+ expect(leftovers).toEqual([]);+ });+});diff --git a/backend/__tests__/utils/selfBackup/blobFormat.test.ts b/backend/__tests__/utils/selfBackup/blobFormat.test.tsnew file mode 100644index 0000000..34a2541--- /dev/null+++ b/backend/__tests__/utils/selfBackup/blobFormat.test.ts@@ -0,0 +1,136 @@+import {+ sealBlob,+ openBlob,+ parseHeader,+ encodeHeader,+ BlobDecryptError,+ ARGON2_DEFAULTS,+ KDF_LIMITS,+ MAGIC,+ FORMAT_VERSION,+} from '../../../src/utils/selfBackup/blobFormat';++// No mocks: this module imports only node:crypto, by design.++const PASSWORD = 'correct horse battery staple';+const PAYLOAD = Buffer.from('a pretend tar payload with some bytes in it');++// argon2id at m=64MB is ~110ms per derivation, and most cases here derive twice.+jest.setTimeout(30000);++describe('blobFormat', () => {+ it('round-trips a payload through seal -> open', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ expect(openBlob(blob, PASSWORD)).toEqual(PAYLOAD);+ });++ it('produces a different blob each time (fresh salt and nonce)', () => {+ expect(sealBlob(PAYLOAD, PASSWORD).equals(sealBlob(PAYLOAD, PASSWORD))).toBe(false);+ });++ it('throws on the wrong key rather than returning garbage', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ expect(() => openBlob(blob, 'wrong-password')).toThrow(BlobDecryptError);+ });++ it('rejects a bad magic', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ blob.write('XXXX', 0, 4, 'ascii');+ expect(() => parseHeader(blob)).toThrow(/Not a Pluton backup blob/);+ });++ it('rejects an unknown format version', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ blob.writeUInt16BE(FORMAT_VERSION + 1, 4);+ expect(() => parseHeader(blob)).toThrow(/Unsupported blob format version/);+ });++ it('rejects a file too small to be a blob', () => {+ expect(() => parseHeader(Buffer.from('PLBK'))).toThrow(/too small/);+ });++ it('throws when a ciphertext byte is flipped', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ const { bodyOffset } = parseHeader(blob);+ blob[bodyOffset] ^= 0xff;+ expect(() => openBlob(blob, PASSWORD)).toThrow(BlobDecryptError);+ });++ it('throws when the auth tag is tampered with', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ blob[blob.length - 1] ^= 0xff;+ expect(() => openBlob(blob, PASSWORD)).toThrow(BlobDecryptError);+ });++ it('carries the kdf params in the header so a future KDF swap stays readable', () => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ const header = parseHeader(blob);+ expect(header.kdf).toEqual(ARGON2_DEFAULTS);+ expect(header.version).toBe(FORMAT_VERSION);+ expect(blob.toString('ascii', 0, 4)).toBe(MAGIC);+ });++ it('opens a blob using the params recorded in its header, not the current defaults', () => {+ const weakKdf = { memory: 8192, passes: 1, parallelism: 1 };+ const blob = sealBlob(PAYLOAD, PASSWORD, weakKdf);+ expect(parseHeader(blob).kdf).toEqual(weakKdf);+ expect(openBlob(blob, PASSWORD)).toEqual(PAYLOAD);+ });++ describe('kdf params from an untrusted header', () => {+ // The header is plaintext AND unauthenticated: it must be read, and the key derived from+ // it, before there is a key with which to check the GCM tag. So on any blob the user did+ // not write -- and --restore-pluton accepts an arbitrary file -- these are attacker+ // controlled, and act before there is anything to authenticate.+ const withKdfParam = (offset: number, value: number): Buffer => {+ const blob = sealBlob(PAYLOAD, PASSWORD);+ blob.writeUInt32BE(value, offset);+ return blob;+ };+ const MEMORY_OFFSET = 6;+ const PASSES_OFFSET = 10;+ const PARALLELISM_OFFSET = 14;++ it('refuses an absurd memory cost instead of asking argon2 for 4 TiB', () => {+ expect(() => parseHeader(withKdfParam(MEMORY_OFFSET, 0xffffffff))).toThrow(+ /unreasonable KDF memory cost/+ );+ });++ it('refuses an absurd pass count instead of hanging forever', () => {+ expect(() => parseHeader(withKdfParam(PASSES_OFFSET, 0xffffffff))).toThrow(+ /unreasonable KDF pass count/+ );+ });++ it('refuses an absurd parallelism', () => {+ expect(() => parseHeader(withKdfParam(PARALLELISM_OFFSET, 0xffffffff))).toThrow(+ /unreasonable KDF parallelism/+ );+ });++ it('refuses zeroed params', () => {+ expect(() => parseHeader(withKdfParam(MEMORY_OFFSET, 0))).toThrow(BlobDecryptError);+ expect(() => parseHeader(withKdfParam(PASSES_OFFSET, 0))).toThrow(BlobDecryptError);+ expect(() => parseHeader(withKdfParam(PARALLELISM_OFFSET, 0))).toThrow(BlobDecryptError);+ });++ it('leaves the defaults, and the limits themselves, comfortably in range', () => {+ // The ceilings must never reject a blob Pluton actually wrote, now or after a+ // params bump.+ expect(() => parseHeader(sealBlob(PAYLOAD, PASSWORD))).not.toThrow();+ expect(ARGON2_DEFAULTS.memory).toBeLessThan(KDF_LIMITS.maxMemory);+ expect(ARGON2_DEFAULTS.passes).toBeLessThan(KDF_LIMITS.maxPasses);+ expect(ARGON2_DEFAULTS.parallelism).toBeLessThan(KDF_LIMITS.maxParallelism);+ });+ });++ it('rejects a salt or nonce of the wrong length', () => {+ expect(() => encodeHeader(ARGON2_DEFAULTS, Buffer.alloc(8), Buffer.alloc(12))).toThrow(+ /salt must be 16 bytes/+ );+ expect(() => encodeHeader(ARGON2_DEFAULTS, Buffer.alloc(16), Buffer.alloc(8))).toThrow(+ /nonce must be 12 bytes/+ );+ });+});diff --git a/backend/__tests__/utils/selfBackup/payload.test.ts b/backend/__tests__/utils/selfBackup/payload.test.tsnew file mode 100644index 0000000..8154270--- /dev/null+++ b/backend/__tests__/utils/selfBackup/payload.test.ts@@ -0,0 +1,270 @@+import fs from 'fs';+import os from 'os';+import path from 'path';++// appPaths is an import-time singleton that mkdirSync's ~12 directories, so it must be+// mocked before anything that imports it loads.+let mockDataDir: string;++jest.mock('../../../src/utils/AppPaths', () => ({+ appPaths: {+ getDataDir: () => mockDataDir,+ getConfigDir: () => path.join(mockDataDir, 'config'),+ getDbDir: () => path.join(mockDataDir, 'db'),+ getProgressDir: () => path.join(mockDataDir, 'progress'),+ getSyncDir: () => path.join(mockDataDir, 'sync'),+ getSchedulesPath: () => path.join(mockDataDir, 'schedules.json'),+ getTempDir: () => path.join(mockDataDir, 'temp'),+ },+}));++import {+ packPayload,+ unpackPayload,+ computeFingerprint,+ assertSafeEntryPath,+ PAYLOAD_SPEC,+ DB_ENTRY,+ MANIFEST_ENTRY,+} from '../../../src/utils/selfBackup/payload';++const write = (rel: string, content = 'x') => {+ const abs = path.join(mockDataDir, rel);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, content);+ return abs;+};++/** A data dir with one of everything the spec knows about, plus things it must never take. */+function seedFullDataDir() {+ write('db/pluton.db', 'not-the-real-snapshot');+ write('config/rclone.conf', '[remote]');+ write('config/rclone_global.json', '{"transfers":8}');+ write('config/restic_global.json', '{"packSize":"16M"}');+ write('config/device_settings.json', '{"general":{}}');+ write('config/config.json', '{"APP_TITLE":"Pluton"}');+ write('config/self_backup_state.json', '{"lastSuccessAt":"2026-01-01T00:00:00Z"}');+ write('keys.json', '{"SECRET":"s"}');+ write('schedules.json', '[]');+ write('.activated', 'licensed');+ write('progress/run-1.json', '{"events":[]}');+ write('progress/nested/run-2.json', '{"events":[]}');+ write('sync/state.json', '{"ok":true}');+ write('sync/worker.lock', 'heartbeat');++ // Must never end up in the blob.+ write('stats/restore-1.json', 'x'.repeat(500));+ write('logs/app.log', 'noise');+ write('rescue/rear.iso', 'huge');+ write('pluton.enc.env', 'ENCRYPTION_KEY=hunter2hunter2');+ write('.setup_complete', '2026-01-01');+}++describe('payload', () => {+ let tmpDir: string;+ let snapshotPath: string;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'payload-'));+ mockDataDir = tmpDir;+ snapshotPath = path.join(tmpDir, 'snapshot.db');+ fs.writeFileSync(snapshotPath, 'pretend-vacuumed-sqlite');+ });++ afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ });++ async function packAndList(): Promise<{ entries: string[]; tar: Buffer }> {+ const tar = await packPayload({ dbSnapshotPath: snapshotPath, edition: 'core' });+ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'unpacked-'));+ const manifest = await unpackPayload(tar, destDir);+ const out = { entries: manifest.fileList, tar };+ fs.rmSync(destDir, { recursive: true, force: true });+ return out;+ }++ it('packs and unpacks, restoring file contents faithfully', async () => {+ seedFullDataDir();+ const tar = await packPayload({ dbSnapshotPath: snapshotPath, edition: 'core' });++ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'unpacked-'));+ try {+ await unpackPayload(tar, destDir);+ expect(fs.readFileSync(path.join(destDir, DB_ENTRY), 'utf-8')).toBe('pretend-vacuumed-sqlite');+ expect(fs.readFileSync(path.join(destDir, 'keys.json'), 'utf-8')).toBe('{"SECRET":"s"}');+ expect(fs.readFileSync(path.join(destDir, 'config/rclone.conf'), 'utf-8')).toBe('[remote]');+ expect(fs.readFileSync(path.join(destDir, 'progress/nested/run-2.json'), 'utf-8')).toBe(+ '{"events":[]}'+ );+ } finally {+ fs.rmSync(destDir, { recursive: true, force: true });+ }+ });++ it('includes exactly the spec entries that exist on disk', async () => {+ seedFullDataDir();+ const { entries } = await packAndList();++ expect(entries).toEqual(+ expect.arrayContaining([+ DB_ENTRY,+ 'config/rclone.conf',+ 'config/rclone_global.json',+ 'config/restic_global.json',+ 'config/device_settings.json',+ 'config/config.json',+ 'config/self_backup_state.json',+ 'keys.json',+ 'schedules.json',+ '.activated',+ 'progress/run-1.json',+ 'progress/nested/run-2.json',+ 'sync/state.json',+ ])+ );+ });++ it('never packs stats/, logs/, rescue/, pluton.enc.env or .setup_complete', async () => {+ seedFullDataDir();+ const { entries } = await packAndList();++ for (const forbidden of ['stats', 'logs', 'rescue', 'pluton.enc.env', '.setup_complete']) {+ expect(entries.some(e => e === forbidden || e.startsWith(`${forbidden}/`))).toBe(false);+ }+ });++ it('packs sync/*.json but skips sync/**/*.lock', async () => {+ seedFullDataDir();+ const { entries } = await packAndList();++ expect(entries).toContain('sync/state.json');+ expect(entries.some(e => e.endsWith('.lock'))).toBe(false);+ });++ it('skips a spec entry that does not exist on disk rather than throwing', async () => {+ // Only the DB snapshot exists, so every optional entry is absent.+ const { entries } = await packAndList();+ expect(entries).toEqual([DB_ENTRY]);+ });++ it('populates manifest.edition and the version-guard fields', async () => {+ seedFullDataDir();+ const tar = await packPayload({+ dbSnapshotPath: snapshotPath,+ edition: 'core',+ dbPageCount: 42,+ });+ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'unpacked-'));+ try {+ const manifest = await unpackPayload(tar, destDir);+ expect(manifest.edition).toBe('core');+ expect(manifest.dbPageCount).toBe(42);+ expect(manifest.hostname).toBeTruthy();+ expect(manifest.createdAt).toBeTruthy();+ expect(manifest).toHaveProperty('plutonVersion');+ expect(manifest).toHaveProperty('drizzleJournalTag');+ expect(fs.existsSync(path.join(destDir, MANIFEST_ENTRY))).toBe(true);+ } finally {+ fs.rmSync(destDir, { recursive: true, force: true });+ }+ });++ it('every spec entry is optional, so the spec is a pure include list', () => {+ // Guards the structural property: nothing in the spec reaches outside the data dir.+ for (const spec of PAYLOAD_SPEC) {+ expect(spec.source()).toContain(mockDataDir);+ }+ });++ describe('assertSafeEntryPath', () => {+ it('accepts a normal nested entry', () => {+ expect(assertSafeEntryPath('config/rclone.conf', tmpDir)).toBe(+ path.resolve(tmpDir, 'config/rclone.conf')+ );+ });++ it('rejects ../ traversal', () => {+ expect(() => assertSafeEntryPath('../../etc/whatever', tmpDir)).toThrow(/escapes/);+ expect(() => assertSafeEntryPath('config/../../evil', tmpDir)).toThrow(/escapes/);+ });++ it('rejects absolute paths', () => {+ expect(() => assertSafeEntryPath('/etc/passwd', tmpDir)).toThrow(/absolute path/);+ expect(() => assertSafeEntryPath('C:\\Windows\\evil', tmpDir)).toThrow(/absolute path/);+ });+ });++ it('unpackPayload rejects a tar entry that escapes the destination', async () => {+ const { pack } = await import('tar-stream');+ const tarPack = pack();+ const chunks: Buffer[] = [];+ tarPack.on('data', (c: Buffer) => chunks.push(c));+ const evil = Buffer.from('pwned');+ tarPack.entry({ name: '../escaped.txt', size: evil.length }, evil);+ tarPack.finalize();+ await new Promise(resolve => tarPack.on('end', resolve));++ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'unpacked-'));+ try {+ await expect(unpackPayload(Buffer.concat(chunks), destDir)).rejects.toThrow(/escapes/);+ expect(fs.existsSync(path.join(path.dirname(destDir), 'escaped.txt'))).toBe(false);+ } finally {+ fs.rmSync(destDir, { recursive: true, force: true });+ }+ });++ it('rejects a payload with no manifest', async () => {+ const { pack } = await import('tar-stream');+ const tarPack = pack();+ const chunks: Buffer[] = [];+ tarPack.on('data', (c: Buffer) => chunks.push(c));+ const body = Buffer.from('db');+ tarPack.entry({ name: DB_ENTRY, size: body.length }, body);+ tarPack.finalize();+ await new Promise(resolve => tarPack.on('end', resolve));++ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'unpacked-'));+ try {+ await expect(unpackPayload(Buffer.concat(chunks), destDir)).rejects.toThrow(/manifest/);+ } finally {+ fs.rmSync(destDir, { recursive: true, force: true });+ }+ });++ describe('computeFingerprint', () => {+ it('is stable across calls when nothing changes', () => {+ seedFullDataDir();+ expect(computeFingerprint()).toBe(computeFingerprint());+ });++ it('changes when a tracked file changes size', () => {+ seedFullDataDir();+ const before = computeFingerprint();+ write('config/rclone.conf', '[remote]\n[another]');+ expect(computeFingerprint()).not.toBe(before);+ });++ it('changes when a tracked file changes mtime', () => {+ seedFullDataDir();+ const before = computeFingerprint();+ const future = new Date(Date.now() + 60_000);+ fs.utimesSync(path.join(mockDataDir, 'db/pluton.db'), future, future);+ expect(computeFingerprint()).not.toBe(before);+ });++ it('changes when a tracked file appears', () => {+ write('db/pluton.db', 'db');+ const before = computeFingerprint();+ write('config/config.json', '{}');+ expect(computeFingerprint()).not.toBe(before);+ });++ it('ignores untracked noise like logs/', () => {+ seedFullDataDir();+ const before = computeFingerprint();+ write('logs/app.log', 'a lot more noise than before');+ expect(computeFingerprint()).toBe(before);+ });+ });+});diff --git a/backend/package.json b/backend/package.jsonindex 1072ee0..f22599d 100644--- a/backend/package.json+++ b/backend/package.json@@ -37,6 +37,7 @@"pino": "^9.6.0","qrcode": "^1.5.4","systeminformation": "^5.31.0",+ "tar-stream": "^3.1.7","tsx": "^4.21.0","zod": "^4.1.12"},@@ -55,6 +56,7 @@"@types/pg": "^8.11.11","@types/qrcode": "^1.5.6","@types/supertest": "^6.0.3",+ "@types/tar-stream": "^3.1.4","concurrently": "^9.1.2","cross-env": "^10.0.0","dotenv": "17.2.0",diff --git a/backend/src/controllers/SettingsController.ts b/backend/src/controllers/SettingsController.tsindex 3e49f70..501c0b3 100644--- a/backend/src/controllers/SettingsController.ts+++ b/backend/src/controllers/SettingsController.ts@@ -1,4 +1,5 @@import { Request, Response } from 'express';+import { createReadStream } from 'fs';import { SettingsService } from '../services/SettingsService';import { AppSettings, IntegrationTypes } from '../types/settings';@@ -210,6 +211,78 @@ export class SettingsController {}}+ async getSelfBackupStatus(req: Request, res: Response): Promise<void> {+ try {+ const status = await this.settingsService.getSelfBackupStatus();+ res.status(200).json({ success: true, result: status });+ } catch (error: any) {+ res.status(error.statusCode || 500).json({+ success: false,+ error: error instanceof Error ? error.message : 'Failed to get Pluton backup status',+ });+ }+ }++ async listSelfBackups(req: Request, res: Response): Promise<void> {+ try {+ const backups = await this.settingsService.listSelfBackups();+ res.status(200).json({ success: true, result: backups });+ } catch (error: any) {+ res.status(error.statusCode || 500).json({+ success: false,+ error: error instanceof Error ? error.message : 'Failed to list Pluton backups',+ });+ }+ }++ async downloadSelfBackup(req: Request, res: Response): Promise<void> {+ const blobName = req.params.blobName;+ if (!blobName) {+ res.status(400).json({ success: false, error: 'Backup name is required' });+ return;+ }++ try {+ const { localPath, cleanup } = await this.settingsService.downloadSelfBackup(blobName);++ res.setHeader('Content-Type', 'application/octet-stream');+ res.setHeader('Content-Disposition', `attachment; filename="${blobName}"`);++ const fileStream = createReadStream(localPath);+ // The temp copy lives only for this response; remove it once the socket is done+ // either way (finish = fully sent, close = client aborted).+ res.on('finish', () => void cleanup());+ res.on('close', () => void cleanup());+ fileStream.on('error', () => {+ void cleanup();+ if (!res.headersSent) {+ res.status(500).json({ success: false, error: 'Failed to read backup file' });+ } else {+ res.destroy();+ }+ });+ fileStream.pipe(res);+ } catch (error: any) {+ res.status(error.statusCode || 500).json({+ success: false,+ error: error instanceof Error ? error.message : 'Failed to download Pluton backup',+ });+ }+ }++ async runSelfBackup(req: Request, res: Response): Promise<void> {+ try {+ await this.settingsService.runSelfBackupNow();+ // 202: the job is queued, not done. The UI polls the status endpoint.+ res.status(202).json({ success: true, result: 'Pluton backup queued.' });+ } catch (error: any) {+ res.status(error.statusCode || 500).json({+ success: false,+ error: error instanceof Error ? error.message : 'Failed to queue Pluton backup',+ });+ }+ }+async checkLatestVersion(req: Request, res: Response): Promise<void> {try {const latestVersion = await this.settingsService.checkLatestVersion();diff --git a/backend/src/createApp.ts b/backend/src/createApp.tsindex 651a723..001360b 100644--- a/backend/src/createApp.ts+++ b/backend/src/createApp.ts@@ -7,7 +7,7 @@ import session from 'express-session';import createMemoryStore from 'memorystore';import helmet from 'helmet';import rateLimit from 'express-rate-limit';-import { db } from './db';+import { db, sqlite } from './db';import { createPlanRouter } from './routes/plans';import { createDeviceRouter } from './routes/devices';import { createStorageRouter } from './routes/storages';@@ -47,9 +47,11 @@ import { BaseSystemManager } from './managers/BaseSystemManager';import { BaseStorageManager } from './managers/BaseStorageManager';import { StorageService } from './services/StorageService';import { SettingsService } from './services/SettingsService';+import { SelfBackupService } from './services/SelfBackupService';import { SystemTaskManager } from './jobs/SystemTaskManager';import { SYSTEM_JOBS } from './jobs/systemJobs';import { jobProcessor } from './jobs/JobProcessor';+import { SelfBackupTask } from './jobs/tasks/SelfBackupTask';import { initializeLogger } from './utils/logger';import { configService } from './services/ConfigService';import { BaseRestoreManager } from './managers/BaseRestoreManager';@@ -110,9 +112,11 @@ export async function createApp(): Promise<{ app: Express }> {localStorageAgent,localSystemAgent,storageStore,- planStore+ planStore,+ settingsStore);- const settingsService = new SettingsService(settingsStore);+ const selfBackupService = new SelfBackupService(settingsStore, storageStore, sqlite, 'core');+ const settingsService = new SettingsService(settingsStore, selfBackupService);// API Route Controllersconst planController = new PlanController(planService);@@ -261,6 +265,9 @@ export async function createApp(): Promise<{ app: Express }> {restoreManager: localRestoreAgent,});+ // Self Backup Task+ jobProcessor.addTask(new SelfBackupTask(selfBackupService));+jobProcessor.start();return { app };diff --git a/backend/src/db/index.ts b/backend/src/db/index.tsindex 5360950..0c91771 100644--- a/backend/src/db/index.ts+++ b/backend/src/db/index.ts@@ -1,5 +1,5 @@import { drizzle } from 'drizzle-orm/better-sqlite3';-import Database from 'better-sqlite3';+import Database, { type Database as SqliteDatabase } from 'better-sqlite3';import path from 'path';import { plans, plansRelations } from './schema/plans';import { storageRelations, storages } from './schema/storages';@@ -10,7 +10,8 @@ import { settings } from './schema/settings';import { appPaths } from '../utils/AppPaths';const dbPath = path.join(appPaths.getDbDir(), 'pluton.db');-const sqlite = new Database(dbPath);+export const sqlite: SqliteDatabase = new Database(dbPath);+export const dbFilePath = dbPath;sqlite.pragma('journal_mode = WAL');export const db = drizzle(sqlite, {diff --git a/backend/src/index.ts b/backend/src/index.tsindex 6c826ff..fb638f1 100644--- a/backend/src/index.ts+++ b/backend/src/index.ts@@ -2,7 +2,7 @@ import './types/process.d.ts';import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';import { migrate } from 'drizzle-orm/better-sqlite3/migrator';import { createApp } from './createApp';-import { db } from './db';+import { db, sqlite, dbFilePath } from './db';import { initSetup } from './utils/initSetup';import { configService, ConfigService } from './services/ConfigService';import { requiresDesktopSetup } from './utils/installHelpers';@@ -15,21 +15,34 @@ export { configService } from './services/ConfigService';// This block only runs when this file is executed directly (e.g., npm run dev or packaged executable)// Always run when imported as the main entry point-import path from 'path';import fs from 'fs';+import { getMigrationsFolder, getMigrationsJournalPath } from './utils/migrations';+import { CLI_COMMAND_FLAGS } from './utils/cliCommands';const isMainModule = import.meta.url === `file://${process.argv[1]}` || (process as any).pkg;const isDevelopment = process.env.NODE_ENV === 'development';if (isMainModule || isDevelopment) {(async () => {+ // These flags are also what lets ConfigService skip its server-credential fail-fast+ // at import time, so both sides read the same list. See utils/cliCommands.ts.+ const [RESET_PASSWORD_FLAG, RESTORE_PLUTON_FLAG] = CLI_COMMAND_FLAGS;+// Handle --reset-password CLI command (runs and exits, does not start server)- if (process.argv.includes('--reset-password')) {+ if (process.argv.includes(RESET_PASSWORD_FLAG)) {const { handlePasswordReset } = await import('./utils/cliPasswordReset');await handlePasswordReset();return; // handlePasswordReset calls process.exit(), but just in case}+ // Handle --restore-pluton CLI command (runs and exits, does not start server).+ // Must run before migrations, initSetup and listen. It replaces the whole data dir.+ if (process.argv.includes(RESTORE_PLUTON_FLAG)) {+ const { handleSelfRestore } = await import('./utils/cliSelfRestore');+ await handleSelfRestore({ sqlite, dbFilePath, edition: 'core' });+ return;+ }+// For binary installations on desktop platforms, try to load credentials from env file or keyringif (requiresDesktopSetup() && configService.isSetupPending()) {console.log('Attempting to load credentials from env file or system keyring...');@@ -45,13 +58,10 @@ if (isMainModule || isDevelopment) {if (process.env.NODE_ENV === 'production') {console.log('Running database migrations...');try {- const migrationsFolder =- process.env.IS_DOCKER === 'true'- ? '/app/drizzle'- : path.join(path.dirname(process.execPath), 'drizzle');+ const migrationsFolder = getMigrationsFolder();// Check if migrations exist- const journalPath = path.join(migrationsFolder, 'meta', '_journal.json');+ const journalPath = getMigrationsJournalPath(migrationsFolder);if (!fs.existsSync(journalPath)) {console.log('No migrations found (meta/_journal.json missing), skipping...');} else {diff --git a/backend/src/jobs/JobQueue.ts b/backend/src/jobs/JobQueue.tsindex 54ba4c5..72b1ac5 100644--- a/backend/src/jobs/JobQueue.ts+++ b/backend/src/jobs/JobQueue.ts@@ -72,6 +72,13 @@ class JobQueue {return this.runningJob;}+ /**+ * Whether a job of this name is queued or currently running.+ */+ public hasPending(jobName: string): boolean {+ return this.runningJob?.name === jobName || this.queue.some(job => job.name === jobName);+ }+/*** Marks the currently running job as complete.*/diff --git a/backend/src/jobs/systemJobs.ts b/backend/src/jobs/systemJobs.tsindex 20a83b2..a59ed0d 100644--- a/backend/src/jobs/systemJobs.ts+++ b/backend/src/jobs/systemJobs.ts@@ -1,5 +1,7 @@import { SystemJobConfig } from '../types/global';+export const SELF_BACKUP_JOB_NAME = 'SelfBackup';+export const SYSTEM_JOBS: SystemJobConfig[] = [{name: 'CleanDownloads',@@ -7,6 +9,12 @@ export const SYSTEM_JOBS: SystemJobConfig[] = [maxAttempts: 2,retryDelay: 300000,},+ {+ name: SELF_BACKUP_JOB_NAME,+ schedule: '0 * * * *',+ maxAttempts: 3,+ retryDelay: 600000,+ },// {// name: 'PruneDatabase',// schedule: '0 3 * * *', // Every day at 3:00 AM@@ -20,3 +28,5 @@ export const SYSTEM_JOBS: SystemJobConfig[] = [// },// Add other system jobs here];++export const CORE_SYSTEM_JOBS = SYSTEM_JOBS;diff --git a/backend/src/jobs/tasks/SelfBackupTask.ts b/backend/src/jobs/tasks/SelfBackupTask.tsnew file mode 100644index 0000000..5baf70a--- /dev/null+++ b/backend/src/jobs/tasks/SelfBackupTask.ts@@ -0,0 +1,27 @@+import { Task } from './AbstractTask';+import { cronLogger } from '../../utils/logger';+import { Job } from '../JobQueue';+import { SELF_BACKUP_JOB_NAME } from '../systemJobs';+import { SelfBackupService } from '../../services/SelfBackupService';++/**+ * Ticks hourly and gates on `intervalHours` from settings.+ */+export class SelfBackupTask extends Task {+ name = SELF_BACKUP_JOB_NAME;++ constructor(private selfBackupService: SelfBackupService) {+ super();+ }++ async run(job?: Job): Promise<void> {+ const force = job?.payload?.force === true;++ if (!force && !(await this.selfBackupService.isDue())) {+ return;+ }++ const result = await this.selfBackupService.run({ force });+ cronLogger.info(`[SelfBackup] Run finished with status: ${result.status}`);+ }+}diff --git a/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.ejs b/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.ejsnew file mode 100644index 0000000..39490c8--- /dev/null+++ b/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.ejs@@ -0,0 +1,71 @@+<div>+ <div class="center">+ <h2 class="title title-error">+ <img+ width="16"+ height="16"+ src="https://pluton.b-cdn.net/email/cross-red.png"+ style="vertical-align: middle"+ />+ Pluton Backup Failed+ </h2>+ </div>+ <!-- Basic ERROR Info -->+ <div class="backupError">+ <span class="backupErrorTitle"+ ><i class="img-icon">+ <img+ width="14"+ height="14"+ src="https://pluton.b-cdn.net/email/warning-red.png"+ style="vertical-align: middle"+ />+ </i>+ <strong>Self-Backup Failed</strong></span+ >+ <p>+ <%= appTitle %> could not back up its own configuration. Until this is resolved, your+ plans, storages and credentials are not being protected.+ </p>+ <p>Error: <%= error %></p>+ </div>++ <!-- Basic Summary Info -->+ <div class="backupDateTime">+ <table role="presentation" cellpadding="0" cellspacing="0">+ <% if (storageName) { %>+ <tr class="backupSummary_date">+ <td style="text-align: left">Storage:</td>+ <td style="text-align: right"><strong><%= storageName %></strong></td>+ </tr>+ <% } %>+ <% if (hostname) { %>+ <tr class="backupSummary_date">+ <td style="text-align: left">Host:</td>+ <td style="text-align: right"><strong><%= hostname %></strong></td>+ </tr>+ <% } %>+ <tr class="backupSummary_date">+ <td style="text-align: left">+ <img+ width="11"+ height="11"+ src="https://pluton.b-cdn.net/email/cross.png"+ style="vertical-align: middle"+ />+ Failed At:+ </td>+ <td style="text-align: right"><%= failedAt %></td>+ </tr>+ </table>+ </div>++ <!-- Notification Settings Info -->+ <div class="center notificationMsg">+ <p>+ You are receiving this email because failure notifications are enabled for Pluton's+ self-backup. You can change this in+ <a href="<%= appUrl %>/settings">Settings</a>.+ </p>+ </div>+</div>diff --git a/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.ts b/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.tsnew file mode 100644index 0000000..d868f26--- /dev/null+++ b/backend/src/notifications/templates/email/backup/SelfBackupFailedNotification.ts@@ -0,0 +1,50 @@+import ejs from 'ejs';+import { configService } from '../../../../services/ConfigService';+import { BaseNotification } from '../../../BaseNotification';+import { loadBackupTemplate } from '../../../templateLoader';++export interface SelfBackupFailedNotificationPayload {+ appTitle: string;+ error: string;+ hostname?: string;+ storageName?: string;+ /** When the run failed. Defaults to now if omitted. */+ failedAt?: Date;+}++/**+ * Emailed to the admin when Pluton's own self-backup run fails, if the failure-notification+ * toggle is enabled. Email-only: unlike the plan notifications this never fans out to push+ * or chat channels, so only the HTML body is built.+ */+export class SelfBackupFailedNotification extends BaseNotification {+ constructor(data: SelfBackupFailedNotificationPayload) {+ super();+ this.type = 'error';+ this.subject = `${data.appTitle || 'Pluton'} Self-Backup Failed`;+ this.content = this.buildContent(data);+ }++ protected buildContent(data: SelfBackupFailedNotificationPayload): string {+ const failedAt = new Date(data.failedAt ?? Date.now()).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ });++ const templateString = loadBackupTemplate('SelfBackupFailedNotification.ejs');+ const renderedBody = ejs.render(templateString, {+ ...data,+ appUrl: configService.config.APP_URL || '',+ failedAt,+ });++ return this.applyEmailTemplate(renderedBody, {+ appTitle: data.appTitle || configService.config.APP_TITLE || 'Pluton',+ preHeader: `${data.appTitle || 'Pluton'} could not back up its own configuration.`,+ className: 'content--error',+ });+ }+}diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.tsindex 00794a3..ef6b90b 100644--- a/backend/src/routes/settings.ts+++ b/backend/src/routes/settings.ts@@ -13,6 +13,14 @@ export function createSettingsRouter(router.get('/:id/logs/download', authM, controller.downloadAppLogs.bind(controller));router.post('/:id/2fa/setup', authM, controller.setupTwoFactorAuth.bind(controller));router.post('/:id/2fa/finalize', authM, controller.finalizeTwoFactorSetup.bind(controller));+ router.get('/:id/self-backup/status', authM, controller.getSelfBackupStatus.bind(controller));+ router.post('/:id/self-backup/run', authM, controller.runSelfBackup.bind(controller));+ router.get('/:id/self-backup/backups', authM, controller.listSelfBackups.bind(controller));+ router.get(+ '/:id/self-backup/backups/:blobName/download',+ authM,+ controller.downloadSelfBackup.bind(controller)+ );// Misc Routesrouter.post('/integration/validate', authM, controller.validateIntegration.bind(controller));diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.tsindex a9dca93..fc3b125 100644--- a/backend/src/services/ConfigService.ts+++ b/backend/src/services/ConfigService.ts@@ -3,10 +3,8 @@ 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 { isCliCommandInvocation } from '../utils/cliCommands';+import { readEncryptionKeyFromEnvFile, verifyFilePermissions } from '../utils/envFileHelpers';import { credentialManager } from './CredentialManager';// Schema for the .env config file (with optional sensitive fields for setup mode)@@ -195,10 +193,21 @@ class ConfigService {if (!parsedConfig.success) {// Check if we're in binary mode on a desktop platform// In this case, we can start in "setup pending" mode- if (requiresDesktopSetup()) {- console.log('⏳ [ConfigService] Binary mode detected without credentials.');- console.log('⏳ [ConfigService] Starting in setup pending mode...');- console.log('⏳ [ConfigService] Please complete the initial setup via the web interface.');+ //+ // CLI commands (--restore-pluton, --reset-password) take the same branch: they do+ // their work and exit without ever booting the app, so the server's credential+ // requirements dont apply to them. Exiting here would make them unreachable on docker/server installs+ const isCliCommand = isCliCommandInvocation();+ if (requiresDesktopSetup() || isCliCommand) {+ if (isCliCommand) {+ console.log('[ConfigService] Running a CLI command without full server credentials.');+ } else {+ console.log('⏳ [ConfigService] Binary mode detected without credentials.');+ console.log('⏳ [ConfigService] Starting in setup pending mode...');+ console.log(+ '⏳ [ConfigService] Please complete the initial setup via the web interface.'+ );+ }// Create a setup-mode config with placeholder valuesthis._isSetupPending = true;@@ -211,7 +220,9 @@ class ConfigService {SETUP_PENDING: true,} as SetupModeConfig;- console.log('⏳ Environment configuration loaded in SETUP PENDING mode.');+ if (!isCliCommand) {+ console.log('⏳ Environment configuration loaded in SETUP PENDING mode.');+ }return;}diff --git a/backend/src/services/SelfBackupService.ts b/backend/src/services/SelfBackupService.tsnew file mode 100644index 0000000..7a5dfd1--- /dev/null+++ b/backend/src/services/SelfBackupService.ts@@ -0,0 +1,347 @@+import fsp from 'fs/promises';+import os from 'os';+import path from 'path';+import type { Database as SqliteDatabase } from 'better-sqlite3';+import { SettingsStore } from '../stores/SettingsStore';+import { StorageStore } from '../stores/StorageStore';+import { appPaths } from '../utils/AppPaths';+import { cronLogger } from '../utils/logger';+import { configService } from './ConfigService';+import { sealBlob } from '../utils/selfBackup/blobFormat';+import { packPayload, computeFingerprint, PlutonEdition } from '../utils/selfBackup/payload';+import { readSelfBackupState, writeSelfBackupState } from '../utils/selfBackup/state';+import { resolveSelfBackup } from '../utils/selfBackup/settings';+import { rcloneCopyTo, rcloneDeleteFile, rcloneLsJson } from '../utils/rclone/helpers';+import { jobQueue } from '../jobs/JobQueue';+import { SELF_BACKUP_JOB_NAME } from '../jobs/systemJobs';+import { AppError } from '../utils/AppError';+import { IntegrationTypes, SelfBackupSettings } from '../types/settings';+import { NotificationChannelResolver } from '../notifications/channels/NotificationChannelResolver';+import { SelfBackupFailedNotification } from '../notifications/templates/email/backup/SelfBackupFailedNotification';++const RCLONE_TIMEOUT_MS = 120_000;++const BLOB_PREFIX = 'pluton-';+const BLOB_SUFFIX = '.pluton';+const BLOB_NAME_RE = /^pluton-.*\.pluton$/;+const SIDECAR_NAME = 'pluton-recovery.json';++export type SelfBackupRunStatus = 'disabled' | 'skipped' | 'uploaded';++export interface SelfBackupRunResult {+ status: SelfBackupRunStatus;+ blobName?: string;+}++export interface SelfBackupBlob {+ name: string;+ size: number;+ modTime?: string;+}++export interface SelfBackupStatus extends SelfBackupSettings {+ lastRunAt?: string;+ lastSuccessAt?: string;+ lastError?: string | null;+ lastBlobName?: string;+ running: boolean;+}++export class SelfBackupService {+ constructor(+ protected settingsStore: SettingsStore,+ protected storageStore: StorageStore,+ protected sqlite: SqliteDatabase,+ protected edition: PlutonEdition+ ) {}++ protected async resolveSettings(): Promise<SelfBackupSettings> {+ const settingsRow = await this.settingsStore.getFirst();+ return resolveSelfBackup(settingsRow?.settings);+ }++ async getStatus(): Promise<SelfBackupStatus> {+ const settings = await this.resolveSettings();+ const state = readSelfBackupState();+ return {+ ...settings,+ lastRunAt: state.lastRunAt,+ lastSuccessAt: state.lastSuccessAt,+ lastError: state.lastError,+ lastBlobName: state.lastBlobName,+ running: jobQueue.hasPending(SELF_BACKUP_JOB_NAME),+ };+ }++ /**+ * Interval gate. SYSTEM_JOBS is a static array read once at startup, so a+ * user-configurable interval can't be a cron expression. The task ticks hourly+ * and asks this instead.+ */+ async isDue(): Promise<boolean> {+ const settings = await this.resolveSettings();+ if (!settings.enabled) return false;++ const { lastSuccessAt } = readSelfBackupState();+ if (!lastSuccessAt) return true;++ const elapsedMs = Date.now() - new Date(lastSuccessAt).getTime();+ return elapsedMs >= settings.intervalHours * 60 * 60 * 1000;+ }++ async run(opts: { force?: boolean } = {}): Promise<SelfBackupRunResult> {+ const settings = await this.resolveSettings();+ if (!settings.enabled) {+ return { status: 'disabled' };+ }++ const fingerprint = computeFingerprint();+ if (!opts.force && fingerprint === readSelfBackupState().lastFingerprint) {+ cronLogger.info('[SelfBackup] Nothing changed since the last upload. Skipping.');+ const skippedAt = new Date().toISOString();+ writeSelfBackupState({ lastRunAt: skippedAt, lastSuccessAt: skippedAt, lastError: null });+ return { status: 'skipped' };+ }++ // The name is user-editable after save, so the zod check at save time isn't enough.+ const remoteName = await this.resolveRemoteName(settings);++ const tmpDir = await fsp.mkdtemp(path.join(appPaths.getTempDir(), 'self-backup-'));+ try {+ const blobName = `${BLOB_PREFIX}${new Date().toISOString().replace(/[:.]/g, '-')}${BLOB_SUFFIX}`;+ const snapshotPath = path.join(tmpDir, 'pluton.db');++ const dbPageCount = this.vacuumInto(snapshotPath);+ const tar = await packPayload({+ dbSnapshotPath: snapshotPath,+ edition: this.edition,+ dbPageCount,+ });+ const blob = sealBlob(tar, configService.config.ENCRYPTION_KEY);++ const blobPath = path.join(tmpDir, blobName);+ await fsp.writeFile(blobPath, blob, { mode: 0o600 });++ const destDir = this.remoteDir(remoteName, settings.path);+ await rcloneCopyTo(blobPath, this.remoteFile(destDir, blobName), undefined, {+ timeoutMs: RCLONE_TIMEOUT_MS,+ });++ await this.uploadSidecar(tmpDir, destDir, blobName);+ await this.applyRetention(destDir, settings.retention);++ const finishedAt = new Date().toISOString();+ writeSelfBackupState({+ lastRunAt: finishedAt,+ lastSuccessAt: finishedAt,+ lastError: null,+ lastFingerprint: fingerprint,+ lastBlobName: blobName,+ });++ cronLogger.info(`[SelfBackup] Uploaded ${blobName} (${blob.length} bytes) to ${destDir}`);+ return { status: 'uploaded', blobName };+ } catch (error: any) {+ // Throw: JobQueue retries, and a silent failure here is only discovered during a disaster.+ writeSelfBackupState({+ lastRunAt: new Date().toISOString(),+ lastError: error?.message || 'Unknown error',+ });+ cronLogger.error(`[SelfBackup] Backup failed: ${error?.message}`);+ await this.notifyFailure(error);+ throw error;+ } finally {+ await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {});+ }+ }++ /**+ * Email the admin when a run fails, if the failure-notification toggle is on and an email+ * integration is connected. Wrapped so a notification problem can never mask or replace the+ * original backup error.+ */+ protected async notifyFailure(error: any): Promise<void> {+ try {+ const settingsRow = await this.settingsStore.getFirst();+ const appSettings = settingsRow?.settings;+ const selfBackup = resolveSelfBackup(appSettings);+ if (!selfBackup.notifyOnFailure) return;++ const adminEmail = appSettings?.admin_email;+ if (!adminEmail) {+ cronLogger.warn('[SelfBackup] Failure notification is on but no admin email is set.');+ return;+ }++ const integration = appSettings?.integration ?? {};+ const emailTypes: IntegrationTypes[] = [+ 'smtp',+ 'sendgrid',+ 'mailgun',+ 'brevo',+ 'resend',+ 'awsSes',+ ];+ const channelType = emailTypes.find(type => integration[type]?.connected);+ if (!channelType) {+ cronLogger.warn(+ '[SelfBackup] Failure notification is on but no email integration is connected.'+ );+ return;+ }++ const channel = await NotificationChannelResolver.getChannel(channelType);+ const notification = new SelfBackupFailedNotification({+ appTitle: appSettings?.title || 'Pluton',+ error: error?.message || 'Unknown error',+ hostname: os.hostname(),+ storageName: selfBackup.storageName,+ failedAt: new Date(),+ });+ const res = await channel.send(notification, { emails: adminEmail });+ if (!res?.success) {+ cronLogger.error(`[SelfBackup] Failure notification email failed: ${res?.result}`);+ } else {+ cronLogger.info('[SelfBackup] Failure notification email sent to admin.');+ }+ } catch (err: any) {+ cronLogger.error(`[SelfBackup] Could not send failure notification: ${err?.message}`);+ }+ }++ /**+ * A read-transaction snapshot: everything committed to the WAL at this instant, in a+ * fresh checkpointed standalone file with no -wal beside it. Never a raw file copy,+ * which is either stale (main file only) or torn (main + wal under a live writer).+ *+ * Refuses an existing destination, hence the mkdtemp + unique name from the caller.+ */+ protected vacuumInto(destPath: string): number {+ let pageCount = 0;+ try {+ const row = this.sqlite.pragma('page_count', { simple: true });+ pageCount = typeof row === 'number' ? row : 0;+ } catch {+ pageCount = 0;+ }+ this.sqlite.prepare('VACUUM INTO ?').run(destPath);+ return pageCount;+ }++ protected async resolveRemoteName(settings: SelfBackupSettings): Promise<string> {+ const storage = await this.storageStore.getById(settings.storageId);+ if (!storage) {+ throw new AppError(+ 400,+ `The storage selected for Pluton backup no longer exists (id: ${settings.storageId}).`+ );+ }+ return storage.name;+ }++ protected remoteDir(remoteName: string, targetPath: string): string {+ const cleaned = targetPath.replace(/^\/+|\/+$/g, '');+ return `${remoteName}:${cleaned}`;+ }++ /**+ * Join a filename onto a remote dir.+ *+ * An empty configured path makes destDir `remote:`, and a naive `${destDir}/${name}`+ * would yield `remote:/name`, a leading slash that means the filesystem root on a+ * local remote rather than the remote's own root.+ */+ protected remoteFile(destDir: string, fileName: string): string {+ return destDir.endsWith(':') ? `${destDir}${fileName}` : `${destDir}/${fileName}`;+ }++ /**+ * Lets `--list` say "a backup from this morning, host nas-01" rather than making the+ * user know a path. No secrets in it.+ */+ protected async uploadSidecar(tmpDir: string, destDir: string, blobName: string): Promise<void> {+ const sidecar = {+ hostname: os.hostname(),+ plutonVersion: process.env.APP_VERSION || 'unknown',+ edition: this.edition,+ updatedAt: new Date().toISOString(),+ latestBlob: blobName,+ };+ const sidecarPath = path.join(tmpDir, SIDECAR_NAME);+ await fsp.writeFile(sidecarPath, JSON.stringify(sidecar, null, 2));+ await rcloneCopyTo(sidecarPath, this.remoteFile(destDir, SIDECAR_NAME), undefined, {+ timeoutMs: RCLONE_TIMEOUT_MS,+ });+ }++ /**+ * List the backup blobs currently on the configured storage+ */+ async listBackups(): Promise<SelfBackupBlob[]> {+ const settings = await this.resolveSettings();+ if (!settings.storageId) return [];++ const remoteName = await this.resolveRemoteName(settings);+ const destDir = this.remoteDir(remoteName, settings.path);+ const items = await rcloneLsJson(destDir, undefined, { timeoutMs: RCLONE_TIMEOUT_MS });+ return items+ .filter(item => !item.IsDir && BLOB_NAME_RE.test(item.Name))+ .map(item => ({ name: item.Name, size: item.Size, modTime: item.ModTime }))+ .sort((a, b) => b.name.localeCompare(a.name));+ }++ /**+ * Copy a single backup blob down to a local temp file for streaming to the client.+ */+ async downloadBackup(+ blobName: string+ ): Promise<{ localPath: string; cleanup: () => Promise<void> }> {+ if (!BLOB_NAME_RE.test(blobName)) {+ throw new AppError(400, 'Invalid backup name.');+ }++ const settings = await this.resolveSettings();+ const remoteName = await this.resolveRemoteName(settings);+ const destDir = this.remoteDir(remoteName, settings.path);++ const tmpDir = await fsp.mkdtemp(path.join(appPaths.getTempDir(), 'self-backup-dl-'));+ const localPath = path.join(tmpDir, blobName);+ try {+ await rcloneCopyTo(this.remoteFile(destDir, blobName), localPath, undefined, {+ timeoutMs: RCLONE_TIMEOUT_MS,+ });+ } catch (error) {+ await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {});+ throw error;+ }++ return {+ localPath,+ cleanup: () => fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {}),+ };+ }++ /** Failures here are logged and swallowed, since the blob is already safely uploaded. */+ protected async applyRetention(destDir: string, retention: number): Promise<void> {+ try {+ const items = await rcloneLsJson(destDir, undefined, { timeoutMs: RCLONE_TIMEOUT_MS });+ const blobs = items+ .filter(item => !item.IsDir && BLOB_NAME_RE.test(item.Name))+ // Names are ISO timestamps, so lexical desc == newest first.+ .sort((a, b) => b.Name.localeCompare(a.Name));++ for (const stale of blobs.slice(retention)) {+ try {+ await rcloneDeleteFile(this.remoteFile(destDir, stale.Name), undefined, {+ timeoutMs: RCLONE_TIMEOUT_MS,+ });+ cronLogger.info(`[SelfBackup] Retention removed ${stale.Name}`);+ } catch (error: any) {+ cronLogger.error(`[SelfBackup] Could not delete ${stale.Name}: ${error?.message}`);+ }+ }+ } catch (error: any) {+ cronLogger.error(`[SelfBackup] Retention pass failed: ${error?.message}`);+ }+ }+}diff --git a/backend/src/services/SettingsService.ts b/backend/src/services/SettingsService.tsindex 7039168..da63de3 100644--- a/backend/src/services/SettingsService.ts+++ b/backend/src/services/SettingsService.ts@@ -10,6 +10,10 @@ import { AppSettings, IntegrationTypes } from '../types/settings';import { INotificationChannelResolver } from '../types/notifications';import { NotificationChannelResolver } from '../notifications/channels/NotificationChannelResolver';import { appPaths } from '../utils/AppPaths';+import { selfBackupSettingsSchema } from '../utils/selfBackup/settings';+import { SelfBackupService } from './SelfBackupService';+import { jobQueue } from '../jobs/JobQueue';+import { SELF_BACKUP_JOB_NAME } from '../jobs/systemJobs';import { AppError, NotFoundError } from '../utils/AppError';import Cryptr from 'cryptr';import { configService } from './ConfigService';@@ -20,7 +24,10 @@ import { createHash, randomBytes } from 'crypto';*/export class SettingsService {protected notificationChannelResolver: INotificationChannelResolver = NotificationChannelResolver;- constructor(protected settingsStore: SettingsStore) {}+ constructor(+ protected settingsStore: SettingsStore,+ protected selfBackupService: SelfBackupService+ ) {}async getMainSettings(): Promise<Settings | null> {return await this.settingsStore.getFirst();@@ -44,6 +51,19 @@ export class SettingsService {console.error('Error parsing settings data:', error);throw new AppError(400, 'Invalid settings data provided');}++ // settingsUpdateSchema treats the settings JSON column as opaque, so the+ // self-backup block is validated separately.+ if (parsedSettings.selfBackup !== undefined) {+ const parsedSelfBackup = selfBackupSettingsSchema.safeParse(parsedSettings.selfBackup);+ if (!parsedSelfBackup.success) {+ throw new AppError(+ 400,+ `Invalid Pluton backup settings: ${parsedSelfBackup.error.issues.map(i => i.message).join(', ')}`+ );+ }+ parsedSettings.selfBackup = parsedSelfBackup.data;+ }const updatedSettings = await this.settingsStore.update(id, parsedSettings);if (!updatedSettings) {@@ -273,6 +293,30 @@ export class SettingsService {return { recoveryCodes };}+ async getSelfBackupStatus() {+ return await this.selfBackupService.getStatus();+ }++ async listSelfBackups() {+ return await this.selfBackupService.listBackups();+ }++ async downloadSelfBackup(blobName: string) {+ return await this.selfBackupService.downloadBackup(blobName);+ }++ /**+ * Queue the run rather than awaiting it: an inline run would block the response for the+ * whole upload and bypass the job lock. The UI polls the status endpoint.+ */+ async runSelfBackupNow(): Promise<void> {+ const { enabled } = await this.selfBackupService.getStatus();+ if (!enabled) {+ throw new AppError(400, 'Pluton backup is not enabled.');+ }+ jobQueue.add(SELF_BACKUP_JOB_NAME, { force: true }, 1, 0);+ }+async checkLatestVersion() {try {const response = await fetch('https://api.github.com/repos/plutonhq/pluton/releases/latest');diff --git a/backend/src/services/StorageService.ts b/backend/src/services/StorageService.tsindex fce9e9a..6e4e51b 100644--- a/backend/src/services/StorageService.ts+++ b/backend/src/services/StorageService.ts@@ -2,6 +2,8 @@ import { Storage, storageInsertSchema, storageUpdateSchema } from '../db/schema/import { providers } from '../utils/providers';import { PlanStore } from '../stores/PlanStore';import { StorageStore } from '../stores/StorageStore';+import { SettingsStore } from '../stores/SettingsStore';+import { resolveSelfBackup } from '../utils/selfBackup/settings';import Cryptr from 'cryptr';import { BaseStorageManager } from '../managers/BaseStorageManager';import {@@ -27,7 +29,8 @@ export class StorageService {protected storageManager: BaseStorageManager,protected systemManager: BaseSystemManager,protected storageStore: StorageStore,- protected planStore: PlanStore+ protected planStore: PlanStore,+ protected settingsStore: SettingsStore) {}getSystemStrategy(deviceId: string): SystemStrategy {@@ -264,6 +267,15 @@ export class StorageService {);}+ const settingsRow = await this.settingsStore.getFirst();+ const selfBackup = resolveSelfBackup(settingsRow?.settings);+ if (selfBackup.enabled && selfBackup.storageId === id) {+ throw new AppError(+ 400,+ `This Storage is used by Pluton's self-backup. Please disable self-backup or choose a different storage before deleting it.`+ );+ }+const remoteResult = await this.storageManager.deleteRemote(storage.name);if (!remoteResult.success) {throw new AppError(500, remoteResult.result || 'Failed to delete remote storage');diff --git a/backend/src/types/settings.ts b/backend/src/types/settings.tsindex fe521e5..97cb90c 100644--- a/backend/src/types/settings.ts+++ b/backend/src/types/settings.ts@@ -52,11 +52,23 @@ export interface NTFYSettings {connected: boolean;}+export interface SelfBackupSettings {+ enabled: boolean;+ storageId: string;+ storageName: string;+ path: string;+ intervalHours: number;+ retention: number;+ /** Email the admin when a backup run fails. Requires a connected email integration. */+ notifyOnFailure: boolean;+}+export interface AppSettings {title: string;description: string;theme: 'light' | 'dark' | 'auto';admin_email: string;+ selfBackup?: SelfBackupSettings;integration: {smtp?: SmtpSettings;sendgrid?: SendGridSettings;diff --git a/backend/src/utils/cliCommands.ts b/backend/src/utils/cliCommands.tsnew file mode 100644index 0000000..3ad4208--- /dev/null+++ b/backend/src/utils/cliCommands.ts@@ -0,0 +1,19 @@+/**+ * The argv flags that make this process a short-lived CLI command rather than a server.+ *+ * Deliberately dependency-free: ConfigService imports this from its constructor, which runs+ * at module-eval time, so anything imported here would be pulled into every startup.+ */+export const CLI_COMMAND_FLAGS = ['--reset-password', '--restore-pluton'] as const;++/**+ * True when the process was invoked to run a CLI command and exit, not to serve.+ *+ * ConfigService fail-fasts on missing ENCRYPTION_KEY / USER_NAME / USER_PASSWORD to stop the+ * *app* booting into a broken state. A CLI command never boots the app: it does its work and+ * exits. Those credentials are the server's requirements, not the command's, and on the+ * deployments where a restore actually matters they are legitimately absent from the shell.+ */+export function isCliCommandInvocation(argv: string[] = process.argv): boolean {+ return CLI_COMMAND_FLAGS.some(flag => argv.includes(flag));+}diff --git a/backend/src/utils/cliPasswordReset.ts b/backend/src/utils/cliPasswordReset.tsindex ba314bb..79fe0f3 100644--- a/backend/src/utils/cliPasswordReset.ts+++ b/backend/src/utils/cliPasswordReset.ts@@ -1,49 +1,12 @@-import readline from 'readline';import fs from 'fs';import path from 'path';import bcrypt from 'bcryptjs';import { appPaths } from './AppPaths';import { applyStrictPermissions } from './envFileHelpers';+import { prompt } from './cliPrompt';const BCRYPT_SALT_ROUNDS = 10;-/**- * Prompts the user for input via stdin.- * When `hidden` is true, input is not echoed (for passwords).- */-function prompt(question: string, hidden = false): Promise<string> {- return new Promise(resolve => {- if (hidden) {- // For hidden input, write the question directly and use raw mode- process.stdout.write(question);- const rl = readline.createInterface({- input: process.stdin,- output: new (require('stream').Writable)({- write(_chunk: any, _encoding: any, callback: () => void) {- callback(); // swallow all output (hides typed characters)- },- }),- terminal: true,- });-- rl.question('', answer => {- rl.close();- process.stdout.write('\n');- resolve(answer);- });- } else {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });- rl.question(question, answer => {- rl.close();- resolve(answer);- });- }- });-}-/*** Stores the new password hash in keys.json.*/diff --git a/backend/src/utils/cliPrompt.ts b/backend/src/utils/cliPrompt.tsnew file mode 100644index 0000000..d66ca0f--- /dev/null+++ b/backend/src/utils/cliPrompt.ts@@ -0,0 +1,41 @@+import readline from 'readline';+import { Writable } from 'stream';++/**+ * Prompts the user for input via stdin.+ * When `hidden` is true, input is not echoed (for passwords).+ *+ * Shared by the CLI entry points, because copy-pasting raw-mode readline is how they drift.+ */+export function prompt(question: string, hidden = false): Promise<string> {+ return new Promise(resolve => {+ if (hidden) {+ // For hidden input, write the question directly and use raw mode+ process.stdout.write(question);+ const rl = readline.createInterface({+ input: process.stdin,+ output: new Writable({+ write(_chunk: any, _encoding: any, callback: () => void) {+ callback(); // swallow all output (hides typed characters)+ },+ }),+ terminal: true,+ });++ rl.question('', answer => {+ rl.close();+ process.stdout.write('\n');+ resolve(answer);+ });+ } else {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });+ rl.question(question, answer => {+ rl.close();+ resolve(answer);+ });+ }+ });+}diff --git a/backend/src/utils/cliSelfRestore.ts b/backend/src/utils/cliSelfRestore.tsnew file mode 100644index 0000000..6cd2a60--- /dev/null+++ b/backend/src/utils/cliSelfRestore.ts@@ -0,0 +1,481 @@+/**+ * `pluton --restore-pluton <blob>`: restore Pluton's config and history from a self-backup+ * blob, against a stopped server. A short-lived CLI process, not a flow inside the server.+ *+ * Steps 1-5 are read-only. A wrong key, corrupt blob, foreign edition, newer version, or a+ * running server all fail before the data dir is touched.+ */++import fs from 'fs';+import fsp from 'fs/promises';+import os from 'os';+import path from 'path';+import type { Database as SqliteDatabase } from 'better-sqlite3';+import { appPaths } from './AppPaths';+import { prompt } from './cliPrompt';+import { openBlob, BlobDecryptError } from './selfBackup/blobFormat';+import { unpackPayload, PayloadManifest, PlutonEdition } from './selfBackup/payload';+import { getDrizzleJournalTag } from './migrations';+import {+ writeEncryptionKeyToEnvFile,+ isLinuxInstalledRuntime,+ getEncEnvFilePath,+} from './envFileHelpers';+import { isDockerMode } from './installHelpers';+import { configService } from '../services/ConfigService';++export interface RestoreArgs {+ blobPath: string | null;+ force: boolean;+}++export interface RestoreDeps {+ /** The live handle this process opened, injected so we close the right one (see below). */+ sqlite: SqliteDatabase;+ dbFilePath: string;+ edition: PlutonEdition;+}++export function parseRestoreArgs(argv: string[]): RestoreArgs {+ const flagIndex = argv.indexOf('--restore-pluton');+ const next = flagIndex === -1 ? undefined : argv[flagIndex + 1];+ const blobPath = next && !next.startsWith('--') ? next : null;+ return { blobPath, force: argv.includes('--force') };+}++/** Any response on /api/health means a live Pluton. A negative is namespace-scoped (see guard). */+export async function isServerRunning(port: number): Promise<boolean> {+ try {+ await fetch(`http://127.0.0.1:${port}/api/health`, {+ signal: AbortSignal.timeout(2000),+ });+ return true;+ } catch {+ return false;+ }+}++export type GuardVerdict = { allowed: true; warning?: string } | { allowed: false; reason: string };++/**+ * A probe response is authoritative; silence is not. Under Docker the restore container has its+ * own network namespace, so the probe stays silent even when the server is live on the same+ * volume -- undetectable, so refuse unless --force.+ */+export function evaluateInstanceGuard(opts: {+ serverResponding: boolean;+ isDocker: boolean;+ force: boolean;+ port: number;+}): GuardVerdict {+ if (opts.serverResponding) {+ if (!opts.force) {+ return {+ allowed: false,+ reason:+ `Pluton is still running on port ${opts.port}. Stop the Pluton service before restoring, ` ++ 'then run this command again.\n' ++ ' (If the port is held by something else, re-run with --force.)',+ };+ }+ return {+ allowed: true,+ warning: `A server is responding on port ${opts.port}, but --force was given. Continuing.`,+ };+ }++ if (opts.isDocker) {+ if (!opts.force) {+ return {+ allowed: false,+ reason:+ 'Running inside a container, Pluton cannot tell whether your Pluton container is still up:\n' ++ ' this restore container has its own network namespace, so the health check here proves nothing.\n' ++ ' Restoring while Pluton is running will corrupt the database.\n\n' ++ ' Stop it first:\n' ++ ' docker compose down\n\n' ++ ' Then re-run this command with --force to confirm it is stopped.',+ };+ }+ return {+ allowed: true,+ warning:+ 'Could not verify that Pluton is stopped (running inside a container). ' ++ 'Proceeding because --force was given.',+ };+ }++ return { allowed: true };+}++export interface SkewCheckResult {+ ok: boolean;+ reason?: string;+}++/** Refuse a newer blob into older Pluton (no down migrations). Caller MUST check edition first. */+export function checkVersionSkew(+ manifest: Pick<PayloadManifest, 'plutonVersion' | 'drizzleJournalTag'>,+ local: { plutonVersion: string; drizzleJournalTag: string | null }+): SkewCheckResult {+ const cmp = compareSemver(manifest.plutonVersion, local.plutonVersion);+ if (cmp > 0) {+ return {+ ok: false,+ reason:+ `This blob was written by Pluton ${manifest.plutonVersion}, but this install is ${local.plutonVersion}. ` ++ 'Restoring a newer backup into an older Pluton is not supported (there are no down migrations). ' ++ 'Upgrade Pluton to at least the blob version, then restore again.',+ };+ }++ if (+ manifest.drizzleJournalTag &&+ local.drizzleJournalTag &&+ compareJournalTag(manifest.drizzleJournalTag, local.drizzleJournalTag) > 0+ ) {+ return {+ ok: false,+ reason:+ `This blob's database schema (${manifest.drizzleJournalTag}) is newer than this install's (${local.drizzleJournalTag}). ` ++ 'Restoring it would leave the database ahead of the code. Upgrade Pluton, then restore again.',+ };+ }++ return { ok: true };+}++export function checkEdition(+ manifestEdition: string | undefined,+ localEdition: PlutonEdition+): SkewCheckResult {+ if (!manifestEdition) {+ return {+ ok: false,+ reason:+ 'This blob does not record which Pluton edition produced it, so it cannot be safely restored.',+ };+ }+ if (manifestEdition !== localEdition) {+ return {+ ok: false,+ reason:+ `This blob is from the "${manifestEdition}" edition of Pluton, but this install is "${localEdition}". ` ++ 'Cross-edition restore is not supported. Version and schema numbering differ between editions.',+ };+ }+ return { ok: true };+}++/** Numeric-segment compare; non-numeric suffixes are ignored. Returns -1 / 0 / 1. */+function compareSemver(a: string, b: string): number {+ const parse = (v: string) =>+ v+ .replace(/^v/, '')+ .split(/[.\-+]/)+ .map(part => parseInt(part, 10))+ .filter(n => !Number.isNaN(n));++ const left = parse(a);+ const right = parse(b);+ // An unparseable version ('unknown', a dev build) can't be ordered, so don't block on it.+ if (left.length === 0 || right.length === 0) return 0;++ for (let i = 0; i < Math.max(left.length, right.length); i++) {+ const l = left[i] ?? 0;+ const r = right[i] ?? 0;+ if (l !== r) return l > r ? 1 : -1;+ }+ return 0;+}++/** Drizzle tags are `NNNN_name`; the numeric prefix is the ordering. */+function compareJournalTag(a: string, b: string): number {+ const idx = (tag: string) => parseInt(tag.split('_')[0], 10);+ const left = idx(a);+ const right = idx(b);+ if (Number.isNaN(left) || Number.isNaN(right)) return 0;+ if (left === right) return 0;+ return left > right ? 1 : -1;+}++// Scratch holds the decrypted payload (keys.json included); process.exit() skips finally, so+// every exit path cleans up through here.+let scratchToClean: string | null = null;++function cleanScratch(): void {+ if (!scratchToClean) return;+ try {+ fs.rmSync(scratchToClean, { recursive: true, force: true });+ } catch {+ // best effort+ }+ scratchToClean = null;+}++/** Per-install next steps: env-injected key/password override what we restored, except on desktop. */+export function buildCompletionMessage(env: {+ isDocker: boolean;+ isLinuxInstalled: boolean;+}): string {+ const done = '\n✅ Restore complete.\n';++ if (env.isDocker) {+ return (+ done ++ '\n REQUIRED: open the .env next to your docker-compose.yml and set\n' ++ '\n ENCRYPTION_KEY=<the same key you just entered>\n' ++ '\n The key is deliberately NOT stored in the data volume, so compose is the only\n' ++ ' place Pluton can get it. Without it the container will refuse to start.\n' ++ ' If it is set but does not match the backup, Pluton starts and every restored plan\n' ++ ' points at a repository it can no longer read, so check it now.\n' ++ '\n While you are in that file, USER_NAME and USER_PASSWORD are your login: they\n' ++ ' override the restored account, so set them to what you want to log in with.\n' ++ '\n Then: docker compose up -d\n' ++ ' Log in with the USER_NAME / USER_PASSWORD from that .env, not your old password.\n'+ );+ }++ if (env.isLinuxInstalled) {+ return (+ done ++ '\n The encryption key from your backup was written to /etc/pluton/pluton.enc.env,\n' ++ ' which the service reads on start. Nothing more to do for the key.\n' ++ '\n Then: sudo systemctl start pluton\n' ++ ' Log in with the PLUTON_USER_NAME / PLUTON_USER_PASSWORD in /etc/pluton/pluton.env.\n' ++ ' Those override the restored account, so they are your credentials now, not the old ones.\n'+ );+ }++ return done + '\n Start the Pluton service and log in with your old password.\n';+}++/**+ * Desktop/Server: write pluton.enc.env so the key takes effect. Docker: write nothing and delete+ * any copy -- compose owns the key, and a leftover OLDER key would silently boot against the+ * wrong key instead of failing loudly. Safe to delete: the caller just decrypted with it.+ */+export async function applyEncryptionKey(opts: {+ dataDir: string;+ key: string;+ isDocker: boolean;+}): Promise<void> {+ if (opts.isDocker) {+ await fsp.rm(getEncEnvFilePath(opts.dataDir), { force: true });+ return;+ }+ writeEncryptionKeyToEnvFile(opts.dataDir, opts.key);+}++function fail(message: string): never {+ cleanScratch();+ console.error(`❌ ${message}`);+ process.exit(1);+}++function succeed(message: string): never {+ cleanScratch();+ console.log(message);+ process.exit(0);+}++async function copyTree(srcDir: string, destDir: string): Promise<void> {+ await fsp.cp(srcDir, destDir, { recursive: true, force: true });+}++/** Transient errno codes Windows raises for a momentarily-held file (AV, indexer, memory-map). */+const TRANSIENT_FS_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY', 'EMFILE', 'ENFILE']);++/**+ * Close the DB handle and clear pluton.db + its WAL sidecars. On Windows a naive close()-unlink+ * races the -shm teardown and AV/indexer scans and hits EBUSY, so: switch out of WAL before+ * closing (deletes -wal/-shm with the handle still held), retry the unlink, then rename aside+ * for a clean slot. Throws only if all three fail; the caller aborts before copying.+ */+export async function releaseDatabaseFiles(+ sqlite: SqliteDatabase,+ dbFilePath: string+): Promise<void> {+ // A downstream edition injects its own handle, but core's db/index.ts also loads here, leaving+ // a SECOND open handle that would make the unlink fail. Close it too. Lazy import keeps the+ // pure pieces off the db graph; the guard avoids double-closing when it already IS the injected one.+ try {+ const coreDb = await import('../db');+ if (coreDb.sqlite !== sqlite && coreDb.sqlite.open) {+ coreDb.sqlite.close();+ }+ } catch {+ // core's db may not be loaded here, or already closed+ }++ try {+ sqlite.pragma('journal_mode = DELETE'); // deletes -wal/-shm before we drop the handle+ } catch {+ // switch failed; still close and lean on the retry/rename below+ }+ sqlite.close();++ const rmOpts = { force: true, maxRetries: 10, retryDelay: 200 } as const;++ for (const suffix of ['-wal', '-shm']) {+ await fsp.rm(`${dbFilePath}${suffix}`, rmOpts);+ }++ try {+ await fsp.rm(dbFilePath, rmOpts);+ return;+ } catch (error: any) {+ if (!TRANSIENT_FS_CODES.has(error?.code)) throw error;+ }++ // Still locked: rename aside. An inert DB with no sidecars is ignored by SQLite.+ const aside = `${dbFilePath}.restore-old-${process.pid}`;+ await fsp.rename(dbFilePath, aside);+ fsp.rm(aside, rmOpts).catch(() => {});+}++/** `deps.sqlite` is injected, not imported, so releaseDatabaseFiles closes the right handle. */+export async function handleSelfRestore(deps: RestoreDeps): Promise<never> {+ console.log('\n🛟 Pluton Restore\n');++ // Show the target while still read-only. A service sets PLUTON_DATA_DIR but the operator's+ // shell often doesn't inherit it, and then the path falls back to the default.+ const dataDir = appPaths.getDataDir();+ console.log(`Restoring into data directory: ${dataDir}`);+ const isRealInstall = Boolean((process as any).pkg) || process.env.NODE_ENV === 'production';+ if (isRealInstall && !isDockerMode() && !process.env.PLUTON_DATA_DIR) {+ console.warn(+ '⚠️ PLUTON_DATA_DIR is not set in this shell, so the path above is the default location.\n' ++ ' If this Pluton runs as a service with a custom data directory, stop the service and set\n' ++ ' PLUTON_DATA_DIR to match it before restoring, or you will restore into the wrong place.\n'+ );+ }++ // ---- 1. Parse+ const { blobPath, force } = parseRestoreArgs(process.argv);+ if (!blobPath) {+ fail('Usage: pluton --restore-pluton <path-to-blob> [--force]');+ }+ if (!fs.existsSync(blobPath)) {+ fail(`No such file: ${blobPath}`);+ }++ // ---- 2. Running-instance guard+ const port = configService.config.SERVER_PORT || 5173;+ const verdict = evaluateInstanceGuard({+ serverResponding: await isServerRunning(port),+ isDocker: isDockerMode(),+ force,+ port,+ });+ if (!verdict.allowed) {+ fail(verdict.reason);+ }+ if (verdict.warning) {+ console.warn(`⚠️ ${verdict.warning}`);+ }++ // ---- 3. Key+ const key = await obtainEncryptionKey();++ // ---- 4. Decrypt (wrong key fails here, before anything is touched)+ console.log('Decrypting blob...');+ let tar: Buffer;+ try {+ tar = openBlob(await fsp.readFile(blobPath), key);+ } catch (error: any) {+ if (error instanceof BlobDecryptError) {+ fail(`${error.message}\n Nothing has been modified.`);+ }+ throw error;+ }++ // ---- 5. Unpack to scratch, then guard edition before version+ const scratchDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'pluton-restore-'));+ scratchToClean = scratchDir;+ try {+ const manifest = await unpackPayload(tar, scratchDir);++ const editionCheck = checkEdition(manifest.edition, deps.edition);+ if (!editionCheck.ok) {+ fail(`${editionCheck.reason}\n Nothing has been modified.`);+ }++ const skewCheck = checkVersionSkew(manifest, {+ plutonVersion: process.env.APP_VERSION || 'unknown',+ drizzleJournalTag: getDrizzleJournalTag(),+ });+ if (!skewCheck.ok) {+ fail(`${skewCheck.reason}\n Nothing has been modified.`);+ }++ console.log(+ `Blob looks good. Written ${manifest.createdAt} on host "${manifest.hostname}" ` ++ `by Pluton ${manifest.plutonVersion} (${manifest.edition}).`+ );++ // ================= past this line we mutate =================++ // ---- 6/7. Close the DB and clear pluton.db + its WAL sidecars (Windows-safe; see helper)+ console.log('Applying restore...');+ try {+ await releaseDatabaseFiles(deps.sqlite, deps.dbFilePath);+ } catch (error: any) {+ // Nothing copied yet, so the data dir is intact -- safe to abort.+ fail(+ `Could not replace the database file (${error?.code || error?.message || error}).\n` ++ ` Something still holds ${deps.dbFilePath} open. On Windows this is almost always\n` ++ ' antivirus or the Search indexer scanning it, or a Pluton process that did not fully\n' ++ ' stop. Confirm no "pluton" process is running (Task Manager, or `Get-Process pluton`),\n' ++ ' then run this command again. Your existing data has not been modified.'+ );+ }++ // ---- 8. Unpack over the data dir+ await copyTree(scratchDir, appPaths.getDataDir());+ await fsp.rm(path.join(appPaths.getDataDir(), 'manifest.json'), { force: true });++ // ---- 9. Get the key where this install reads it from (nowhere, on Docker)+ await applyEncryptionKey({+ dataDir: appPaths.getDataDir(),+ key,+ isDocker: isDockerMode(),+ });++ // ---- 10. Mark setup complete so the wizard doesn't reappear+ await fsp.writeFile(path.join(appPaths.getDataDir(), '.setup_complete'), '');++ succeed(+ buildCompletionMessage({+ isDocker: isDockerMode(),+ isLinuxInstalled: isLinuxInstalledRuntime(),+ })+ );+ } catch (error) {+ // An unexpected throw (not a fail()) still must not leave the decrypted payload behind.+ cleanScratch();+ throw error;+ }+}++/** No --encryption-key flag (argv leaks to ps/history); use PLUTON_ENCRYPTION_KEY or the prompt. */+async function obtainEncryptionKey(): Promise<string> {+ const fromEnv = process.env.PLUTON_ENCRYPTION_KEY || process.env.ENCRYPTION_KEY;+ if (fromEnv) {+ console.log('Using encryption key from the environment.');+ return fromEnv;+ }++ if (!process.stdin.isTTY) {+ fail(+ 'An encryption key is required. Run this in an interactive terminal, ' ++ 'or set PLUTON_ENCRYPTION_KEY.'+ );+ }++ const key = await prompt('Enter your Pluton encryption key: ', true);+ if (!key) {+ fail('Encryption key cannot be empty.');+ }+ return key;+}diff --git a/backend/src/utils/migrations.ts b/backend/src/utils/migrations.tsnew file mode 100644index 0000000..a20fc6b--- /dev/null+++ b/backend/src/utils/migrations.ts@@ -0,0 +1,39 @@+import path from 'path';+import fs from 'fs';++/**+ * Resolve the drizzle migrations folder for the current runtime.+ * Docker ships them at a fixed path; binaries carry them beside the executable.+ */+export function getMigrationsFolder(): string {+ return process.env.IS_DOCKER === 'true'+ ? '/app/drizzle'+ : path.join(path.dirname(process.execPath), 'drizzle');+}++export function getMigrationsJournalPath(migrationsFolder = getMigrationsFolder()): string {+ return path.join(migrationsFolder, 'meta', '_journal.json');+}++/**+ * The tag of the most recent applied migration, e.g. `0042_lively_thing`.+ * Returns null when no journal is present (dev runs, or a build without migrations).+ */+export function getDrizzleJournalTag(): string | null {+ try {+ const journalPath = getMigrationsJournalPath();+ if (!fs.existsSync(journalPath)) {+ return null;+ }+ const journal = JSON.parse(fs.readFileSync(journalPath, 'utf-8')) as {+ entries?: { tag?: string }[];+ };+ const entries = journal.entries;+ if (!Array.isArray(entries) || entries.length === 0) {+ return null;+ }+ return entries[entries.length - 1]?.tag ?? null;+ } catch {+ return null;+ }+}diff --git a/backend/src/utils/rclone/helpers.ts b/backend/src/utils/rclone/helpers.tsindex 73b65c1..e10378d 100644--- a/backend/src/utils/rclone/helpers.ts+++ b/backend/src/utils/rclone/helpers.ts@@ -2,7 +2,7 @@ import { ChildProcess } from 'child_process';import path from 'path';import os from 'os';import { appPaths } from '../AppPaths';-import { runRcloneCommand } from './rclone';+import { runRcloneCommand, RunRcloneOptions } from './rclone';import { runCommand } from '../runCommand';import { getBinaryPath } from '../binaryPathResolver';import { getInstallType } from '../installHelpers';@@ -31,6 +31,55 @@ export const getRcloneConfigPath = (secure = false) => {return rcloneConfPath;};+export interface RcloneLsJsonItem {+ Path: string;+ Name: string;+ Size: number;+ MimeType?: string;+ ModTime?: string;+ IsDir: boolean;+}++/**+ * Copy a single file to an exact destination path (not into a directory).+ */+export async function rcloneCopyTo(+ src: string,+ dest: string,+ env?: Record<string, string>,+ opts?: RunRcloneOptions+): Promise<void> {+ await runRcloneCommand(['copyto', src, dest], env, opts);+}++export async function rcloneDeleteFile(+ target: string,+ env?: Record<string, string>,+ opts?: RunRcloneOptions+): Promise<void> {+ await runRcloneCommand(['deletefile', target], env, opts);+}++/**+ * List a remote path as JSON.+ */+export async function rcloneLsJson(+ target: string,+ env?: Record<string, string>,+ opts?: RunRcloneOptions+): Promise<RcloneLsJsonItem[]> {+ const raw = await runRcloneCommand(['lsjson', target], env, opts);+ if (!raw || !raw.trimStart().startsWith('[')) {+ return [];+ }+ try {+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? (parsed as RcloneLsJsonItem[]) : [];+ } catch {+ return [];+ }+}+export async function encryptRcloneConfig(password: string): Promise<{ success: boolean; result: string }> {diff --git a/backend/src/utils/rclone/rclone.ts b/backend/src/utils/rclone/rclone.tsindex 1867c2c..f799b5b 100644--- a/backend/src/utils/rclone/rclone.ts+++ b/backend/src/utils/rclone/rclone.ts@@ -5,7 +5,15 @@ import { getRcloneConfigPath } from './helpers';import { configService } from '../../services/ConfigService';import { buildRcloneEnvFromSettings } from '../globalSettings';-export function runRcloneCommand(args: string[], env?: Record<string, string>): Promise<string> {+export interface RunRcloneOptions {+ timeoutMs?: number;+}++export function runRcloneCommand(+ args: string[],+ env?: Record<string, string>,+ opts?: RunRcloneOptions+): Promise<string> {return new Promise((resolve, reject) => {const rcloneBinary = getBinaryPath('rclone');const rcloneConfigPath = getRcloneConfigPath();@@ -25,6 +33,25 @@ export function runRcloneCommand(args: string[], env?: Record<string, string>):const rcProcess = spawn(rcloneBinary, args, { env: envVars });let output = '';let errorOutput = '';+ let timer: NodeJS.Timeout | undefined;+ let settled = false;++ const settle = (fn: () => void) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ fn();+ };++ if (opts?.timeoutMs) {+ rcProcess.on('error', (error: Error) => settle(() => reject(error)));+ timer = setTimeout(() => {+ rcProcess.kill();+ settle(() =>+ reject(new Error(`Rclone command timed out after ${opts.timeoutMs}ms: ${args[0]}`))+ );+ }, opts.timeoutMs);+ }rcProcess.stdout?.on('data', (data: Buffer) => {// console.log('[rclone] Data :', data.toString());@@ -37,19 +64,21 @@ export function runRcloneCommand(args: string[], env?: Record<string, string>):});rcProcess.on('close', (code: number) => {- if (code === 0) {- const outputRes = output.trim();- const errorOutputRes = errorOutput.trim();- if (outputRes) {- resolve(outputRes);- } else if (errorOutputRes) {- resolve(errorOutputRes);+ settle(() => {+ if (code === 0) {+ const outputRes = output.trim();+ const errorOutputRes = errorOutput.trim();+ if (outputRes) {+ resolve(outputRes);+ } else if (errorOutputRes) {+ resolve(errorOutputRes);+ } else {+ resolve('');+ }} else {- resolve('');+ reject(new Error(errorOutput || `Rclone command failed`));}- } else {- reject(new Error(errorOutput || `Rclone command failed`));- }+ });});});}diff --git a/backend/src/utils/selfBackup/blobFormat.ts b/backend/src/utils/selfBackup/blobFormat.tsnew file mode 100644index 0000000..5f0c705--- /dev/null+++ b/backend/src/utils/selfBackup/blobFormat.ts@@ -0,0 +1,241 @@+/**+ * Self-backup blob format: encode/decode the single encrypted artifact.+ *+ * Layout:+ * MAGIC(4) | version(u16) | memory(u32) | passes(u32) | parallelism(u32) |+ * salt(16) | nonce(12) | ciphertext(...) | tag(16)+ *+ * The header is plaintext by design: salt and KDF params only let you re-derive+ * the key from the password, they don't reveal it.+ *+ * This module imports ONLY node:crypto. No appPaths, no configService, so it stays+ * unit-testable with zero mocks, and the CLI restore path can import it without+ * pulling in the app module graph.+ */++import * as nodeCrypto from 'node:crypto';+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';++/**+ * argon2id landed in Node core in v24 and is present in every runtime we ship+ * (verified by probe across the pkg-bundled Node 24 builds). `@types/node@22`, which is+ * this repo's pin, does not declare it yet, so bind a local signature rather+ * than bumping the global type package for a single function.+ */+type Argon2SyncFn = (+ algorithm: 'argon2id' | 'argon2i' | 'argon2d',+ options: {+ message: Buffer;+ nonce: Buffer;+ parallelism: number;+ tagLength: number;+ memory: number;+ passes: number;+ secret?: Buffer;+ associatedData?: Buffer;+ }+) => Buffer;++const argon2Sync = (nodeCrypto as unknown as { argon2Sync?: Argon2SyncFn }).argon2Sync;++export const MAGIC = 'PLBK';+export const FORMAT_VERSION = 1;++const MAGIC_LEN = 4;+const VERSION_LEN = 2;+const KDF_PARAMS_LEN = 12; // memory(4) + passes(4) + parallelism(4)+const SALT_LEN = 16;+const NONCE_LEN = 12;+const TAG_LEN = 16;++export const HEADER_LEN = MAGIC_LEN + VERSION_LEN + KDF_PARAMS_LEN + SALT_LEN + NONCE_LEN;++export interface KdfParams {+ /** Memory cost in KiB. */+ memory: number;+ /** Iterations. */+ passes: number;+ /** Lanes. */+ parallelism: number;+}++export const ARGON2_DEFAULTS: KdfParams = { memory: 65536, passes: 3, parallelism: 1 };++/**+ * Bounds on the KDF params we are willing to honour from a blob header.+ */+export const KDF_LIMITS = {+ /** 1 GiB, expressed in KiB to match `memory`. */+ maxMemory: 1024 * 1024,+ /** argon2's own floor is 8 KiB per lane. */+ minMemory: 8,+ maxPasses: 10,+ maxParallelism: 4,+};++function assertSaneKdfParams(kdf: KdfParams): void {+ const inRange = (value: number, min: number, max: number) =>+ Number.isInteger(value) && value >= min && value <= max;++ if (!inRange(kdf.memory, KDF_LIMITS.minMemory, KDF_LIMITS.maxMemory)) {+ throw new BlobDecryptError(+ `Blob header asks for an unreasonable KDF memory cost (${kdf.memory} KiB). ` ++ 'The file is corrupt or was not written by Pluton.'+ );+ }+ if (!inRange(kdf.passes, 1, KDF_LIMITS.maxPasses)) {+ throw new BlobDecryptError(+ `Blob header asks for an unreasonable KDF pass count (${kdf.passes}). ` ++ 'The file is corrupt or was not written by Pluton.'+ );+ }+ if (!inRange(kdf.parallelism, 1, KDF_LIMITS.maxParallelism)) {+ throw new BlobDecryptError(+ `Blob header asks for an unreasonable KDF parallelism (${kdf.parallelism}). ` ++ 'The file is corrupt or was not written by Pluton.'+ );+ }+}++export interface ParsedHeader {+ version: number;+ kdf: KdfParams;+ salt: Buffer;+ nonce: Buffer;+ bodyOffset: number;+}++/** Thrown when a blob cannot be opened: bad magic, unknown version, wrong key, or tampering. */+export class BlobDecryptError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'BlobDecryptError';+ }+}++export function encodeHeader(kdf: KdfParams, salt: Buffer, nonce: Buffer): Buffer {+ if (salt.length !== SALT_LEN) {+ throw new Error(`salt must be ${SALT_LEN} bytes, got ${salt.length}`);+ }+ if (nonce.length !== NONCE_LEN) {+ throw new Error(`nonce must be ${NONCE_LEN} bytes, got ${nonce.length}`);+ }++ const header = Buffer.alloc(HEADER_LEN);+ let offset = 0;+ header.write(MAGIC, offset, MAGIC_LEN, 'ascii');+ offset += MAGIC_LEN;+ header.writeUInt16BE(FORMAT_VERSION, offset);+ offset += VERSION_LEN;+ header.writeUInt32BE(kdf.memory, offset);+ offset += 4;+ header.writeUInt32BE(kdf.passes, offset);+ offset += 4;+ header.writeUInt32BE(kdf.parallelism, offset);+ offset += 4;+ salt.copy(header, offset);+ offset += SALT_LEN;+ nonce.copy(header, offset);++ return header;+}++export function parseHeader(buf: Buffer): ParsedHeader {+ if (buf.length < HEADER_LEN + TAG_LEN) {+ throw new BlobDecryptError('Not a Pluton backup blob: file is too small.');+ }++ let offset = 0;+ const magic = buf.toString('ascii', 0, MAGIC_LEN);+ if (magic !== MAGIC) {+ throw new BlobDecryptError(+ `Not a Pluton backup blob: expected magic '${MAGIC}', found '${magic}'.`+ );+ }+ offset += MAGIC_LEN;++ const version = buf.readUInt16BE(offset);+ offset += VERSION_LEN;+ if (version !== FORMAT_VERSION) {+ throw new BlobDecryptError(+ `Unsupported blob format version ${version}. This Pluton understands version ${FORMAT_VERSION}. ` ++ 'The blob was probably written by a newer Pluton.'+ );+ }++ const memory = buf.readUInt32BE(offset);+ offset += 4;+ const passes = buf.readUInt32BE(offset);+ offset += 4;+ const parallelism = buf.readUInt32BE(offset);+ offset += 4;++ const salt = buf.subarray(offset, offset + SALT_LEN);+ offset += SALT_LEN;+ const nonce = buf.subarray(offset, offset + NONCE_LEN);+ offset += NONCE_LEN;++ const kdf: KdfParams = { memory, passes, parallelism };+ // Checked before deriveKey() can act on them: these came off an unauthenticated header.+ assertSaneKdfParams(kdf);++ return { version, kdf, salt, nonce, bodyOffset: offset };+}++/**+ * Derive a 32-byte AES key from the user's ENCRYPTION_KEY.+ */+export function deriveKey(+ password: string,+ salt: Buffer,+ kdf: KdfParams = ARGON2_DEFAULTS+): Buffer {+ if (!argon2Sync) {+ throw new Error(+ 'This Node runtime has no crypto.argon2Sync (added in Node 24). ' ++ 'Pluton self-backup requires it to derive the blob encryption key.'+ );+ }+ return Buffer.from(+ argon2Sync('argon2id', {+ message: Buffer.from(password, 'utf-8'),+ nonce: salt,+ parallelism: kdf.parallelism,+ tagLength: 32,+ memory: kdf.memory,+ passes: kdf.passes,+ })+ );+}++export function sealBlob(tar: Buffer, password: string, kdf: KdfParams = ARGON2_DEFAULTS): Buffer {+ const salt = randomBytes(SALT_LEN);+ const nonce = randomBytes(NONCE_LEN);+ const key = deriveKey(password, salt, kdf);++ const cipher = createCipheriv('aes-256-gcm', key, nonce);+ const ciphertext = Buffer.concat([cipher.update(tar), cipher.final()]);+ const tag = cipher.getAuthTag();++ return Buffer.concat([encodeHeader(kdf, salt, nonce), ciphertext, tag]);+}++export function openBlob(blob: Buffer, password: string): Buffer {+ const { kdf, salt, nonce, bodyOffset } = parseHeader(blob);++ const tag = blob.subarray(blob.length - TAG_LEN);+ const ciphertext = blob.subarray(bodyOffset, blob.length - TAG_LEN);++ const key = deriveKey(password, salt, kdf);+ const decipher = createDecipheriv('aes-256-gcm', key, nonce);+ // setAuthTag before final() so a wrong key throws instead of yielding garbage.+ decipher.setAuthTag(tag);++ try {+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);+ } catch {+ throw new BlobDecryptError(+ 'Could not decrypt the blob. The encryption key is wrong, or the file is corrupt.'+ );+ }+}diff --git a/backend/src/utils/selfBackup/payload.ts b/backend/src/utils/selfBackup/payload.tsnew file mode 100644index 0000000..6c36fad--- /dev/null+++ b/backend/src/utils/selfBackup/payload.ts@@ -0,0 +1,279 @@+/**+ * Self-backup payload: the tar that goes inside the encrypted blob.+ */++import fs from 'fs';+import os from 'os';+import path from 'path';+import { createHash } from 'crypto';+import { extract, pack } from 'tar-stream';+import { appPaths } from '../AppPaths';+import { getDrizzleJournalTag } from '../migrations';++export type PlutonEdition = 'core' | 'pro';++export interface PayloadManifest {+ edition: PlutonEdition;+ plutonVersion: string;+ drizzleJournalTag: string | null;+ createdAt: string;+ hostname: string;+ fileList: string[];+ dbPageCount: number;+}++export const MANIFEST_ENTRY = 'manifest.json';+export const DB_ENTRY = 'db/pluton.db';++/**+ * Every entry is optional: pack what exists, skip what doesn't. Several are absent+ * on a given install, and downstream editions write files core never does.+ */+interface PayloadEntry {+ /** Path inside the tar. */+ entry: string;+ /** Resolve the absolute source path at pack time. */+ source: () => string;+ /** Recurse a directory rather than pack a single file. */+ dir?: boolean;+ /** Skip matching basenames when packing a directory. */+ skip?: (relPath: string) => boolean;+}++export const PAYLOAD_SPEC: PayloadEntry[] = [+ { entry: 'config/rclone.conf', source: () => path.join(appPaths.getConfigDir(), 'rclone.conf') },+ {+ entry: 'config/rclone_global.json',+ source: () => path.join(appPaths.getConfigDir(), 'rclone_global.json'),+ },+ {+ entry: 'config/restic_global.json',+ source: () => path.join(appPaths.getConfigDir(), 'restic_global.json'),+ },+ {+ entry: 'config/device_settings.json',+ source: () => path.join(appPaths.getConfigDir(), 'device_settings.json'),+ },+ { entry: 'config/config.json', source: () => path.join(appPaths.getConfigDir(), 'config.json') },+ {+ entry: 'config/self_backup_state.json',+ source: () => path.join(appPaths.getConfigDir(), 'self_backup_state.json'),+ },+ { entry: 'keys.json', source: () => path.join(appPaths.getDataDir(), 'keys.json') },+ { entry: 'schedules.json', source: () => appPaths.getSchedulesPath() },+ { entry: '.activated', source: () => path.join(appPaths.getDataDir(), '.activated') },+ { entry: 'progress', source: () => appPaths.getProgressDir(), dir: true },+ {+ entry: 'sync',+ source: () => appPaths.getSyncDir(),+ dir: true,+ skip: relPath => relPath.endsWith('.lock'),+ },+];++/**+ * Files whose mtime+size decide whether anything actually changed since the last upload.+ */+const FINGERPRINT_EXCLUDED = new Set(['config/self_backup_state.json']);++function fingerprintTargets(): string[] {+ const dbPath = path.join(appPaths.getDbDir(), 'pluton.db');+ return [+ dbPath,+ `${dbPath}-wal`,+ ...PAYLOAD_SPEC.filter(e => !e.dir && !FINGERPRINT_EXCLUDED.has(e.entry)).map(e => e.source()),+ ];+}++/**+ * sha256 over path|size|mtime of the DB and the config files in the spec.+ * An unchanged fingerprint means the upload can be skipped entirely, with zero API calls.+ */+export function computeFingerprint(): string {+ const hash = createHash('sha256');+ for (const filePath of fingerprintTargets()) {+ try {+ const stat = fs.statSync(filePath);+ hash.update(`${filePath}|${stat.size}|${stat.mtimeMs}\n`);+ } catch {+ // Absent files contribute a stable marker, so creation/deletion still moves the fingerprint.+ hash.update(`${filePath}|absent\n`);+ }+ }+ return hash.digest('hex');+}++function walkDir(root: string, prefix: string, skip?: (relPath: string) => boolean): string[] {+ const out: string[] = [];+ const stack: { abs: string; rel: string }[] = [{ abs: root, rel: '' }];++ while (stack.length > 0) {+ const { abs, rel } = stack.pop()!;+ let dirEntries: fs.Dirent[];+ try {+ dirEntries = fs.readdirSync(abs, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const dirent of dirEntries) {+ const childAbs = path.join(abs, dirent.name);+ const childRel = rel ? `${rel}/${dirent.name}` : dirent.name;+ if (dirent.isDirectory()) {+ stack.push({ abs: childAbs, rel: childRel });+ } else if (dirent.isFile()) {+ const entry = `${prefix}/${childRel}`;+ if (skip?.(entry)) continue;+ out.push(childRel);+ }+ }+ }+ return out;+}++export function buildManifest(+ fileList: string[],+ dbPageCount: number,+ edition: PlutonEdition+): PayloadManifest {+ return {+ edition,+ // The version of whichever repo built this binary. Core and pro ship separate release lines.+ plutonVersion: process.env.APP_VERSION || 'unknown',+ drizzleJournalTag: getDrizzleJournalTag(),+ createdAt: new Date().toISOString(),+ hostname: os.hostname(),+ fileList,+ dbPageCount,+ };+}++/**+ * Pack the DB snapshot plus every present spec entry into a tar buffer.+ * `dbSnapshotPath` must be a VACUUM INTO output, never a raw copy of a live WAL DB.+ */+export async function packPayload(opts: {+ dbSnapshotPath: string;+ edition: PlutonEdition;+ dbPageCount?: number;+}): Promise<Buffer> {+ const tarPack = pack();+ const chunks: Buffer[] = [];+ const collected = new Promise<Buffer>((resolve, reject) => {+ tarPack.on('data', (c: Buffer) => chunks.push(c));+ tarPack.on('end', () => resolve(Buffer.concat(chunks)));+ tarPack.on('error', reject);+ });++ const fileList: string[] = [];++ const addFile = (entryName: string, absPath: string) => {+ const content = fs.readFileSync(absPath);+ tarPack.entry({ name: entryName, mode: 0o600, size: content.length }, content);+ fileList.push(entryName);+ };++ addFile(DB_ENTRY, opts.dbSnapshotPath);++ for (const spec of PAYLOAD_SPEC) {+ let absSource: string;+ try {+ absSource = spec.source();+ } catch {+ continue;+ }+ if (!fs.existsSync(absSource)) continue;++ if (spec.dir) {+ for (const rel of walkDir(absSource, spec.entry, spec.skip)) {+ addFile(`${spec.entry}/${rel}`, path.join(absSource, rel));+ }+ } else {+ addFile(spec.entry, absSource);+ }+ }++ const manifest = buildManifest(fileList, opts.dbPageCount ?? 0, opts.edition);+ const manifestJson = Buffer.from(JSON.stringify(manifest, null, 2));+ tarPack.entry({ name: MANIFEST_ENTRY, mode: 0o600, size: manifestJson.length }, manifestJson);++ tarPack.finalize();+ return collected;+}++/**+ * Reject any entry that would land outside destDir.+ *+ * In the restore path this tar is attacker-supplied: tar-stream will happily write+ * `../../etc/whatever` if asked. Absolute paths, drive letters, and `..` traversal+ * are all refused.+ */+export function assertSafeEntryPath(entryName: string, destDir: string): string {+ const normalized = entryName.replace(/\\/g, '/');++ if (normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized)) {+ throw new Error(`Refusing tar entry with an absolute path: ${entryName}`);+ }++ const resolvedDest = path.resolve(destDir);+ const target = path.resolve(resolvedDest, normalized);+ const rel = path.relative(resolvedDest, target);++ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {+ throw new Error(`Refusing tar entry that escapes the destination: ${entryName}`);+ }++ return target;+}++/** Unpack a payload tar into destDir and return its manifest. */+export async function unpackPayload(tar: Buffer, destDir: string): Promise<PayloadManifest> {+ const extractor = extract();+ let manifest: PayloadManifest | null = null;++ const done = new Promise<void>((resolve, reject) => {+ extractor.on('entry', (header, stream, next) => {+ if (header.type !== 'file') {+ stream.resume();+ stream.on('end', next);+ return;+ }++ let target: string;+ try {+ target = assertSafeEntryPath(header.name, destDir);+ } catch (error) {+ stream.resume();+ extractor.destroy();+ reject(error as Error);+ return;+ }++ const buf: Buffer[] = [];+ stream.on('data', (c: Buffer) => buf.push(c));+ stream.on('error', reject);+ stream.on('end', () => {+ try {+ const content = Buffer.concat(buf);+ if (header.name === MANIFEST_ENTRY) {+ manifest = JSON.parse(content.toString('utf-8')) as PayloadManifest;+ }+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, content, { mode: 0o600 });+ next();+ } catch (error) {+ reject(error as Error);+ }+ });+ });+ extractor.on('finish', resolve);+ extractor.on('error', reject);+ });++ extractor.end(tar);+ await done;++ if (!manifest) {+ throw new Error('Payload is missing manifest.json. This is not a valid Pluton backup blob.');+ }+ return manifest;+}diff --git a/backend/src/utils/selfBackup/settings.ts b/backend/src/utils/selfBackup/settings.tsnew file mode 100644index 0000000..4b54e45--- /dev/null+++ b/backend/src/utils/selfBackup/settings.ts@@ -0,0 +1,41 @@+import { z } from 'zod';+import { AppSettings, SelfBackupSettings } from '../../types/settings';++export const SELF_BACKUP_DEFAULTS: SelfBackupSettings = {+ enabled: false,+ storageId: '',+ storageName: '',+ path: '',+ intervalHours: 12,+ retention: 10,+ notifyOnFailure: false,+};++/**+ * The drizzle-zod `settingsUpdateSchema` treats the settings JSON column as opaque and+ * validates nothing inside it, so the self-backup block needs its own schema.+ */+export const selfBackupSettingsSchema = z+ .object({+ enabled: z.boolean(),+ storageId: z.string(),+ storageName: z.string(),+ path: z.string(),+ intervalHours: z.number().int().positive(),+ retention: z.number().int().positive(),+ notifyOnFailure: z.boolean().optional().default(false),+ })+ // Empty storage fields are valid while disabled (that is the default state), but an+ // enabled config with no storage would only fail later, at run time.+ .refine(v => !v.enabled || (v.storageId !== '' && v.storageName !== ''), {+ message: 'A storage must be selected to enable Pluton self-backup.',+ path: ['storageId'],+ });++/**+ * `initSetup` short-circuits on `.setup_complete`, so `selfBackup` is undefined on every+ * pre-existing install. Backend and UI both resolve through here so defaults live in one place.+ */+export function resolveSelfBackup(appSettings?: AppSettings | null): SelfBackupSettings {+ return { ...SELF_BACKUP_DEFAULTS, ...(appSettings?.selfBackup ?? {}) };+}diff --git a/backend/src/utils/selfBackup/state.ts b/backend/src/utils/selfBackup/state.tsnew file mode 100644index 0000000..db381d8--- /dev/null+++ b/backend/src/utils/selfBackup/state.ts@@ -0,0 +1,43 @@+/**+ * Runtime state for self-backup, stored at `config/self_backup_state.json`.+ *+ * Deliberately NOT in the settings blob: `SettingsStore.update()` is a whole-blob+ * replace and the Settings UI PUTs the entire blob on every save, so blob-resident+ * `lastSuccessAt` would be silently clobbered by an unrelated tab save.+ *+ * Follows the device_settings.json / restic_global.json precedent in utils/globalSettings.ts.+ * It lives under config/, so the payload spec already ships it in the blob.+ */++import fs from 'fs';+import path from 'path';+import { appPaths } from '../AppPaths';++export interface SelfBackupState {+ lastRunAt?: string;+ lastSuccessAt?: string;+ lastError?: string | null;+ lastFingerprint?: string;+ lastBlobName?: string;+}++const getStatePath = () => path.join(appPaths.getConfigDir(), 'self_backup_state.json');++export function readSelfBackupState(): SelfBackupState {+ try {+ const filePath = getStatePath();+ if (fs.existsSync(filePath)) {+ return JSON.parse(fs.readFileSync(filePath, 'utf-8')) as SelfBackupState;+ }+ } catch (error) {+ console.error('[selfBackup] Failed to read self_backup_state.json:', error);+ }+ return {};+}++/** Read-modify-write: callers only ever supply the fields they changed. */+export function writeSelfBackupState(update: Partial<SelfBackupState>): SelfBackupState {+ const merged = { ...readSelfBackupState(), ...update };+ fs.writeFileSync(getStatePath(), JSON.stringify(merged, null, 2), { mode: 0o600 });+ return merged;+}diff --git a/frontend/src/components/Settings/SelfBackupSettings/BackupsListModal.tsx b/frontend/src/components/Settings/SelfBackupSettings/BackupsListModal.tsxnew file mode 100644index 0000000..5cfefa6--- /dev/null+++ b/frontend/src/components/Settings/SelfBackupSettings/BackupsListModal.tsx@@ -0,0 +1,74 @@+import { toast } from 'react-toastify';+import Modal from '../../common/Modal/Modal';+import Icon from '../../common/Icon/Icon';+import { useGetSelfBackupBackups, useDownloadSelfBackup } from '../../../services/settings';+import { formatBytes } from '../../../utils/helpers';+import classes from './SelfBackupSettings.module.scss';++interface BackupsListModalProps {+ settingsID: string;+ closeModal: () => void;+}++function formatDate(iso?: string): string {+ if (!iso) return '—';+ const date = new Date(iso);+ return Number.isNaN(date.getTime()) ? '—' : date.toLocaleString();+}++const BackupsListModal = ({ settingsID, closeModal }: BackupsListModalProps) => {+ const { data, isLoading, isError, error } = useGetSelfBackupBackups(settingsID);+ const downloadMutation = useDownloadSelfBackup();+ const backups = data?.result || [];+ const downloadingName = downloadMutation.isPending ? downloadMutation.variables?.blobName : undefined;++ const download = (blobName: string) => {+ downloadMutation.mutate(+ { settingsID, blobName },+ { onError: (err: Error) => toast.error('Could not download backup. ' + (err?.message || '')) },+ );+ };++ return (+ <Modal title="Pluton Backups" width="640px" closeModal={closeModal}>+ <div className={classes.backupsModal}>+ {isLoading ? (+ <div className={classes.backupsEmpty}>+ <Icon type="loading" size={16} /> Loading backups…+ </div>+ ) : isError ? (+ <div className={classes.backupsEmpty}>Could not load backups. {(error as Error)?.message || ''}</div>+ ) : backups.length === 0 ? (+ <div className={classes.backupsEmpty}>No backups found yet.</div>+ ) : (+ <ul className={classes.backupsList}>+ {backups.map((backup) => (+ <li key={backup.name} className={classes.backupRow}>+ <div className={classes.backupInfo}>+ <Icon type="box" size={20} />+ <div className={classes.backupInfoTitle}>+ <span className={classes.backupName}>{backup.name}</span>+ <span className={classes.backupMeta}>+ {formatBytes(backup.size)} · {formatDate(backup.modTime)}+ </span>+ </div>+ </div>+ <button+ className={classes.downloadBtn}+ onClick={() => download(backup.name)}+ disabled={downloadMutation.isPending}+ title="Download backup"+ >+ <Icon type={downloadingName === backup.name ? 'loading' : 'download'} size={14} />+ Download+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ </Modal>+ );+};++export default BackupsListModal;diff --git a/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.module.scss b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.module.scssnew file mode 100644index 0000000..a7acd2d--- /dev/null+++ b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.module.scss@@ -0,0 +1,188 @@+.field {+ margin-bottom: 1rem;++ label {+ font-weight: 600;+ font-size: 0.75rem;+ color: var(--content-text-color);+ display: block;+ margin-bottom: 6px;+ }++ div[class*='_storagePickerInput_'] {+ padding: 0;+ border: none;+ max-width: 600px;+ }+}++.intro {+ margin: 0 0 1.25rem;+ font-size: 0.85rem;+ line-height: 1.5;+ color: var(--content-text-color-light);+}++.actions {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 10px;+ margin-top: 1.5rem;+ padding-top: 1.25rem;+ border-top: 1px solid var(--line-color);+}++.backupNowBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 9px 16px;+ border-radius: 6px;+ font-weight: 600;+ cursor: pointer;+ background-color: var(--primary-color);+ color: var(--primary-text-color);++ &:disabled {+ opacity: 0.55;+ cursor: not-allowed;+ }+}++.viewBackupsBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 9px 14px;+ border-radius: 6px;+ font-weight: 600;+ cursor: pointer;+ background: transparent;+ color: var(--content-text-color);+ border: 1px solid var(--line-color);+ transition: all 0.12s linear;++ &:hover {+ border-color: var(--primary-color-mid);+ color: var(--primary-color);+ }++ &:disabled {+ opacity: 0.55;+ cursor: not-allowed;+ }+}++// Status is now a single line of colour-coded text on the far right of the action row.+// No background — only the text colour changes with the status type.+.statusText {+ margin-left: auto;+ font-size: 0.75rem;+ font-weight: 600;+}++// .statusOk {+// color: var(--success-text-color);+// }++.statusWarn {+ color: var(--error-button-color);+}++.statusMuted {+ color: var(--content-text-color-light);+}++.actionsHint {+ font-size: 0.78rem;+ color: var(--content-text-color-light);+}++// ---- Backups modal ----+.backupsModal {+ min-width: 0;+}++.backupsEmpty {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 1.5rem 0.5rem;+ font-size: 0.85rem;+ color: var(--content-text-color-light);+}++.backupsList {+ list-style: none;+ margin: 0;+ padding: 0;+ max-height: 60vh;+ overflow-y: auto;+}++.backupRow {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 6px;+ border-bottom: 1px solid var(--line-color);++ &:last-child {+ border-bottom: none;+ }+}++.backupInfo {+ display: flex;+ gap: 12px;+ align-items: center;+ :global(.icon) {+ color: var(--icon-color);+ }+ .backupInfoTitle {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+}++.backupName {+ font-size: 0.8rem;+ font-weight: 600;+ color: var(--content-text-color);+ word-break: break-all;+}++.backupMeta {+ font-size: 0.72rem;+ color: var(--content-text-color-light);+}++.downloadBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ flex-shrink: 0;+ padding: 7px 12px;+ border-radius: 6px;+ font-size: 0.78rem;+ font-weight: 600;+ cursor: pointer;+ background: transparent;+ color: var(--content-text-color);+ border: 1px solid var(--line-color);+ transition: all 0.12s linear;++ &:hover {+ border-color: var(--primary-color-mid);+ color: var(--primary-color);+ }++ &:disabled {+ opacity: 0.55;+ cursor: not-allowed;+ }+}diff --git a/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsxnew file mode 100644index 0000000..6e2ae38--- /dev/null+++ b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx@@ -0,0 +1,160 @@+import { useState } from 'react';+import { toast } from 'react-toastify';+import Icon from '../../common/Icon/Icon';+import Toggle from '../../common/form/Toggle/Toggle';+import NumberInput from '../../common/form/NumberInput/NumberInput';+import StoragePicker from '../../common/form/StoragePicker/StoragePicker';+import { useGetSelfBackupStatus, useRunSelfBackup } from '../../../services/settings';+import BackupsListModal from './BackupsListModal';+import classes from './SelfBackupSettings.module.scss';++interface SelfBackupSettingsProps {+ settingsID: number;+ settings: Record<string, any>;+ onUpdate: (settings: Record<string, any>) => void;+}++export const SELF_BACKUP_DEFAULTS = {+ enabled: false,+ storageId: '',+ storageName: '',+ path: '',+ intervalHours: 12,+ retention: 10,+ notifyOnFailure: false,+};++// Any connected email integration can carry the failure notification. Ntfy is push, not email.+const EMAIL_INTEGRATIONS = ['smtp', 'sendgrid', 'mailgun', 'brevo', 'resend', 'awsSes'];++function formatRelative(iso?: string): string {+ if (!iso) return 'never';+ const diffMs = Date.now() - new Date(iso).getTime();+ if (Number.isNaN(diffMs)) return 'unknown';++ const minutes = Math.floor(diffMs / 60000);+ if (minutes < 1) return 'just now';+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`;+ const days = Math.floor(hours / 24);+ return `${days} day${days === 1 ? '' : 's'} ago`;+}++const SelfBackupSettings = ({ settings, settingsID, onUpdate }: SelfBackupSettingsProps) => {+ const selfBackup = { ...SELF_BACKUP_DEFAULTS, ...(settings?.selfBackup || {}) };+ const { data } = useGetSelfBackupStatus(settingsID ? String(settingsID) : '');+ const runMutation = useRunSelfBackup();+ const status = data?.result;+ const [showBackups, setShowBackups] = useState(false);++ const update = (patch: Record<string, any>) => onUpdate({ ...settings, selfBackup: { ...selfBackup, ...patch } });++ // This is the one backup whose failure would otherwise be discovered during a disaster,+ // so a stale or failed run is surfaced loudly rather than tucked away in a log.+ const isStale =+ !!status?.enabled && (!status.lastSuccessAt || Date.now() - new Date(status.lastSuccessAt).getTime() > 2 * status.intervalHours * 3600 * 1000);++ // The POST only queues the job and returns 202, so its own isPending covers just that+ // round trip. `status.running` is what reports the actual run, straight from the job queue.+ const isRunning = runMutation.isPending || !!status?.running;++ // Two hard prerequisites for the failure-notification toggle: a connected email integration+ // (only ever marked `connected` after a successful test send) and an admin email to send to.+ const emailConnected = EMAIL_INTEGRATIONS.some((type) => settings?.integration?.[type]?.connected);+ const adminEmailSet = !!String(settings?.admin_email || '').trim();+ const canNotifyOnFailure = emailConnected && adminEmailSet;++ // Only the title text, coloured by type — no background. Replaced while a run is in flight.+ const statusView = (() => {+ if (isRunning) return { text: 'Backing up Pluton…', className: classes.statusMuted };+ if (status?.lastError) return { text: 'Last backup failed', className: classes.statusWarn };+ if (isStale) return { text: 'No recent backup', className: classes.statusWarn };+ return { text: `Last backed up ${formatRelative(status?.lastSuccessAt)}`, className: classes.statusOk };+ })();++ const runNow = () => {+ runMutation.mutate(String(settingsID), {+ onSuccess: () => toast.success('Backup queued. This page will update when it finishes.', { autoClose: 5000 }),+ onError: (error: Error) => toast.error('Could not start backup. ' + (error?.message || '')),+ });+ };++ return (+ <div>+ <div className={classes.field}>+ <Toggle+ label="Back up Pluton's configuration"+ fieldValue={selfBackup.enabled}+ onUpdate={(val) => update({ enabled: val })}+ inline={true}+ hint={`Backs up Pluton's own configuration (plans, storages, credentials and history) as a single encrypted file.`}+ />+ </div>++ {selfBackup.enabled && (+ <>+ <div className={classes.field}>+ <label>Where to store backups</label>+ <StoragePicker+ storageId={selfBackup.storageId}+ storagePath={selfBackup.path}+ onUpdate={({ storage, path }) => update({ storageId: storage.id, storageName: storage.name, path })}+ />+ </div>+ <div className={classes.field}>+ <NumberInput+ label="Back up every (hours)"+ fieldValue={selfBackup.intervalHours}+ onUpdate={(val) => update({ intervalHours: val })}+ min={1}+ hint="Pluton only uploads when something has actually changed."+ inline={false}+ />+ </div>+ <div className={classes.field}>+ <NumberInput+ label="Number of backups to keep"+ fieldValue={selfBackup.retention}+ onUpdate={(val) => update({ retention: val })}+ min={1}+ hint="Older backups beyond this count are deleted from the storage."+ inline={false}+ />+ </div>+ <div className={classes.field}>+ <Toggle+ label="Email me if a backup fails"+ fieldValue={selfBackup.notifyOnFailure}+ onUpdate={(val) => update({ notifyOnFailure: val })}+ inline={true}+ disabled={!canNotifyOnFailure}+ hint={+ canNotifyOnFailure+ ? `Sends an email to the admin address (${settings?.admin_email}) whenever a backup run fails.`+ : !adminEmailSet+ ? 'Set an Admin Email under the General tab to enable failure notifications.'+ : 'Connect an email integration under the Integrations tab to enable failure notifications.'+ }+ />+ </div>+ <div className={classes.actions}>+ <button className={classes.backupNowBtn} onClick={runNow} disabled={isRunning || !status?.enabled}>+ <Icon type={isRunning ? 'loading' : 'backup'} size={12} />+ {isRunning ? 'Backing up...' : 'Backup now'}+ </button>+ <button className={classes.viewBackupsBtn} onClick={() => setShowBackups(true)}>+ <Icon type="rows" size={12} />+ View backups+ </button>+ {status?.enabled && <span className={`${classes.statusText} ${statusView.className}`}>{statusView.text}</span>}+ </div>+ </>+ )}++ {showBackups && <BackupsListModal settingsID={String(settingsID)} closeModal={() => setShowBackups(false)} />}+ </div>+ );+};++export default SelfBackupSettings;diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.tsindex 5228e06..124e9df 100644--- a/frontend/src/components/index.ts+++ b/frontend/src/components/index.ts@@ -115,6 +115,7 @@ export { default as RestoreWizard } from './Restore/RestoreWizard/RestoreWizard'// Settings componentsexport { default as AppLogs } from './Settings/AppLogs/AppLogs';export { default as GeneralSettings } from './Settings/GeneralSettings/GeneralSettings';+export { default as SelfBackupSettings } from './Settings/SelfBackupSettings/SelfBackupSettings';export { default as IntegrationSettings } from './Settings/IntegrationSettings/IntegrationSettings';export { default as SMTPSettings } from './Settings/IntegrationSettings/SMTPSettings';export { default as NtfySettings } from './Settings/IntegrationSettings/NtfySettings';diff --git a/frontend/src/routes/Settings/Settings.module.scss b/frontend/src/routes/Settings/Settings.module.scssindex b0bed57..0c9ee5b 100644--- a/frontend/src/routes/Settings/Settings.module.scss+++ b/frontend/src/routes/Settings/Settings.module.scss@@ -11,7 +11,7 @@margin-top: 20px;.sidebar {- width: 180px;+ width: 190px;height: 100%;position: absolute;border-radius: 6px 0 0 6px;diff --git a/frontend/src/routes/Settings/Settings.tsx b/frontend/src/routes/Settings/Settings.tsxindex b548439..d1ad56a 100644--- a/frontend/src/routes/Settings/Settings.tsx+++ b/frontend/src/routes/Settings/Settings.tsx@@ -9,6 +9,7 @@ import AnimatedWrapper from '../../components/common/AnimatedWrapper/AnimatedWraimport AppLogs from '../../components/Settings/AppLogs/AppLogs';import SidePanel from '../../components/common/SidePanel/SidePanel';import GeneralSettings from '../../components/Settings/GeneralSettings/GeneralSettings';+import SelfBackupSettings from '../../components/Settings/SelfBackupSettings/SelfBackupSettings';const Settings = () => {const [tab, setTab] = useState(() => {@@ -62,6 +63,9 @@ const Settings = () => {<li className={`${tab === 'integration' ? classes.tabActive : ''}`} onClick={() => setTab('integration')}><Icon type="integration" size={13} /> Integrations</li>+ <li className={`${tab === 'backup' ? classes.tabActive : ''}`} onClick={() => setTab('backup')}>+ <Icon type="backup" size={13} /> Backup Pluton+ </li></ul><button className={classes.updateBtn} onClick={() => updateSettings()}><Icon type={settingsMutation.isPending ? 'loading' : 'check'} size={11} /> {settingsMutation.isPending ? 'Updating...' : 'Update'}@@ -88,6 +92,16 @@ const Settings = () => {/></div></AnimatedWrapper>+ <AnimatedWrapper isVisible={tab === 'backup'} animationType="slide-left" animationDuration={100} absolute={true}>+ <div className={classes.tabContent}>+ <h4>Backup Pluton</h4>+ <SelfBackupSettings+ settingsID={settingsID}+ settings={settings}+ onUpdate={(st: Record<string, any>) => setSettings({ ...settings, ...st })}+ />+ </div>+ </AnimatedWrapper></div></div>{showAppLogs && (diff --git a/frontend/src/services/settings.ts b/frontend/src/services/settings.tsindex a483876..adbf66c 100644--- a/frontend/src/services/settings.ts+++ b/frontend/src/services/settings.ts@@ -53,6 +53,8 @@ export function useUpdateSettings() {onSuccess: (res) => {console.log('# Settings Updated! :', res);queryClient.invalidateQueries({ queryKey: ['settings'] });+ queryClient.invalidateQueries({ queryKey: ['selfBackupStatus'] });+ queryClient.invalidateQueries({ queryKey: ['selfBackupBackups'] });},});}@@ -134,6 +136,139 @@ export function useGetDownloadAppLogs() {});}+// ============== Pluton Self-Backup API ==============++export interface SelfBackupStatus {+ enabled: boolean;+ storageId: string;+ storageName: string;+ path: string;+ intervalHours: number;+ retention: number;+ notifyOnFailure: boolean;+ lastRunAt?: string;+ lastSuccessAt?: string;+ lastError?: string | null;+ lastBlobName?: string;+ running: boolean;+}++export interface SelfBackupBlob {+ name: string;+ size: number;+ modTime?: string;+}++export async function getSelfBackupStatus(settingsID: string) {+ const res = await fetch(`${API_URL}/settings/${settingsID}/self-backup/status`, {+ method: 'GET',+ credentials: 'include',+ });+ const data = await res.json();+ if (!data.success) {+ throw new Error(data.error);+ }+ return data as { success: boolean; result: SelfBackupStatus };+}++export function useGetSelfBackupStatus(settingsID: string) {+ return useQuery({+ queryKey: ['selfBackupStatus', settingsID],+ queryFn: () => getSelfBackupStatus(settingsID),+ enabled: !!settingsID,+ refetchOnMount: true,+ retry: false,+ refetchInterval: (query) => (query.state.data?.result?.running ? 3000 : false),+ });+}++export async function runSelfBackup(settingsID: string) {+ const res = await fetch(`${API_URL}/settings/${settingsID}/self-backup/run`, {+ method: 'POST',+ credentials: 'include',+ });+ const data = await res.json();+ if (!data.success) {+ throw new Error(data.error);+ }+ return data;+}++export function useRunSelfBackup() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: runSelfBackup,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['selfBackupStatus'] });+ queryClient.invalidateQueries({ queryKey: ['selfBackupBackups'] });+ },+ });+}++export async function getSelfBackupBackups(settingsID: string) {+ const res = await fetch(`${API_URL}/settings/${settingsID}/self-backup/backups`, {+ method: 'GET',+ credentials: 'include',+ });+ const data = await res.json();+ if (!data.success) {+ throw new Error(data.error);+ }+ return data as { success: boolean; result: SelfBackupBlob[] };+}++export function useGetSelfBackupBackups(settingsID: string, enabled = true) {+ return useQuery({+ queryKey: ['selfBackupBackups', settingsID],+ queryFn: () => getSelfBackupBackups(settingsID),+ enabled: enabled && !!settingsID,+ refetchOnMount: true,+ retry: false,+ });+}++export async function downloadSelfBackup({ settingsID, blobName }: { settingsID: string; blobName: string }) {+ const res = await fetch(`${API_URL}/settings/${settingsID}/self-backup/backups/${encodeURIComponent(blobName)}/download`, {+ method: 'GET',+ credentials: 'include',+ });+ if (!res.ok) {+ const data = await res.json();+ throw new Error(data.error);+ }++ const filename = res.headers.get('content-disposition')?.split('filename=')[1]?.replace(/"/g, '') || blobName;++ const reader = res.body?.getReader();+ const stream = new ReadableStream({+ async start(controller) {+ while (true) {+ const { done, value } = await reader!.read();+ if (done) break;+ controller.enqueue(value);+ }+ controller.close();+ reader!.releaseLock();+ },+ });++ const blob = await new Response(stream).blob();+ const url = window.URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = filename;+ document.body.appendChild(link);+ link.click();+ link.remove();+ window.URL.revokeObjectURL(url);+}++export function useDownloadSelfBackup() {+ return useMutation({+ mutationFn: downloadSelfBackup,+ });+}+export async function validateIntegration(updatePayload: {settingsID: number;type: string;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex db0b1ea..6b982a0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -107,6 +107,9 @@ importers:systeminformation:specifier: ^5.31.0version: 5.31.0+ tar-stream:+ specifier: ^3.1.7+ version: 3.1.7tsx:specifier: ^4.21.0version: 4.21.0@@ -156,6 +159,9 @@ importers:'@types/supertest':specifier: ^6.0.3version: 6.0.3+ '@types/tar-stream':+ specifier: ^3.1.4+ version: 3.1.4concurrently:specifier: ^9.1.2version: 9.2.1@@ -2599,6 +2605,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-8WzXq62EXFhJ7QsH3Ocb/iKQ/Ty9ZVWnVzoTKc9tyyFRRF3a74Tk2+TLFgaFFw364Ere+npzHKEJ6ga2LzIL7w==}+ '@types/[email protected]':+ resolution: {integrity: sha512-921gW0+g29mCJX0fRvqeHzBlE/XclDaAG0Ousy1LCghsOhvaKacDeRGEVzQP9IPfKn8Vysy7FEXAIxycpc/CMg==}+'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}@@ -8741,6 +8750,10 @@ snapshots:'@types/methods': 1.1.4'@types/superagent': 8.1.9+ '@types/[email protected]':+ dependencies:+ '@types/node': 22.18.13+'@types/[email protected]': {}'@types/[email protected]': {}