Skip to content

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

fix: resolves broken self-backup for local storage

towfiqi564c4a63fd97
diff --git a/backend/__tests__/services/SelfBackupService.test.ts b/backend/__tests__/services/SelfBackupService.test.ts
index 2c80292..9735848 100644
--- a/backend/__tests__/services/SelfBackupService.test.ts
+++ b/backend/__tests__/services/SelfBackupService.test.ts
@@ -68,6 +68,7 @@ function makeService(
overrides: {
selfBackup?: any;
storageName?: string | null;
+ storage?: Record<string, any>;
adminEmail?: string;
integration?: Record<string, any>;
} = {}
@@ -89,7 +90,14 @@ function makeService(
getById: jest
.fn()
.mockResolvedValue(
- overrides.storageName === null ? null : { id: 'stor-1', name: overrides.storageName ?? 'mybackups' }
+ overrides.storageName === null
+ ? null
+ : {
+ id: 'stor-1',
+ type: 's3',
+ name: overrides.storageName ?? 'mybackups',
+ ...(overrides.storage ?? {}),
+ }
),
} as any;
@@ -205,6 +213,52 @@ describe('SelfBackupService', () => {
expect(rcloneCalls('copyto')[0][0][2]).toBe(`mybackups:pluton/self/${result.blobName}`);
});
+ describe('local storage', () => {
+ const LOCAL_STORAGE = { id: 'local', type: 'local', name: 'Local Storage' };
+
+ const makeLocalService = (targetPath: string) =>
+ makeService({
+ storage: LOCAL_STORAGE,
+ selfBackup: {
+ ...ENABLED,
+ storageId: 'local',
+ storageName: 'Local Storage',
+ path: targetPath,
+ },
+ }).service;
+
+ it('addresses the built-in local storage by its rclone remote name', async () => {
+ // The row is named "Local Storage", but rclone only knows the section "local".
+ const service = makeLocalService(tmpDir);
+ const result = await service.run();
+
+ expect(rcloneCalls('copyto')[0][0][2]).toBe(`local:${tmpDir}/${result.blobName}`);
+ });
+
+ it('keeps a local path absolute, trailing slash aside', async () => {
+ // Stripping the leading slash would make rclone resolve it against its own cwd.
+ const service = makeLocalService(`${tmpDir}/`);
+ const result = await service.run();
+
+ expect(rcloneCalls('copyto')[0][0][2]).toBe(`local:${tmpDir}/${result.blobName}`);
+ });
+
+ it('refuses a local folder that does not exist instead of creating one', async () => {
+ // rclone would create it and report success, quietly backing up into the container.
+ const service = makeLocalService(path.join(tmpDir, 'not-mounted'));
+
+ await expect(service.run()).rejects.toThrow(/does not exist or is not writable/);
+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();
+ });
+
+ it('refuses an empty local path, which would mean rclone\'s working directory', async () => {
+ const service = makeLocalService('');
+
+ await expect(service.run()).rejects.toThrow(/Select a folder/);
+ expect(mockRunRcloneCommand).not.toHaveBeenCalled();
+ });
+ });
+
it('records success state including the fingerprint it uploaded', async () => {
const { service } = makeService();
const result = await service.run();
diff --git a/backend/src/jobs/JobProcessor.ts b/backend/src/jobs/JobProcessor.ts
index ddc77d0..7978506 100644
--- a/backend/src/jobs/JobProcessor.ts
+++ b/backend/src/jobs/JobProcessor.ts
@@ -222,10 +222,6 @@ class JobProcessor extends EventEmitter {
);
// Emit a specific event for permanent failures that listeners can act on.
// e.g., backup_failed, integrity_failed, 'prune_failed
- console.log(
- '######### JobProcessor-> Emit Fail Event :',
- `${job.name.toLowerCase()}_failed`
- );
this.emit(`${job.name.toLowerCase()}_failed`, {
...job.payload,
error: error.message || 'Unknown error after multiple retries.',
diff --git a/backend/src/services/SelfBackupService.ts b/backend/src/services/SelfBackupService.ts
index 7a5dfd1..047febf 100644
--- a/backend/src/services/SelfBackupService.ts
+++ b/backend/src/services/SelfBackupService.ts
@@ -1,4 +1,5 @@
import fsp from 'fs/promises';
+import { constants as fsConstants } from 'fs';
import os from 'os';
import path from 'path';
import type { Database as SqliteDatabase } from 'better-sqlite3';
@@ -15,6 +16,7 @@ import { rcloneCopyTo, rcloneDeleteFile, rcloneLsJson } from '../utils/rclone/he
import { jobQueue } from '../jobs/JobQueue';
import { SELF_BACKUP_JOB_NAME } from '../jobs/systemJobs';
import { AppError } from '../utils/AppError';
+import { normalizeStorageName } from '../utils/helpers';
import { IntegrationTypes, SelfBackupSettings } from '../types/settings';
import { NotificationChannelResolver } from '../notifications/channels/NotificationChannelResolver';
import { SelfBackupFailedNotification } from '../notifications/templates/email/backup/SelfBackupFailedNotification';
@@ -28,6 +30,12 @@ const SIDECAR_NAME = 'pluton-recovery.json';
export type SelfBackupRunStatus = 'disabled' | 'skipped' | 'uploaded';
+/** The rclone remote behind a storage. `name` is the config section, not the display name. */
+interface SelfBackupRemote {
+ name: string;
+ isLocal: boolean;
+}
+
export interface SelfBackupRunResult {
status: SelfBackupRunStatus;
blobName?: string;
@@ -104,7 +112,8 @@ export class SelfBackupService {
}
// The name is user-editable after save, so the zod check at save time isn't enough.
- const remoteName = await this.resolveRemoteName(settings);
+ const remote = await this.resolveRemote(settings);
+ await this.assertLocalTargetUsable(remote, settings.path);
const tmpDir = await fsp.mkdtemp(path.join(appPaths.getTempDir(), 'self-backup-'));
try {
@@ -122,7 +131,7 @@ export class SelfBackupService {
const blobPath = path.join(tmpDir, blobName);
await fsp.writeFile(blobPath, blob, { mode: 0o600 });
- const destDir = this.remoteDir(remoteName, settings.path);
+ const destDir = this.remoteDir(remote, settings.path);
await rcloneCopyTo(blobPath, this.remoteFile(destDir, blobName), undefined, {
timeoutMs: RCLONE_TIMEOUT_MS,
});
@@ -228,7 +237,8 @@ export class SelfBackupService {
return pageCount;
}
- protected async resolveRemoteName(settings: SelfBackupSettings): Promise<string> {
+ /** The built-in local storage is named "Local Storage" but its rclone section is "local". */
+ protected async resolveRemote(settings: SelfBackupSettings): Promise<SelfBackupRemote> {
const storage = await this.storageStore.getById(settings.storageId);
if (!storage) {
throw new AppError(
@@ -236,12 +246,47 @@ export class SelfBackupService {
`The storage selected for Pluton backup no longer exists (id: ${settings.storageId}).`
);
}
- return storage.name;
+ return {
+ name: storage.id === 'local' ? 'local' : normalizeStorageName(storage.name),
+ isLocal: storage.type === 'local',
+ };
}
- protected remoteDir(remoteName: string, targetPath: string): string {
- const cleaned = targetPath.replace(/^\/+|\/+$/g, '');
- return `${remoteName}:${cleaned}`;
+ /**
+ * rclone resolves a relative root against its own working directory, so a local target
+ * must keep its leading slash. A cloud remote must not have one.
+ */
+ protected remoteDir(remote: SelfBackupRemote, targetPath: string): string {
+ const trimmed = targetPath.replace(/\/+$/g, '');
+ const cleaned = remote.isLocal ? trimmed : trimmed.replace(/^\/+/, '');
+ return `${remote.name}:${cleaned}`;
+ }
+
+ /**
+ * rclone would create a missing local directory and report success, so a path that is not
+ * mounted into the container silently backs up into the container itself.
+ */
+ protected async assertLocalTargetUsable(
+ remote: SelfBackupRemote,
+ targetPath: string
+ ): Promise<void> {
+ if (!remote.isLocal) return;
+
+ const dir = targetPath.replace(/\/+$/g, '');
+ if (!dir) {
+ throw new AppError(400, 'Select a folder on the local storage for Pluton backup.');
+ }
+
+ try {
+ const stat = await fsp.stat(dir);
+ if (!stat.isDirectory()) throw new Error('not a directory');
+ await fsp.access(dir, fsConstants.W_OK);
+ } catch {
+ throw new AppError(
+ 400,
+ `The Pluton backup folder "${dir}" does not exist or is not writable. In Docker, bind-mount it into the container as a read-write volume.`
+ );
+ }
}
/**
@@ -281,8 +326,8 @@ export class SelfBackupService {
const settings = await this.resolveSettings();
if (!settings.storageId) return [];
- const remoteName = await this.resolveRemoteName(settings);
- const destDir = this.remoteDir(remoteName, settings.path);
+ const remote = await this.resolveRemote(settings);
+ const destDir = this.remoteDir(remote, settings.path);
const items = await rcloneLsJson(destDir, undefined, { timeoutMs: RCLONE_TIMEOUT_MS });
return items
.filter(item => !item.IsDir && BLOB_NAME_RE.test(item.Name))
@@ -301,8 +346,8 @@ export class SelfBackupService {
}
const settings = await this.resolveSettings();
- const remoteName = await this.resolveRemoteName(settings);
- const destDir = this.remoteDir(remoteName, settings.path);
+ const remote = await this.resolveRemote(settings);
+ const destDir = this.remoteDir(remote, settings.path);
const tmpDir = await fsp.mkdtemp(path.join(appPaths.getTempDir(), 'self-backup-dl-'));
const localPath = path.join(tmpDir, blobName);
diff --git a/docker-compose.yml b/docker-compose.yml
index 163d962..f607253 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -31,6 +31,12 @@ services:
# - /var/lib/docker/volumes:/mnt/docker-volumes:ro #linux
# - C:/ProgramData/docker/volumes:/mnt/docker-volumes:ro # Windows
+ # Example: Mount a host directory to store backups in (Local Storage)
+ # Leave out ":ro", a backup destination has to be writable. In Pluton,
+ # select the container path (/mnt/backups), not the host path.
+ # - /mnt/disk1/backups:/mnt/backups #linux
+ # - D:/backups:/mnt/backups # Windows
+
environment:
# ===== REQUIRED: Security & Authentication =====
# Generate secure random strings (min 12 characters for the first three)
diff --git a/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx
index 6e2ae38..59c98c3 100644
--- a/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx
+++ b/frontend/src/components/Settings/SelfBackupSettings/SelfBackupSettings.tsx
@@ -50,22 +50,14 @@ const SelfBackupSettings = ({ settings, settingsID, onUpdate }: SelfBackupSettin
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 };
@@ -148,6 +140,11 @@ const SelfBackupSettings = ({ settings, settingsID, onUpdate }: SelfBackupSettin
View backups
</button>
{status?.enabled && <span className={`${classes.statusText} ${statusView.className}`}>{statusView.text}</span>}
+ {!isRunning && status?.lastError && (
+ <span className={classes.erroHint} data-tooltip-id="htmlToolTip" data-tooltip-place="top" data-tooltip-html={status.lastError}>
+ <Icon type={'error-circle-filled'} color="#ff8888" size={16} />
+ </span>
+ )}
</div>
</>
)}
diff --git a/readme.md b/readme.md
index d717efc..e0b348d 100644
--- a/readme.md
+++ b/readme.md
@@ -78,6 +78,12 @@ services:
# - /var/lib/docker/volumes/wp-data/_data:/mnt/wordpress:ro
# - C:/ProgramData/docker/volumes/wp-data/_data:/mnt/wordpress:ro # Windows
+ # Example: Mount a host directory to store backups in (Local Storage)
+ # Leave out ":ro", a backup destination has to be writable. In Pluton,
+ # select the container path (/mnt/backups), not the host path.
+ # - /mnt/disk1/backups:/mnt/backups #linux
+ # - D:/backups:/mnt/backups # Windows
+
environment:
# ===== REQUIRED: Security & Authentication =====
# Generate secure random strings (min 12 characters each)