Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([data-safety-backup-source-compatibility]): restore snapshots across machine namespaces (#7175)

[._.]/ Adam Eivy9d2f0e9aae81
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index e0f30cfca6..a3e787554d 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -55,6 +55,11 @@ const HEALTH_STYLES = {
}
};
+const snapshotIdentity = (snapshot) =>
+ snapshot.selectionKey || `${snapshot.source || 'current'}/${snapshot.id}`;
+const snapshotSourceLabel = (snapshot) =>
+ snapshot.sourceLabel || snapshot.source || 'Current machine';
+
// ---------------------------------------------------------------------------
// RestorePanel
// ---------------------------------------------------------------------------
@@ -68,10 +73,12 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
const currentRequest = {
snapshotId: snapshot.id,
+ ...(snapshot.source ? { source: snapshot.source } : {}),
subdirFilter: filter.trim() || null,
};
const previewMatchesCurrentRequest = acceptedPreview
&& acceptedPreview.request.snapshotId === currentRequest.snapshotId
+ && acceptedPreview.request.source === currentRequest.source
&& acceptedPreview.request.subdirFilter === currentRequest.subdirFilter;
const handleFilterChange = useCallback((event) => {
@@ -86,6 +93,7 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
previewGenerationRef.current = generation;
const request = {
snapshotId: snapshot.id,
+ ...(snapshot.source ? { source: snapshot.source } : {}),
subdirFilter: filter.trim() || null,
};
setPreviewing(true);
@@ -105,12 +113,12 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
return;
}
if (outcome.previewResult) setAcceptedPreview({ request, result: outcome.previewResult });
- }, [snapshot.id, filter]);
+ }, [snapshot.id, snapshot.source, filter]);
const handleRestore = useCallback(async () => {
if (!previewMatchesCurrentRequest || restoring) return;
- onRestoreStateChange(snapshot.id);
+ onRestoreStateChange(snapshotIdentity(snapshot));
const result = await api.restoreBackup({
...acceptedPreview.request,
dryRun: false,
@@ -123,7 +131,7 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
toast.success(`Restore complete — ${result.changedFiles?.length ?? 0} file(s) restored`);
onClose();
}
- }, [acceptedPreview, onClose, onRestoreStateChange, previewMatchesCurrentRequest, restoring, snapshot.id]);
+ }, [acceptedPreview, onClose, onRestoreStateChange, previewMatchesCurrentRequest, restoring, snapshot]);
const preview = previewMatchesCurrentRequest ? acceptedPreview.result : null;
@@ -142,6 +150,8 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
</button>
</div>
+ <p className="text-xs text-gray-500">Source: {snapshotSourceLabel(snapshot)}</p>
+
{/* Subdirectory filter */}
<div>
<label htmlFor={filterId} className="block text-xs text-gray-500 mb-1">
@@ -242,15 +252,21 @@ function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
// the oldest — walk every rendered tuple (id + fileCount) so a stale
// server-side fileCount recount or a middle-row mutation can't hide
// behind the head/tail id check.
- compare: (prev, next) => equalListByKeys(prev, next, ['id', 'fileCount', 'incomplete', 'failed']),
+ compare: (prev, next) => equalListByKeys(prev, next, [
+ 'selectionKey', 'id', 'source', 'fileCount', 'incomplete', 'failed',
+ ]),
},
);
const [selectedId, setSelectedId] = useState(null);
const [downloadingId, setDownloadingId] = useState(null);
- const handleDownload = useCallback((snapshotId) => {
- setDownloadingId(snapshotId);
- api.downloadBackupSnapshot(snapshotId)
+ const handleDownload = useCallback((snapshot) => {
+ const identity = snapshotIdentity(snapshot);
+ setDownloadingId(identity);
+ const download = snapshot.source
+ ? api.downloadBackupSnapshot(snapshot.id, snapshot.source)
+ : api.downloadBackupSnapshot(snapshot.id);
+ download
.then(() => toast.success('Snapshot downloaded'))
// Dismissing the browser's save dialog is a choice, not a failure.
.catch(err => { if (err?.name !== 'AbortError') toast.error(`Download failed: ${err.message}`); })
@@ -274,10 +290,11 @@ function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
return (
<div className="mt-3 space-y-1">
{snapshots.map(snap => (
- <div key={snap.id}>
+ <div key={snapshotIdentity(snap)}>
<div className="flex items-center justify-between gap-2 py-1.5 px-2 rounded bg-port-bg/50 hover:bg-port-bg/80 transition-colors">
<div className="min-w-0 flex-1">
<div className="text-xs text-gray-300 font-mono truncate">{snap.id}</div>
+ <div className="text-xs text-gray-500 truncate">Source: {snapshotSourceLabel(snap)}</div>
<div className="text-xs text-gray-600">
{snap.incomplete
? 'Still being written…'
@@ -288,19 +305,19 @@ function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
</div>
<div className="flex shrink-0 items-center gap-1">
<button
- onClick={() => handleDownload(snap.id)}
+ onClick={() => handleDownload(snap)}
// Deliberately disabled across every row, not just this one:
// each download spawns a tar over the whole snapshot on the
// same external drive, so two at once only thrash the disk.
disabled={downloadingId !== null || snap.incomplete}
- aria-label={`Download snapshot ${snap.id}`}
+ aria-label={`Download snapshot ${snap.id} from ${snapshotSourceLabel(snap)}`}
className="flex items-center gap-1 px-2 py-1 text-xs text-port-accent hover:text-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed min-h-[32px]"
>
- {downloadingId === snap.id ? <BrailleSpinner /> : <Download size={12} />}
+ {downloadingId === snapshotIdentity(snap) ? <BrailleSpinner /> : <Download size={12} />}
Download
</button>
<button
- onClick={() => setSelectedId(selectedId === snap.id ? null : snap.id)}
+ onClick={() => setSelectedId(selectedId === snapshotIdentity(snap) ? null : snapshotIdentity(snap))}
disabled={snap.incomplete || snap.failed || restoringSnapshotId !== null}
title={snap.failed ? 'Failed backup snapshots can only be downloaded for salvage' : undefined}
className="flex items-center gap-1 px-2 py-1 text-xs text-port-accent hover:text-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed min-h-[32px]"
@@ -310,11 +327,11 @@ function SnapshotList({ restoringSnapshotId, onRestoreStateChange }) {
</button>
</div>
</div>
- {selectedId === snap.id && !snap.incomplete && !snap.failed && (
+ {selectedId === snapshotIdentity(snap) && !snap.incomplete && !snap.failed && (
<RestorePanel
snapshot={snap}
onClose={() => setSelectedId(null)}
- restoring={restoringSnapshotId === snap.id}
+ restoring={restoringSnapshotId === snapshotIdentity(snap)}
onRestoreStateChange={onRestoreStateChange}
/>
)}
diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsx
index 6890fc2a5b..285042f37f 100644
--- a/client/src/components/BackupWidget.test.jsx
+++ b/client/src/components/BackupWidget.test.jsx
@@ -98,6 +98,50 @@ describe('BackupWidget snapshots', () => {
expect(mockToast.success).toHaveBeenCalledWith('Snapshot downloaded');
});
+ it('keeps duplicate snapshot ids distinct and binds restore approval to source', async () => {
+ mockGetBackupSnapshots.mockResolvedValue([
+ {
+ id: 'same-id',
+ source: 'current-machine',
+ sourceLabel: 'current-machine (current machine)',
+ selectionKey: 'current-machine/same-id',
+ fileCount: 2,
+ },
+ {
+ id: 'same-id',
+ source: 'previous-machine',
+ sourceLabel: 'previous-machine',
+ selectionKey: 'previous-machine/same-id',
+ fileCount: 2,
+ },
+ ]);
+ mockRestoreBackup
+ .mockResolvedValueOnce({ changedFiles: ['brain/example.json'] })
+ .mockResolvedValueOnce({ changedFiles: ['brain/example.json'] });
+ renderWidget();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Snapshots' }));
+ expect(await screen.findByText('Source: previous-machine')).toBeInTheDocument();
+ fireEvent.click(screen.getAllByRole('button', { name: 'Restore' })[1]);
+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
+
+ expect(await screen.findByText('brain/example.json')).toBeInTheDocument();
+ expect(mockRestoreBackup).toHaveBeenNthCalledWith(1, {
+ snapshotId: 'same-id',
+ source: 'previous-machine',
+ subdirFilter: null,
+ dryRun: true,
+ }, { silent: true });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Restore 1 file(s)' }));
+ await waitFor(() => expect(mockRestoreBackup).toHaveBeenNthCalledWith(2, {
+ snapshotId: 'same-id',
+ source: 'previous-machine',
+ subdirFilter: null,
+ dryRun: false,
+ }, { silent: true }));
+ });
+
it('stays silent when the user dismisses the save dialog', async () => {
mockDownloadBackupSnapshot.mockRejectedValue(
Object.assign(new Error('The user aborted a request.'), { name: 'AbortError' }),
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 28e831c236..680ed7c368 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useId } from 'react';
+import { useState, useEffect, useId, useRef } from 'react';
import { Save, Plus, X, Play, ShieldOff, ChevronDown, ChevronRight } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
@@ -19,6 +19,10 @@ const sameSet = (a, b) => a.length === b.length && a.every(x => b.includes(x));
// null, or any other shape. Normalize before it reaches React state — otherwise
// downstream `.some` / `.includes` / `.filter` calls crash the Backup tab.
const asArray = (v) => Array.isArray(v) ? v : [];
+const snapshotIdentity = (snapshot) =>
+ snapshot.selectionKey || `${snapshot.source || 'current'}/${snapshot.id}`;
+const snapshotSourceLabel = (snapshot) =>
+ snapshot.sourceLabel || snapshot.source || 'Current machine';
export function BackupTab() {
const destPathId = useId();
@@ -49,8 +53,10 @@ export function BackupTab() {
const [pgBackup, setPgBackup] = useState(null);
const [backupStatus, setBackupStatus] = useState('never');
const [snapshots, setSnapshots] = useState([]);
- const [restoreTarget, setRestoreTarget] = useState(null); // snapshotId pending confirm
+ const [showAllSnapshots, setShowAllSnapshots] = useState(false);
+ const [restoreTarget, setRestoreTarget] = useState(null); // source-bound request pending confirm
const [restorePreview, setRestorePreview] = useState(null); // dry-run result
+ const restorePreviewGenerationRef = useRef(0);
// The default-exclusions catalog is a 15+ row reference list the user rarely
// edits — collapsed by default so the fields they came to change (destination,
// enabled, schedule) and the action bar are what the tab actually shows.
@@ -193,12 +199,19 @@ export function BackupTab() {
);
};
- const handleRestoreDb = async (snapshotId) => {
+ const handleRestoreDb = async (snapshot) => {
+ const generation = restorePreviewGenerationRef.current + 1;
+ restorePreviewGenerationRef.current = generation;
setRestorePreview(null);
setRestoreTarget(null);
+ const request = {
+ snapshotId: snapshot.id,
+ ...(snapshot.source ? { source: snapshot.source } : {}),
+ };
// Dry-run first to show what would restore, then open the confirm modal.
- const preview = await restoreDatabase({ snapshotId, dryRun: true }, { silent: true })
+ const preview = await restoreDatabase({ ...request, dryRun: true }, { silent: true })
.catch(() => null);
+ if (restorePreviewGenerationRef.current !== generation) return;
if (!preview || preview.status === 'skipped') {
toast.error(preview?.reason === 'no_dump' ? 'No DB dump in this snapshot' : 'DB restore unavailable');
return;
@@ -213,16 +226,16 @@ export function BackupTab() {
return;
}
setRestorePreview(preview);
- setRestoreTarget(snapshotId);
+ setRestoreTarget({ request, sourceLabel: snapshotSourceLabel(snapshot) });
};
const confirmRestoreDb = async () => {
- const snapshotId = restoreTarget;
+ const target = restoreTarget;
setRestoreTarget(null);
- const result = await restoreDatabase({ snapshotId, dryRun: false }, { silent: true })
+ const result = await restoreDatabase({ ...target.request, dryRun: false }, { silent: true })
.catch(() => ({ status: 'failed', reason: 'request_error' }));
if (result.status === 'ok') {
- toast.success(`Database restored from ${snapshotId}`, { icon: '💾' });
+ toast.success(`Database restored from ${target.request.snapshotId}`, { icon: '💾' });
} else {
toast.error(`DB restore failed: ${result.reason || 'unknown'}`);
}
@@ -367,10 +380,11 @@ export function BackupTab() {
<div className="space-y-2">
<p className="block text-sm text-gray-400">Snapshots</p>
<ul className="space-y-1.5">
- {snapshots.slice(0, 10).map((snap) => (
- <li key={snap.id} className="flex items-center justify-between gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5">
+ {(showAllSnapshots ? snapshots : snapshots.slice(0, 10)).map((snap) => (
+ <li key={snapshotIdentity(snap)} className="flex items-center justify-between gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5">
<span className="min-w-0">
<span className="block text-gray-300 truncate">{snap.id}</span>
+ <span className="block text-gray-500 truncate">Source: {snapshotSourceLabel(snap)}</span>
{snap.failed && (
<span className="block text-port-error">Backup failed — download only</span>
)}
@@ -379,7 +393,7 @@ export function BackupTab() {
)}
</span>
<button
- onClick={() => handleRestoreDb(snap.id)}
+ onClick={() => handleRestoreDb(snap)}
disabled={snap.failed || snap.incomplete}
title={snap.failed ? 'Failed backup snapshots can only be downloaded for salvage' : undefined}
className="shrink-0 px-2 py-1 bg-port-border hover:bg-port-border/70 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
@@ -389,6 +403,16 @@ export function BackupTab() {
</li>
))}
</ul>
+ {snapshots.length > 10 && (
+ <button
+ type="button"
+ onClick={() => setShowAllSnapshots(value => !value)}
+ aria-expanded={showAllSnapshots}
+ className="text-xs text-port-accent hover:text-port-accent/80 transition-colors min-h-[32px]"
+ >
+ {showAllSnapshots ? 'Show newest 10 snapshots' : `Show all ${snapshots.length} snapshots`}
+ </button>
+ )}
</div>
)}
@@ -402,7 +426,8 @@ export function BackupTab() {
<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
<h3 className="text-white text-sm font-medium">Restore database?</h3>
<p className="text-sm text-gray-400">
- This replays <code>portos-db.sql</code> from snapshot <code className="text-gray-300">{restoreTarget}</code>
+ This replays <code>portos-db.sql</code> from snapshot <code className="text-gray-300">{restoreTarget?.request.snapshotId}</code>
+ {' '}on <span className="text-gray-300">{restoreTarget?.sourceLabel}</span>
{restorePreview && <> ({formatBytes(restorePreview.sizeBytes || 0)} · {restorePreview.tableCount} tables)</>}
{' '}into the live PostgreSQL database. Existing rows may be overwritten.
</p>
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index ee9d45ca6a..6bf2af0115 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -163,6 +163,52 @@ describe('BackupTab', () => {
expect(toast.success).toHaveBeenCalledWith('Database restored from snap-2026-06-09', { icon: '💾' });
});
+ it('binds database preview and confirmation to the selected source', async () => {
+ getBackupSnapshots.mockResolvedValue([
+ ...Array.from({ length: 10 }, (_, index) => ({
+ id: `newer-${index}`,
+ source: 'current-machine',
+ sourceLabel: 'current-machine (current machine)',
+ selectionKey: `current-machine/newer-${index}`,
+ })),
+ {
+ id: 'shared-id',
+ source: 'previous-machine',
+ sourceLabel: 'previous-machine',
+ selectionKey: 'previous-machine/shared-id',
+ },
+ ]);
+ restoreDatabase
+ .mockResolvedValueOnce({ status: 'ok', sizeBytes: 2048, tableCount: 12 })
+ .mockResolvedValueOnce({ status: 'ok' });
+ await renderTab();
+
+ expect(screen.queryByText('Source: previous-machine')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Show all 11 snapshots' }));
+ expect(await screen.findByText('Source: previous-machine')).toBeInTheDocument();
+ await act(async () => {
+ const restoreButtons = await screen.findAllByRole('button', { name: /Restore DB/i });
+ fireEvent.click(restoreButtons.at(-1));
+ });
+ expect(restoreDatabase).toHaveBeenNthCalledWith(1, {
+ snapshotId: 'shared-id',
+ source: 'previous-machine',
+ dryRun: true,
+ }, { silent: true });
+ expect(screen.getByText((_, element) =>
+ element?.tagName === 'P' && element.textContent.includes('on previous-machine')))
+ .toBeInTheDocument();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Restore$/i }));
+ });
+ expect(restoreDatabase).toHaveBeenNthCalledWith(2, {
+ snapshotId: 'shared-id',
+ source: 'previous-machine',
+ dryRun: false,
+ }, { silent: true });
+ });
+
it('toasts an error when the confirmed restore fails', async () => {
withSnapshot();
restoreDatabase
diff --git a/client/src/services/apiSystem.download.test.js b/client/src/services/apiSystem.download.test.js
index 084a0e5c55..8ea7972918 100644
--- a/client/src/services/apiSystem.download.test.js
+++ b/client/src/services/apiSystem.download.test.js
@@ -43,6 +43,19 @@ describe('downloadBackupSnapshot', () => {
expect(HTMLAnchorElement.prototype.click).toHaveBeenCalledTimes(1);
});
+ it('selects a source namespace and gives colliding snapshots distinct filenames', async () => {
+ const blob = new Blob(['snapshot']);
+ fetch.mockResolvedValue({ ok: true, headers: new Headers(), blob: vi.fn().mockResolvedValue(blob) });
+
+ await expect(downloadBackupSnapshot('same-id', 'previous-machine'))
+ .resolves.toEqual({ filename: 'portos-snapshot-previous-machine-same-id.tar.gz' });
+
+ expect(fetch).toHaveBeenCalledWith(
+ '/api/backup/snapshots/same-id/download?source=previous-machine',
+ { credentials: 'same-origin' },
+ );
+ });
+
it('surfaces a failed download response', async () => {
fetch.mockResolvedValue({
ok: false,
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 17aa03c22a..2b64a83792 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -210,14 +210,14 @@ export const getBackupStatus = (options) => request('/backup/status', options);
export const triggerBackup = (options) => request('/backup/run', { method: 'POST', ...options });
export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
export const restoreBackup = (data, options = {}) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data), ...options });
-export async function downloadBackupSnapshot(snapshotId) {
+export async function downloadBackupSnapshot(snapshotId, source) {
// The server names the file the same way; deriving it here too lets the save
// picker open BEFORE the fetch, while the click's transient user activation is
// still valid. Waiting for response headers first — as this used to — routinely
// outlives that window on a cold external drive, Chromium then refuses the
// picker, and the download falls back to buffering a multi-gigabyte archive in
// tab memory: exactly the case the streaming path exists to avoid.
- const filename = `portos-snapshot-${snapshotId}.tar.gz`;
+ const filename = `portos-snapshot-${source ? `${source}-` : ''}${snapshotId}.tar.gz`;
let writable = null;
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
@@ -240,7 +240,8 @@ export async function downloadBackupSnapshot(snapshotId) {
};
try {
- const response = await fetch(`${API_BASE}/backup/snapshots/${encodeURIComponent(snapshotId)}/download`, {
+ const query = source ? `?source=${encodeURIComponent(source)}` : '';
+ const response = await fetch(`${API_BASE}/backup/snapshots/${encodeURIComponent(snapshotId)}/download${query}`, {
credentials: 'same-origin',
});
if (!response.ok) {
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index bf935342d9..022f084c89 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -22,6 +22,7 @@ A backup run (`runBackup` in `server/services/backup.js`) writes to:
```
- Snapshots are namespaced by `<hostname>` so one shared destination (e.g. an iCloud folder) can host backups from several federated machines without `snapshotId` collisions.
+- Snapshot lists include every machine namespace in the destination, plus snapshots written directly under `snapshots/` by PortOS versions from before hostname namespaces. Each row identifies its source, so equal timestamp IDs from different machines remain separate choices. Download, file restore, and database restore keep that source attached through preview and execution. API requests that omit `source` retain the existing behavior and select the current machine; `source: "@legacy"` selects the pre-namespace root.
- The `manifest.json` hashes the SQL dump too (keyed as `../portos-db.sql`, since the dump lives one level above the `data/` tree), so a truncated or corrupt dump is detectable rather than silently trusted.
### What is excluded by default
@@ -61,7 +62,7 @@ Key behaviors, accurate to the code:
## How restore works
-Restore is two independent operations — restoring files and restoring the DB are separate decisions. Both are **dry-run by default** and validate `snapshotId` against path traversal before touching anything.
+Restore is two independent operations — restoring files and restoring the DB are separate decisions. Both are **dry-run by default** and validate `snapshotId` and an optional source namespace against path traversal before touching anything. Explicit source selections also reject symbolic-link aliases for the snapshots root, source namespace, or selected snapshot before archive or restore reads begin.
A backup run that fails after creating its snapshot directory records a durable `.failed` marker before releasing its `.in-progress` guards. Failed snapshots are never eligible for file or database restore (`SNAPSHOT_FAILED`); they remain downloadable so their partial files can be inspected or recovered manually. If PortOS cannot write the failed marker, it keeps the existing incomplete markers instead, which also block restore. Snapshots created by older PortOS versions without a manifest or failure marker retain their legacy behavior because an unmarked historical failure cannot be distinguished reliably from a genuine pre-manifest snapshot.
diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.js
index 8aa571d315..9912d1e6d9 100644
--- a/server/lib/sharedSchemas.js
+++ b/server/lib/sharedSchemas.js
@@ -100,3 +100,13 @@ export const isSafeSubdirFilter = (v) =>
&& /^[a-z0-9._/-]+$/i.test(v)
&& !v.split('/').includes('..')
&& !v.startsWith('/');
+
+// Backup sources are directory names under snapshots/. `@legacy` is reserved
+// for the pre-namespace snapshots root; `@` cannot occur in the sanitized
+// machine names used by backup.js, so a real machine named "legacy" stays
+// independently addressable.
+export const isSafeSnapshotSource = (v) =>
+ typeof v === 'string'
+ && v.length > 0
+ && v.length <= 255
+ && (v === '@legacy' || (v !== '.' && v !== '..' && /^[a-z0-9._-]+$/i.test(v)));
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 32141f6aba..9ef99d5501 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -10,7 +10,7 @@ import { MAX_MONTHLY_COST } from './subscriptionSavings.js';
import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
import {
- grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter, csvIdsParam,
+ grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSnapshotSource, isSafeSubdirFilter, csvIdsParam,
} from './sharedSchemas.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
@@ -61,7 +61,7 @@ export { optionalBooleanMap };
// re-exported so every existing `import { … } from '../lib/validation.js'`
// keeps working unchanged.
export {
- grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter,
+ grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSnapshotSource, isSafeSubdirFilter,
};
// =============================================================================
@@ -994,14 +994,23 @@ export const instanceFeatureGroupUpdateSchema = z.object({
export const subdirFilterSchema = z.string()
.refine(isSafeSubdirFilter, 'subdirFilter must be a relative path with no wildcard, ".." , or leading "/" segments');
+export const snapshotSourceSchema = z.string()
+ .refine(isSafeSnapshotSource, 'source must be "@legacy" or a single machine-name segment');
+
+export const snapshotDownloadQuerySchema = z.object({
+ source: snapshotSourceSchema.optional(),
+}).strict();
+
export const restoreRequestSchema = z.object({
snapshotId: z.string().min(1),
+ source: snapshotSourceSchema.optional(),
subdirFilter: subdirFilterSchema.optional().nullable(),
dryRun: z.boolean().optional().default(true)
});
export const restoreDbRequestSchema = z.object({
snapshotId: z.string().min(1),
+ source: snapshotSourceSchema.optional(),
dryRun: z.boolean().optional().default(true)
});
diff --git a/server/routes/backup.js b/server/routes/backup.js
index 1b9b34bb9e..376c707eaa 100644
--- a/server/routes/backup.js
+++ b/server/routes/backup.js
@@ -1,7 +1,12 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { streamAttachment } from '../lib/streamAttachment.js';
-import { validateRequest, restoreRequestSchema, restoreDbRequestSchema } from '../lib/validation.js';
+import {
+ validateRequest,
+ restoreRequestSchema,
+ restoreDbRequestSchema,
+ snapshotDownloadQuerySchema,
+} from '../lib/validation.js';
import * as backup from '../services/backup.js';
import { getSettings } from '../services/settings.js';
@@ -49,9 +54,12 @@ router.get('/snapshots/:snapshotId/download', asyncHandler(async (req, res) => {
throw new ServerError('No backup destination configured in settings', { status: 400, code: 'BACKUP_NOT_CONFIGURED' });
}
const { snapshotId } = req.params;
- const stream = await backup.openSnapshotStream(destPath, snapshotId);
+ const { source } = validateRequest(snapshotDownloadQuerySchema, req.query);
+ const stream = source
+ ? await backup.openSnapshotStream(destPath, snapshotId, { source })
+ : await backup.openSnapshotStream(destPath, snapshotId);
streamAttachment(res, stream, {
- filename: `portos-snapshot-${snapshotId}.tar.gz`,
+ filename: `portos-snapshot-${source ? `${source}-` : ''}${snapshotId}.tar.gz`,
contentType: 'application/gzip',
failure: new ServerError('Snapshot download failed', { status: 500, code: 'BACKUP_DOWNLOAD_FAILED' }),
label: `Backup snapshot ${snapshotId}`,
@@ -60,21 +68,28 @@ router.get('/snapshots/:snapshotId/download', asyncHandler(async (req, res) => {
// POST /api/backup/restore
router.post('/restore', asyncHandler(async (req, res) => {
- const { snapshotId, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
+ const { snapshotId, source, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
const settings = await getSettings();
- const result = await backup.restoreSnapshot(settings.backup?.destPath, snapshotId, { dryRun, subdirFilter });
+ const result = await backup.restoreSnapshot(settings.backup?.destPath, snapshotId, {
+ dryRun,
+ subdirFilter,
+ ...(source ? { source } : {}),
+ });
res.json(result);
}));
// POST /api/backup/restore-db
router.post('/restore-db', asyncHandler(async (req, res) => {
- const { snapshotId, dryRun } = validateRequest(restoreDbRequestSchema, req.body);
+ const { snapshotId, source, dryRun } = validateRequest(restoreDbRequestSchema, req.body);
const settings = await getSettings();
const destPath = settings.backup?.destPath;
if (!destPath) {
throw new ServerError('No backup destination configured in settings', { status: 400, code: 'BACKUP_NOT_CONFIGURED' });
}
- const result = await backup.restorePostgres(destPath, snapshotId, { dryRun });
+ const result = await backup.restorePostgres(destPath, snapshotId, {
+ dryRun,
+ ...(source ? { source } : {}),
+ });
res.json(result);
}));
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index ee06f31ecc..9ecffb297a 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -149,6 +149,34 @@ describe('backup routes', () => {
expect(backup.openSnapshotStream).toHaveBeenCalledWith('/dest', 'snap-1');
});
+ it('validates and forwards the selected snapshot source', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.openSnapshotStream.mockImplementation(async () => {
+ const stream = new PassThrough();
+ process.nextTick(() => stream.end(Buffer.from('tarball')));
+ return stream;
+ });
+
+ const res = await request(buildApp())
+ .get('/api/backup/snapshots/snap-1/download?source=previous-machine');
+
+ expect(res.status).toBe(200);
+ expect(res.headers['content-disposition'])
+ .toBe('attachment; filename="portos-snapshot-previous-machine-snap-1.tar.gz"');
+ expect(backup.openSnapshotStream)
+ .toHaveBeenCalledWith('/dest', 'snap-1', { source: 'previous-machine' });
+ });
+
+ it('rejects a traversing source before opening the snapshot', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ const res = await request(buildApp())
+ .get('/api/backup/snapshots/snap-1/download?source=..%2Fother-machine');
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(backup.openSnapshotStream).not.toHaveBeenCalled();
+ });
+
it('returns 400 when the backup destination is not configured', async () => {
getSettings.mockResolvedValue({ backup: {} });
@@ -192,6 +220,21 @@ describe('backup routes', () => {
);
});
+ it('forwards source with file restore preview and execution requests', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.restoreSnapshot.mockResolvedValue({ changedFiles: [] });
+ const res = await request(buildApp())
+ .post('/api/backup/restore')
+ .send({ snapshotId: 'snap-1', source: '@legacy', subdirFilter: null, dryRun: true });
+
+ expect(res.status).toBe(200);
+ expect(backup.restoreSnapshot).toHaveBeenCalledWith('/dest', 'snap-1', {
+ dryRun: true,
+ subdirFilter: null,
+ source: '@legacy',
+ });
+ });
+
it('defaults dryRun to true when omitted', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
backup.restoreSnapshot.mockResolvedValue({ success: true });
@@ -222,6 +265,33 @@ describe('backup routes', () => {
);
});
+ it('forwards source with database restore preview and execution requests', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.restorePostgres.mockResolvedValue({ status: 'ok', dryRun: true });
+ const res = await request(buildApp())
+ .post('/api/backup/restore-db')
+ .send({ snapshotId: 'snap-1', source: 'previous-machine', dryRun: true });
+
+ expect(res.status).toBe(200);
+ expect(backup.restorePostgres).toHaveBeenCalledWith('/dest', 'snap-1', {
+ dryRun: true,
+ source: 'previous-machine',
+ });
+ });
+
+ it.each(['../other-machine', 'machine/name', '', 42])(
+ 'rejects invalid snapshot source %j before database restore',
+ async (source) => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ const res = await request(buildApp())
+ .post('/api/backup/restore-db')
+ .send({ snapshotId: 'snap-1', source });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(backup.restorePostgres).not.toHaveBeenCalled();
+ },
+ );
+
it('forwards dryRun=false when explicitly requested', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
backup.restorePostgres.mockResolvedValue({ status: 'ok', dryRun: false });
diff --git a/server/services/backup.js b/server/services/backup.js
index 5a32cbe399..d199d79902 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -20,7 +20,7 @@ import { checkHealth, getServerMajorVersion } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
-import { isSafeSubdirFilter } from '../lib/sharedSchemas.js';
+import { isSafeSnapshotSource, isSafeSubdirFilter } from '../lib/sharedSchemas.js';
import { getIo } from './socket.js';
import { reloadSettings } from './settings.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
@@ -69,7 +69,7 @@ const markerExists = (snapshotDir, snapshotId) =>
const failedMarkerExists = (snapshotDir) =>
markerExistsAt(failedMarkerPath(snapshotDir));
-async function snapshotState(snapshotDir, snapshotId) {
+async function snapshotState(snapshotDir, snapshotId, currentSource = true) {
const [markedInProgress, failed] = await Promise.all([
markerExists(snapshotDir, snapshotId),
failedMarkerExists(snapshotDir),
@@ -78,13 +78,13 @@ async function snapshotState(snapshotDir, snapshotId) {
failed,
// Once `.failed` exists the run is finished even if marker cleanup was
// interrupted. The durable failed state still blocks every restore.
- incomplete: snapshotId === activeSnapshotId || (markedInProgress && !failed),
+ incomplete: (currentSource && snapshotId === activeSnapshotId) || (markedInProgress && !failed),
};
}
/** Reject a snapshot that is still being written before any consumer reads it. */
-async function assertSnapshotComplete(snapshotDir, snapshotId) {
- const { incomplete } = await snapshotState(snapshotDir, snapshotId);
+async function assertSnapshotComplete(snapshotDir, snapshotId, currentSource) {
+ const { incomplete } = await snapshotState(snapshotDir, snapshotId, currentSource);
if (incomplete) {
throw new ServerError(`Snapshot is still being written: ${snapshotId}`, {
status: 409,
@@ -94,8 +94,8 @@ async function assertSnapshotComplete(snapshotDir, snapshotId) {
}
/** Reject snapshots whose backup run finished unsuccessfully before restoring. */
-async function assertSnapshotRestorable(snapshotDir, snapshotId) {
- const { incomplete, failed } = await snapshotState(snapshotDir, snapshotId);
+async function assertSnapshotRestorable(snapshotDir, snapshotId, currentSource) {
+ const { incomplete, failed } = await snapshotState(snapshotDir, snapshotId, currentSource);
if (incomplete) {
throw new ServerError(`Snapshot is still being written: ${snapshotId}`, {
status: 409,
@@ -213,6 +213,10 @@ export const DEFAULT_EXCLUDES = [
// destination (e.g. iCloud) can host backups from multiple machines without
// their snapshot IDs colliding.
const MACHINE_HOST = hostname().toLowerCase().replace(/[^\w.\-]/g, '_') || 'unknown';
+const LEGACY_SNAPSHOT_SOURCE = '@legacy';
+const SNAPSHOT_ID_PATTERN = /^[\w\-.:T]+$/;
+const SHA256_PATTERN = /^[0-9a-f]{64}$/;
+const MANIFEST_ABSENT = Symbol('manifest-absent');
const DEFAULT_STATE = {
lastRun: null,
@@ -749,23 +753,40 @@ export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath
/**
* List all snapshots in the backup destination.
* @param {string} destPath - Path to external drive backup root
- * @returns {Array<{ id, createdAt, fileCount, incomplete, failed }>} sorted newest-first
+ * @returns {Array<{ id, source, selectionKey, createdAt, fileCount, incomplete, failed }>} sorted newest-first
*/
export async function listSnapshots(destPath) {
if (!destPath) return [];
- const snapshotsDir = join(destPath, 'snapshots', MACHINE_HOST);
+ const snapshotsRoot = join(destPath, 'snapshots');
// withFileTypes so we can skip non-directory entries: the backup target is
// commonly an iCloud/Finder folder, where macOS drops a `.DS_Store` FILE into
// every directory. Treating it as a snapshot id and reading
// `<.DS_Store>/manifest.json` throws ENOTDIR. Also skip dotfile-named dirs so
// nothing hidden can masquerade as a snapshot (real ids are timestamps).
- const entries = await readdir(snapshotsDir, { withFileTypes: true }).catch(() => []);
- const ids = entries.filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => e.name);
+ const rootEntries = await readdir(snapshotsRoot, { withFileTypes: true }).catch(() => []);
+ const directories = rootEntries.filter(entry => entry.isDirectory() && !entry.name.startsWith('.'));
+ const descriptors = (await Promise.all(directories.map(async (entry) => {
+ const rootEntryPath = join(snapshotsRoot, entry.name);
+ const contents = await readdir(rootEntryPath, { withFileTypes: true }).catch(() => []);
+ const isLegacySnapshot = SNAPSHOT_ID_PATTERN.test(entry.name) && contents.some(child =>
+ (child.name === 'data' && child.isDirectory())
+ || child.name === 'manifest.json'
+ || child.name === 'portos-db.sql'
+ || child.name === SNAPSHOT_IN_PROGRESS_MARKER
+ || child.name === SNAPSHOT_FAILED_MARKER);
+
+ if (isLegacySnapshot) return [{ id: entry.name, source: LEGACY_SNAPSHOT_SOURCE }];
+ if (!isSafeSnapshotSource(entry.name) || entry.name === LEGACY_SNAPSHOT_SOURCE) return [];
+
+ return contents
+ .filter(child => child.isDirectory() && !child.name.startsWith('.') && SNAPSHOT_ID_PATTERN.test(child.name))
+ .map(child => ({ id: child.name, source: entry.name }));
+ }))).flat();
const snapshots = await Promise.all(
- ids.map(async (id) => {
- const snapshotDir = join(snapshotsDir, id);
+ descriptors.map(async ({ id, source }) => {
+ const { snapshotDir, currentSource } = resolveSnapshotPath(destPath, id, source);
const manifestPath = join(snapshotDir, 'manifest.json');
// logError:false — a snapshot taken before manifests existed legitimately
// has none; the null is handled below, so it isn't worth a warning per list.
@@ -774,9 +795,15 @@ export async function listSnapshots(destPath) {
// Report a still-being-written snapshot rather than hiding it: the row is
// real and the user should see the run in flight, but download and restore
// must not be offered for it. Mirrors assertSnapshotComplete's two signals.
- const { incomplete, failed } = await snapshotState(snapshotDir, id);
+ const { incomplete, failed } = await snapshotState(snapshotDir, id, currentSource);
return {
id,
+ source,
+ sourceLabel: source === LEGACY_SNAPSHOT_SOURCE
+ ? 'Legacy (pre-namespace)'
+ : source === MACHINE_HOST ? `${source} (current machine)` : source,
+ selectionKey: `${source}/${id}`,
+ currentMachine: source === MACHINE_HOST,
createdAt: manifest?.generatedAt ?? null,
fileCount: manifest?.fileCount ?? 0,
incomplete,
@@ -786,17 +813,15 @@ export async function listSnapshots(destPath) {
);
return snapshots.sort((a, b) => {
- if (!a.createdAt) return 1;
- if (!b.createdAt) return -1;
- return b.createdAt.localeCompare(a.createdAt);
+ if (a.createdAt && b.createdAt) return b.createdAt.localeCompare(a.createdAt)
+ || a.selectionKey.localeCompare(b.selectionKey);
+ if (a.createdAt) return -1;
+ if (b.createdAt) return 1;
+ return b.id.localeCompare(a.id) || a.source.localeCompare(b.source);
});
}
-const SNAPSHOT_ID_PATTERN = /^[\w\-.:T]+$/;
-const SHA256_PATTERN = /^[0-9a-f]{64}$/;
-const MANIFEST_ABSENT = Symbol('manifest-absent');
-
-function resolveSnapshotPath(destPath, snapshotId) {
+function resolveSnapshotPath(destPath, snapshotId, source) {
if (!snapshotId || !SNAPSHOT_ID_PATTERN.test(snapshotId)) {
throw new ServerError(`Invalid snapshotId: ${snapshotId}`, {
status: 400,
@@ -804,9 +829,29 @@ function resolveSnapshotPath(destPath, snapshotId) {
});
}
- const snapshotsRoot = resolve(join(destPath, 'snapshots', MACHINE_HOST));
- const snapshotDir = resolve(join(snapshotsRoot, snapshotId));
- const rel = relative(snapshotsRoot, snapshotDir);
+ const resolvedSource = source ?? MACHINE_HOST;
+ if (!isSafeSnapshotSource(resolvedSource)) {
+ throw new ServerError(`Invalid snapshot source: ${resolvedSource}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const snapshotsRoot = resolve(join(destPath, 'snapshots'));
+ const sourceRoot = resolvedSource === LEGACY_SNAPSHOT_SOURCE
+ ? snapshotsRoot
+ : resolve(join(snapshotsRoot, resolvedSource));
+ const sourceRel = relative(snapshotsRoot, sourceRoot);
+ if (resolvedSource !== LEGACY_SNAPSHOT_SOURCE
+ && (!sourceRel || sourceRel.startsWith('..') || isAbsolute(sourceRel))) {
+ throw new ServerError(`Path traversal detected for snapshot source: ${resolvedSource}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const snapshotDir = resolve(join(sourceRoot, snapshotId));
+ const rel = relative(sourceRoot, snapshotDir);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
throw new ServerError(`Path traversal detected for snapshotId: ${snapshotId}`, {
status: 400,
@@ -814,7 +859,36 @@ function resolveSnapshotPath(destPath, snapshotId) {
});
}
- return { snapshotsRoot, snapshotDir };
+ return {
+ snapshotsRoot: sourceRoot,
+ snapshotsBase: snapshotsRoot,
+ snapshotDir,
+ currentSource: resolvedSource === MACHINE_HOST,
+ explicitSource: source !== undefined,
+ };
+}
+
+async function assertExplicitSnapshotSourceSafe({
+ snapshotsBase,
+ snapshotsRoot,
+ snapshotDir,
+ explicitSource,
+}, snapshotId) {
+ if (!explicitSource) return;
+
+ const [baseInfo, sourceInfo, snapshotInfo] = await Promise.all([
+ lstat(snapshotsBase).catch(() => null),
+ lstat(snapshotsRoot).catch(() => null),
+ lstat(snapshotDir).catch(() => null),
+ ]);
+ if (baseInfo?.isSymbolicLink?.()
+ || sourceInfo?.isSymbolicLink?.()
+ || snapshotInfo?.isSymbolicLink?.()) {
+ throw new ServerError(`Snapshot source escapes through a symbolic link: ${snapshotId}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
}
/**
@@ -823,13 +897,15 @@ function resolveSnapshotPath(destPath, snapshotId) {
* @param {string} snapshotId - Snapshot ID to archive
* @returns {Promise<import('stream').Readable>}
*/
-export async function openSnapshotStream(destPath, snapshotId) {
- const { snapshotsRoot, snapshotDir } = resolveSnapshotPath(destPath, snapshotId);
+export async function openSnapshotStream(destPath, snapshotId, { source } = {}) {
+ const resolved = resolveSnapshotPath(destPath, snapshotId, source);
+ const { snapshotsRoot, snapshotDir, currentSource } = resolved;
+ await assertExplicitSnapshotSourceSafe(resolved, snapshotId);
const info = await stat(snapshotDir).catch(() => null);
if (!info?.isDirectory?.()) {
throw new ServerError(`Snapshot not found: ${snapshotId}`, { status: 404, code: 'NOT_FOUND' });
}
- await assertSnapshotComplete(snapshotDir, snapshotId);
+ await assertSnapshotComplete(snapshotDir, snapshotId, currentSource);
// tar's stderr is a pipe (spawn's default) and MUST be drained: left unread
// it fills its ~64KB buffer on a tree that warns a lot — files changing under
@@ -1043,9 +1119,11 @@ async function verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter
* @param {boolean} [options.dryRun=true] - If true, do not write any files
* @param {string|null} [options.subdirFilter=null] - Limit restore to a subdirectory
*/
-export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {}) {
- const { snapshotsRoot, snapshotDir } = resolveSnapshotPath(destPath, snapshotId);
- await assertSnapshotRestorable(snapshotDir, snapshotId);
+export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null, source } = {}) {
+ const resolved = resolveSnapshotPath(destPath, snapshotId, source);
+ const { snapshotDir, currentSource } = resolved;
+ await assertExplicitSnapshotSourceSafe(resolved, snapshotId);
+ await assertSnapshotRestorable(snapshotDir, snapshotId, currentSource);
const srcDir = join(snapshotDir, 'data');
// Defense-in-depth for non-route callers (the route already validates via
@@ -1107,9 +1185,11 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
* @param {string} snapshotId
* @param {{dryRun?: boolean}} [options]
*/
-export async function restorePostgres(destPath, snapshotId, { dryRun = true } = {}) {
- const { snapshotDir } = resolveSnapshotPath(destPath, snapshotId);
- await assertSnapshotRestorable(snapshotDir, snapshotId);
+export async function restorePostgres(destPath, snapshotId, { dryRun = true, source } = {}) {
+ const resolved = resolveSnapshotPath(destPath, snapshotId, source);
+ const { snapshotDir, currentSource } = resolved;
+ await assertExplicitSnapshotSourceSafe(resolved, snapshotId);
+ await assertSnapshotRestorable(snapshotDir, snapshotId, currentSource);
const sqlPath = join(snapshotDir, 'portos-db.sql');
const info = await stat(sqlPath).catch(() => null);
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 985ec5976a..a9bf1b96de 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -283,11 +283,16 @@ describe('listSnapshots', () => {
// The backup target is commonly an iCloud folder; macOS drops a `.DS_Store`
// FILE into every dir. It must not be treated as a snapshot id (reading
// `<.DS_Store>/manifest.json` would throw ENOTDIR).
- vi.spyOn(fs, 'readdir').mockResolvedValue([
- dirent('.DS_Store', false),
- dirent('2026-06-08T15-18-34', true),
- dirent('2026-06-07T09-00-00', true),
- ]);
+ const readdirSpy = vi.spyOn(fs, 'readdir').mockImplementation(async (path) => {
+ if (String(path) === joinPath('/dest', 'snapshots')) {
+ return [dirent('.DS_Store', false), dirent(machineHost, true)];
+ }
+ return [
+ dirent('.DS_Store', false),
+ dirent('2026-06-08T15-18-34', true),
+ dirent('2026-06-07T09-00-00', true),
+ ];
+ });
vi.spyOn(fs, 'readFile').mockImplementation(async (p) => {
if (String(p).includes('.DS_Store')) throw new Error('ENOTDIR — .DS_Store should never be read');
return JSON.stringify({ generatedAt: '2026-06-08T00:00:00Z', fileCount: 10 });
@@ -297,6 +302,58 @@ describe('listSnapshots', () => {
expect(ids).toHaveLength(2);
expect(ids).toContain('2026-06-08T15-18-34');
expect(ids).not.toContain('.DS_Store');
+ readdirSpy.mockRestore();
+ });
+
+ it('discovers legacy and machine snapshots with collision-safe identities', async () => {
+ const destRoot = await fs.mkdtemp(joinPath(tmpdir(), 'portos-backup-sources-'));
+ const snapshotId = '2026-06-08T15-18-34';
+ const legacyId = '2025-12-31T23-59-59';
+ const roots = [
+ joinPath(destRoot, 'snapshots', legacyId),
+ joinPath(destRoot, 'snapshots', 'legacy', snapshotId),
+ joinPath(destRoot, 'snapshots', 'previous-machine', snapshotId),
+ joinPath(destRoot, 'snapshots', machineHost, snapshotId),
+ ];
+ try {
+ await Promise.all(roots.map(root => fs.mkdir(joinPath(root, 'data'), { recursive: true })));
+ await Promise.all(roots.map((root, index) => fs.writeFile(
+ joinPath(root, 'manifest.json'),
+ JSON.stringify({ generatedAt: `2026-01-0${index + 1}T00:00:00Z`, fileCount: index + 1 }),
+ )));
+
+ const result = await listSnapshots(destRoot);
+
+ expect(result).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ id: legacyId,
+ source: '@legacy',
+ sourceLabel: 'Legacy (pre-namespace)',
+ selectionKey: `@legacy/${legacyId}`,
+ }),
+ expect.objectContaining({
+ id: snapshotId,
+ source: 'legacy',
+ selectionKey: `legacy/${snapshotId}`,
+ currentMachine: false,
+ }),
+ expect.objectContaining({
+ id: snapshotId,
+ source: 'previous-machine',
+ selectionKey: `previous-machine/${snapshotId}`,
+ currentMachine: false,
+ }),
+ expect.objectContaining({
+ id: snapshotId,
+ source: machineHost,
+ selectionKey: `${machineHost}/${snapshotId}`,
+ currentMachine: true,
+ }),
+ ]));
+ expect(new Set(result.map(snapshot => snapshot.selectionKey))).toHaveProperty('size', 4);
+ } finally {
+ await fs.rm(destRoot, { recursive: true, force: true });
+ }
});
it('returns [] for a falsy destPath without touching the filesystem', async () => {
@@ -350,6 +407,31 @@ describe('openSnapshotStream', () => {
expect(fs.stat).not.toHaveBeenCalled();
});
+ it('rejects a traversing source before touching the disk or spawning tar', async () => {
+ await expect(openSnapshotStream('/dest', 'snap-1', { source: '../other-machine' }))
+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(fs.stat).not.toHaveBeenCalled();
+ });
+
+ it('rejects an explicitly selected source namespace that is a symbolic link', async () => {
+ const destRoot = await fs.mkdtemp(joinPath(tmpdir(), 'portos-backup-source-link-'));
+ const outsideRoot = await fs.mkdtemp(joinPath(tmpdir(), 'portos-backup-source-outside-'));
+ try {
+ await fs.mkdir(joinPath(destRoot, 'snapshots'), { recursive: true });
+ await fs.mkdir(joinPath(outsideRoot, 'snap-1'), { recursive: true });
+ await fs.symlink(outsideRoot, joinPath(destRoot, 'snapshots', 'previous-machine'));
+
+ await expect(openSnapshotStream(destRoot, 'snap-1', { source: 'previous-machine' }))
+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(fs.stat).not.toHaveBeenCalled();
+ } finally {
+ await fs.rm(destRoot, { recursive: true, force: true });
+ await fs.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
it('refuses a snapshot whose .in-progress marker survived a crash', async () => {
// activeSnapshotId is module state and resets on restart; the marker is what
// still says "this tree was never finished" after PM2 restarts mid-backup.
@@ -384,15 +466,36 @@ describe('openSnapshotStream', () => {
await expect(done).resolves.toBeUndefined();
});
+ it('archives an explicitly selected previous-machine snapshot', async () => {
+ const proc = readySnapshot();
+
+ const stream = await openSnapshotStream('/dest', 'snap-1', { source: 'previous-machine' });
+
+ expect(spawn).toHaveBeenCalledWith(
+ 'tar',
+ ['-czf', '-', '-C', resolve(join('/dest', 'snapshots', 'previous-machine')), 'snap-1'],
+ { shell: false },
+ );
+ const done = ended(stream);
+ stream.resume();
+ proc.emit('close', 0);
+ await expect(done).resolves.toBeUndefined();
+ });
+
it('archives a legacy pre-manifest snapshot without consulting a manifest', async () => {
// listSnapshots deliberately keeps snapshots taken before manifests existed,
// so a missing manifest.json must never gate the download.
const proc = readySnapshot();
- const stream = await openSnapshotStream('/dest', 'legacy-snapshot');
+ const stream = await openSnapshotStream('/dest', 'legacy-snapshot', { source: '@legacy' });
expect(fs.readFile).not.toHaveBeenCalled();
expect(fs.stat.mock.calls.flat().join(' ')).not.toContain('manifest.json');
+ expect(spawn).toHaveBeenCalledWith(
+ 'tar',
+ ['-czf', '-', '-C', resolve(join('/dest', 'snapshots')), 'legacy-snapshot'],
+ { shell: false },
+ );
const done = ended(stream);
stream.resume();
proc.emit('close', 0);
@@ -795,6 +898,23 @@ describe('restorePostgres', () => {
expect(spawn).not.toHaveBeenCalled();
});
+ it('reads a previous-machine dump from the explicitly selected namespace', async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+
+ await expect(restorePostgres('/dest', 'shared-id', {
+ source: 'previous-machine',
+ dryRun: true,
+ })).resolves.toMatchObject({ status: 'ok', dryRun: true });
+
+ expect(fs.stat).toHaveBeenCalledWith(resolve(
+ '/dest', 'snapshots', 'previous-machine', 'shared-id', 'portos-db.sql',
+ ));
+ expect(fs.readFile).toHaveBeenCalledWith(resolve(
+ '/dest', 'snapshots', 'previous-machine', 'shared-id', 'manifest.json',
+ ), 'utf-8');
+ });
+
it('refuses a real restore when PG is not connected', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
mockLegacyDumpRead();
@@ -1644,6 +1764,15 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
});
describe('subdirFilter rsync flags', () => {
+ it('reads a legacy flat snapshot when that source is explicitly selected', async () => {
+ await runRestore('/dest', 'legacy-snapshot', { source: '@legacy', dryRun: true });
+
+ expect(spawn.mock.calls[0][1]).toEqual(expect.arrayContaining([
+ `${resolve('/dest', 'snapshots', 'legacy-snapshot', 'data')}/`,
+ PATHS.data,
+ ]));
+ });
+
it('builds the exact include/exclude chain for a valid subdirFilter', async () => {
await runRestore('/dest', 'snap-1', { dryRun: true, subdirFilter: 'brain' });