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

Download backup snapshots from the UI (#5050)

[._.]/ Adam Eivyabceac0bb91d
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index 9937229978..e1447c5f67 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -5,6 +5,7 @@ import {HardDrive,
ChevronRight,
RefreshCw,
RotateCcw,
+ Download,
Eye,
AlertTriangle,
CheckCircle,
@@ -197,10 +198,20 @@ function SnapshotList() {
// 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']),
+ compare: (prev, next) => equalListByKeys(prev, next, ['id', 'fileCount', 'incomplete']),
},
);
const [selectedId, setSelectedId] = useState(null);
+ const [downloadingId, setDownloadingId] = useState(null);
+
+ const handleDownload = useCallback((snapshotId) => {
+ setDownloadingId(snapshotId);
+ api.downloadBackupSnapshot(snapshotId)
+ .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}`); })
+ .finally(() => setDownloadingId(null));
+ }, []);
if (loading) {
return (
@@ -220,18 +231,35 @@ function SnapshotList() {
<div className="mt-3 space-y-1">
{snapshots.map(snap => (
<div key={snap.id}>
- <div className="flex items-center justify-between py-1.5 px-2 rounded bg-port-bg/50 hover:bg-port-bg/80 transition-colors">
+ <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-600">{snap.fileCount} files</div>
+ <div className="text-xs text-gray-600">
+ {snap.incomplete ? 'Still being written…' : `${snap.fileCount} files`}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ onClick={() => handleDownload(snap.id)}
+ // 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}`}
+ 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} />}
+ Download
+ </button>
+ <button
+ onClick={() => setSelectedId(selectedId === snap.id ? null : snap.id)}
+ disabled={snap.incomplete}
+ 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]"
+ >
+ <RotateCcw size={12} />
+ Restore
+ </button>
</div>
- <button
- onClick={() => setSelectedId(selectedId === snap.id ? null : snap.id)}
- className="ml-2 flex items-center gap-1 px-2 py-1 text-xs text-port-accent hover:text-port-accent/80 transition-colors min-h-[32px]"
- >
- <RotateCcw size={12} />
- Restore
- </button>
</div>
{selectedId === snap.id && (
<RestorePanel
diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsx
new file mode 100644
index 0000000000..2d635cabb0
--- /dev/null
+++ b/client/src/components/BackupWidget.test.jsx
@@ -0,0 +1,97 @@
+import { MemoryRouter } from 'react-router';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ mockGetBackupStatus,
+ mockGetBackupSnapshots,
+ mockDownloadBackupSnapshot,
+ mockTriggerBackup,
+ mockToast,
+} = vi.hoisted(() => ({
+ mockGetBackupStatus: vi.fn(),
+ mockGetBackupSnapshots: vi.fn(),
+ mockDownloadBackupSnapshot: vi.fn(),
+ mockTriggerBackup: vi.fn(),
+ mockToast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),
+}));
+
+vi.mock('../services/api', () => ({
+ getBackupStatus: (...args) => mockGetBackupStatus(...args),
+ getBackupSnapshots: (...args) => mockGetBackupSnapshots(...args),
+ downloadBackupSnapshot: (...args) => mockDownloadBackupSnapshot(...args),
+ triggerBackup: (...args) => mockTriggerBackup(...args),
+}));
+
+vi.mock('./ui/Toast', () => ({ default: mockToast }));
+
+import BackupWidget from './BackupWidget.jsx';
+
+const renderWidget = () => render(
+ <MemoryRouter>
+ <BackupWidget />
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetBackupStatus.mockResolvedValue({
+ status: 'ok',
+ lastRun: '2026-08-25T11:00:00Z',
+ nextRun: '2026-08-26T11:00:00Z',
+ filesChanged: 2,
+ destPath: '/backup/example',
+ });
+ mockGetBackupSnapshots.mockResolvedValue([{ id: '2026-08-25T11-00-00', fileCount: 3 }]);
+ mockDownloadBackupSnapshot.mockResolvedValue({ filename: 'portos-snapshot.tar.gz' });
+});
+
+describe('BackupWidget snapshots', () => {
+ it('offers neither action for a snapshot that is still being written', async () => {
+ mockGetBackupSnapshots.mockResolvedValue([
+ { id: '2026-08-25T12-00-00', fileCount: 0, incomplete: true },
+ ]);
+ renderWidget();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Snapshots' }));
+ expect(await screen.findByText('Still being written…')).toBeInTheDocument();
+ // The server 409s both; a button that can only fail should not be offered.
+ expect(screen.getByRole('button', { name: /Download snapshot/ })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Restore' })).toBeDisabled();
+ });
+
+ it('offers a download action for each snapshot and confirms success', async () => {
+ renderWidget();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Snapshots' }));
+ const download = await screen.findByRole('button', { name: /Download snapshot 2026-08-25T11-00-00/ });
+ fireEvent.click(download);
+
+ await waitFor(() => expect(mockDownloadBackupSnapshot).toHaveBeenCalledWith('2026-08-25T11-00-00'));
+ expect(mockToast.success).toHaveBeenCalledWith('Snapshot downloaded');
+ });
+
+ it('stays silent when the user dismisses the save dialog', async () => {
+ mockDownloadBackupSnapshot.mockRejectedValue(
+ Object.assign(new Error('The user aborted a request.'), { name: 'AbortError' }),
+ );
+ renderWidget();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Snapshots' }));
+ fireEvent.click(await screen.findByRole('button', { name: /Download snapshot 2026-08-25T11-00-00/ }));
+
+ await waitFor(() => expect(mockDownloadBackupSnapshot).toHaveBeenCalled());
+ expect(mockToast.error).not.toHaveBeenCalled();
+ expect(mockToast.success).not.toHaveBeenCalled();
+ });
+
+ it('shows a toast when a snapshot download fails', async () => {
+ mockDownloadBackupSnapshot.mockRejectedValue(new Error('Connection lost'));
+ renderWidget();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Snapshots' }));
+ fireEvent.click(await screen.findByRole('button', { name: /Download snapshot 2026-08-25T11-00-00/ }));
+
+ await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith('Download failed: Connection lost'));
+ });
+});
diff --git a/client/src/services/apiSystem.download.test.js b/client/src/services/apiSystem.download.test.js
new file mode 100644
index 0000000000..d981d30127
--- /dev/null
+++ b/client/src/services/apiSystem.download.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+import { downloadBackupSnapshot } from './apiSystem.js';
+
+describe('downloadBackupSnapshot', () => {
+ const originalCreateObjectURL = URL.createObjectURL;
+ const originalRevokeObjectURL = URL.revokeObjectURL;
+ const originalClick = HTMLAnchorElement.prototype.click;
+ const originalShowSaveFilePicker = window.showSaveFilePicker;
+
+ beforeEach(() => {
+ vi.stubGlobal('fetch', vi.fn());
+ URL.createObjectURL = vi.fn(() => 'blob:backup');
+ URL.revokeObjectURL = vi.fn();
+ HTMLAnchorElement.prototype.click = vi.fn();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ URL.createObjectURL = originalCreateObjectURL;
+ URL.revokeObjectURL = originalRevokeObjectURL;
+ HTMLAnchorElement.prototype.click = originalClick;
+ window.showSaveFilePicker = originalShowSaveFilePicker;
+ });
+
+ it('fetches with same-origin credentials and saves the response blob', async () => {
+ const blob = new Blob(['snapshot']);
+ fetch.mockResolvedValue({
+ ok: true,
+ headers: new Headers(),
+ blob: vi.fn().mockResolvedValue(blob),
+ });
+
+ await expect(downloadBackupSnapshot('2026-08-25T12-00-00'))
+ .resolves.toEqual({ filename: 'portos-snapshot-2026-08-25T12-00-00.tar.gz' });
+
+ expect(fetch).toHaveBeenCalledWith(
+ '/api/backup/snapshots/2026-08-25T12-00-00/download',
+ { credentials: 'same-origin' },
+ );
+ expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:backup');
+ expect(HTMLAnchorElement.prototype.click).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces a failed download response', async () => {
+ fetch.mockResolvedValue({
+ ok: false,
+ status: 404,
+ json: vi.fn().mockResolvedValue({ error: 'Snapshot not found', code: 'NOT_FOUND' }),
+ });
+
+ await expect(downloadBackupSnapshot('missing'))
+ .rejects.toMatchObject({ message: 'Snapshot not found', code: 'NOT_FOUND', status: 404 });
+ expect(URL.createObjectURL).not.toHaveBeenCalled();
+ });
+
+ it('streams large responses to a file picker when available', async () => {
+ const pipeTo = vi.fn().mockResolvedValue(undefined);
+ const writable = {};
+ const createWritable = vi.fn().mockResolvedValue(writable);
+ const blob = vi.fn();
+ window.showSaveFilePicker = vi.fn().mockResolvedValue({ createWritable });
+ fetch.mockResolvedValue({ ok: true, headers: new Headers(), body: { pipeTo }, blob });
+
+ await expect(downloadBackupSnapshot('large'))
+ .resolves.toEqual({ filename: 'portos-snapshot-large.tar.gz' });
+
+ expect(window.showSaveFilePicker).toHaveBeenCalledWith({ suggestedName: 'portos-snapshot-large.tar.gz' });
+ expect(createWritable).toHaveBeenCalledOnce();
+ expect(pipeTo).toHaveBeenCalledWith(writable);
+ expect(blob).not.toHaveBeenCalled();
+ expect(URL.createObjectURL).not.toHaveBeenCalled();
+ });
+
+ it('opens the save picker BEFORE fetching, so the click activation is still valid', async () => {
+ const order = [];
+ window.showSaveFilePicker = vi.fn(async () => {
+ order.push('picker');
+ return { createWritable: async () => ({}) };
+ });
+ fetch.mockImplementation(async () => {
+ order.push('fetch');
+ return { ok: true, headers: new Headers(), body: { pipeTo: vi.fn() }, blob: vi.fn() };
+ });
+
+ await downloadBackupSnapshot('large');
+
+ expect(order).toEqual(['picker', 'fetch']);
+ });
+
+ it('aborts the opened file handle when the download turns out to 404', async () => {
+ const abort = vi.fn().mockResolvedValue(undefined);
+ window.showSaveFilePicker = vi.fn().mockResolvedValue({ createWritable: async () => ({ abort }) });
+ fetch.mockResolvedValue({
+ ok: false,
+ status: 404,
+ json: vi.fn().mockResolvedValue({ error: 'Snapshot not found', code: 'NOT_FOUND' }),
+ });
+
+ await expect(downloadBackupSnapshot('missing')).rejects.toMatchObject({ status: 404 });
+ // Otherwise the picker leaves a 0-byte file where the user chose to save.
+ expect(abort).toHaveBeenCalledOnce();
+ });
+
+ it('falls back to the blob download when the picker is unavailable', async () => {
+ const blob = new Blob(['snapshot']);
+ const body = { pipeTo: vi.fn() };
+ const pickerError = Object.assign(new Error('Not supported here'), { name: 'SecurityError' });
+ window.showSaveFilePicker = vi.fn().mockRejectedValue(pickerError);
+ fetch.mockResolvedValue({ ok: true, headers: new Headers(), body, blob: vi.fn().mockResolvedValue(blob) });
+
+ await expect(downloadBackupSnapshot('large'))
+ .resolves.toEqual({ filename: 'portos-snapshot-large.tar.gz' });
+
+ expect(body.pipeTo).not.toHaveBeenCalled();
+ expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
+ });
+
+ it('propagates a dismissed picker as a cancel, without fetching at all', async () => {
+ window.showSaveFilePicker = vi.fn().mockRejectedValue(
+ Object.assign(new Error('The user aborted a request.'), { name: 'AbortError' }),
+ );
+
+ await expect(downloadBackupSnapshot('large')).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 1ae8e2026b..f3043849c7 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -1,4 +1,5 @@
-import { request } from './apiCore.js';
+import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
+import { downloadBlob } from '../lib/downloadBlob.js';
// Alerts
export const getAlertsSummary = (options) => request('/alerts/summary', options);
@@ -165,6 +166,53 @@ 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) {
+ // 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`;
+
+ let writable = null;
+ if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
+ // A dismissed picker is the user declining; it propagates as AbortError and
+ // callers treat it as a cancel, not a failure. Any other picker error (an
+ // unsupported context, say) falls through to the Blob path below.
+ try {
+ const handle = await window.showSaveFilePicker({ suggestedName: filename });
+ writable = await handle.createWritable();
+ } catch (error) {
+ if (error?.name === 'AbortError') throw error;
+ }
+ }
+
+ const response = await fetch(`${API_BASE}/backup/snapshots/${encodeURIComponent(snapshotId)}/download`, {
+ credentials: 'same-origin',
+ });
+ if (!response.ok) {
+ // Close the handle we opened before we knew the request would fail, so the
+ // picker doesn't leave a 0-byte file behind.
+ await writable?.abort?.().catch(() => {});
+ const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ maybeRedirectToLogin(response, error);
+ const err = new Error(error.error || `HTTP ${response.status}`);
+ err.code = error.code;
+ err.status = response.status;
+ throw err;
+ }
+
+ if (writable && response.body?.pipeTo) {
+ await response.body.pipeTo(writable);
+ } else {
+ // No File System Access API (Firefox, Safari): the Blob path is the only one
+ // available, and it is why the server caps nothing — the browser holds it all.
+ await writable?.abort?.().catch(() => {});
+ downloadBlob(await response.blob(), filename);
+ }
+ return { filename };
+}
export const restoreDatabase = (data, options) => request('/backup/restore-db', { method: 'POST', body: JSON.stringify(data), ...options });
// Data Manager
diff --git a/server/lib/README.md b/server/lib/README.md
index f0ca23b68e..df0d2a4606 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -428,6 +428,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |
| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
+| `streamAttachment.js` | `streamAttachment(res,stream,{filename,contentType,failure,label})` — pipe a readable to a response as a file download. Sets the attachment headers plus `X-Content-Type-Options:nosniff`, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns `failure` via `sendErrorResponse`, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls `stream.abort?.()` so an upstream child process is torn down. Shared by `routes/imageTo3d.js` (GLB, full-mesh) and `routes/backup.js` (snapshot tarball). |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. |
| `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 5a3c940f52..db7a5d1091 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -404,6 +404,7 @@ export * from './slashdoLoader.js';
export * from './singleFlight.js';
export * from './staleWhileRevalidate.js';
export * from './staticImportGraph.js';
+export * from './streamAttachment.js';
export * from './streamBackpressure.js';
export * from './streamingSpawn.js';
export * from './sseUtils.js';
diff --git a/server/lib/streamAttachment.js b/server/lib/streamAttachment.js
new file mode 100644
index 0000000000..05c4ae4b7e
--- /dev/null
+++ b/server/lib/streamAttachment.js
@@ -0,0 +1,70 @@
+import { sendErrorResponse } from './errorHandler.js';
+import { onClientDisconnect } from './sseDownload.js';
+
+// A tar/child-backed stream exposes abort() to kill its process; a plain file read
+// has none, and without destroy() its fd stays open for every download the client
+// walked away from.
+function teardown(stream) {
+ if (typeof stream.abort === 'function') stream.abort();
+ else stream.destroy();
+}
+
+/**
+ * Pipe a readable to an Express response as a file attachment.
+ *
+ * Every attachment-download route needs the same teardown, and the error
+ * handling is the whole reason this is shared rather than copied: the 'error'
+ * event fires OUTSIDE the asyncHandler promise chain, so a throw there would
+ * crash the process — it has to go through sendErrorResponse (shared envelope +
+ * headers-sent guard). Pre-stream failures (the common case: the file vanished
+ * after the readiness check) get the JSON error envelope; mid-stream failures
+ * tear the socket down, since sendErrorResponse no-ops once headers are sent.
+ *
+ * Call sites: routes/imageTo3d.js (GLB + full-mesh), routes/backup.js
+ * (snapshot tarball).
+ *
+ * @param {import('express').Response} res
+ * @param {import('stream').Readable} stream - piped to res; may expose an
+ * `abort()` used to tear down an upstream child process on disconnect.
+ * @param {object} opts
+ * @param {string} opts.filename - offered to the browser as the download name.
+ * @param {string} opts.contentType
+ * @param {import('./errorHandler.js').ServerError} opts.failure - the error
+ * returned when the stream fails before any bytes are written.
+ * @param {string} opts.label - short subject for the warning log.
+ */
+export function streamAttachment(res, stream, { filename, contentType, failure, label }) {
+ // The route awaited settings/stat before getting here, so the client may have
+ // already gone — in which case res's 'close' fired before the listener below
+ // was installed and nothing would ever tear the stream down.
+ if (res.destroyed || res.writableEnded) {
+ teardown(stream);
+ return;
+ }
+
+ res.set('Content-Type', contentType);
+ // Quote the filename at the boundary rather than trusting every caller to have
+ // slugged it: a quote or newline in a record-derived name would otherwise
+ // break out of the header value.
+ const safeName = String(filename).replace(/[^\w.\-]+/g, '_') || 'download';
+ res.set('Content-Disposition', `attachment; filename="${safeName}"`);
+ // Attachments are never meant to be sniffed into an executable type.
+ res.set('X-Content-Type-Options', 'nosniff');
+
+ stream.on('error', (err) => {
+ if (res.destroyed) return; // our own abort, below — nothing left to report
+ console.warn(`⚠️ ${label} stream error: ${err.code || err.message}`);
+ if (res.headersSent) {
+ res.destroy(err);
+ return;
+ }
+ // Drop the download headers so the JSON error body isn't offered to the
+ // browser as an attachment named like a real file.
+ res.removeHeader('Content-Type');
+ res.removeHeader('Content-Disposition');
+ sendErrorResponse(res, failure);
+ });
+
+ onClientDisconnect(null, res, () => teardown(stream));
+ stream.pipe(res);
+}
diff --git a/server/routes/backup.js b/server/routes/backup.js
index 8afef7905f..1b9b34bb9e 100644
--- a/server/routes/backup.js
+++ b/server/routes/backup.js
@@ -1,5 +1,6 @@
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 * as backup from '../services/backup.js';
import { getSettings } from '../services/settings.js';
@@ -40,6 +41,23 @@ router.get('/snapshots', asyncHandler(async (req, res) => {
res.json(snapshots);
}));
+// GET /api/backup/snapshots/:snapshotId/download
+router.get('/snapshots/:snapshotId/download', asyncHandler(async (req, res) => {
+ 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 { snapshotId } = req.params;
+ const stream = await backup.openSnapshotStream(destPath, snapshotId);
+ streamAttachment(res, stream, {
+ filename: `portos-snapshot-${snapshotId}.tar.gz`,
+ contentType: 'application/gzip',
+ failure: new ServerError('Snapshot download failed', { status: 500, code: 'BACKUP_DOWNLOAD_FAILED' }),
+ label: `Backup snapshot ${snapshotId}`,
+ });
+}));
+
// POST /api/backup/restore
router.post('/restore', asyncHandler(async (req, res) => {
const { snapshotId, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 84605450f3..909b52671f 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
+import { PassThrough } from 'stream';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -8,6 +9,7 @@ vi.mock('../services/backup.js', () => ({
getNextRunTime: vi.fn(),
runBackup: vi.fn(),
listSnapshots: vi.fn(),
+ openSnapshotStream: vi.fn(),
restoreSnapshot: vi.fn(),
restorePostgres: vi.fn(),
DEFAULT_EXCLUDES: [
@@ -129,6 +131,35 @@ describe('backup routes', () => {
});
});
+ describe('GET /api/backup/snapshots/:snapshotId/download', () => {
+ it('streams a gzip attachment for the requested snapshot', 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');
+
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/^application\/gzip/);
+ expect(res.headers['content-disposition']).toBe('attachment; filename="portos-snapshot-snap-1.tar.gz"');
+ expect(res.body.toString()).toBe('tarball');
+ expect(backup.openSnapshotStream).toHaveBeenCalledWith('/dest', 'snap-1');
+ });
+
+ it('returns 400 when the backup destination is not configured', async () => {
+ getSettings.mockResolvedValue({ backup: {} });
+
+ const res = await request(buildApp()).get('/api/backup/snapshots/snap-1/download');
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('BACKUP_NOT_CONFIGURED');
+ expect(backup.openSnapshotStream).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/backup/restore', () => {
it('returns 400 when snapshotId is missing', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index aeea3a6cc6..9898021409 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { createReadStream } from 'node:fs';
import { z } from 'zod';
-import { asyncHandler, ServerError, sendErrorResponse } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { streamAttachment } from '../lib/streamAttachment.js';
import { validateRequest } from '../lib/validation.js';
import { getTarget, listTargets, detectHostCapabilities, unavailableReason, unavailableReasonLabel, IMAGE_TO_3D_TARGET_IDS, renderOptionSupportFor } from '../services/imageTo3d/targets.js';
import { getTargetAdapter } from '../services/imageTo3d/adapters.js';
@@ -276,42 +277,14 @@ router.post('/models', asyncHandler(async (req, res) => {
res.status(202).json(withRenderSupport(model));
}));
-/**
- * Stream a resolved mesh file as an attachment.
- *
- * Shared by the GLB and full-mesh OBJ downloads: the error handling below is the
- * whole reason this is a function rather than two copies. The 'error' event fires
- * OUTSIDE the asyncHandler promise chain, so a throw there would crash the
- * process — it has to go through sendErrorResponse (shared envelope +
- * headers-sent guard).
- *
- * @param {import('express').Response} res
- * @param {{path: string, filename: string}} file
- * @param {string} contentType
- */
-function streamMeshDownload(res, { path, filename }, contentType) {
- res.set('Content-Type', contentType);
- res.set('Content-Disposition', `attachment; filename="${filename}"`);
- const stream = createReadStream(path);
- stream.on('error', (err) => {
- console.warn(`⚠️ Image-to-3D asset stream error: ${err.code || err.message}`);
- // Pre-stream (common: file removed after the readiness check) → shared 404
- // envelope. Mid-stream (headers already flushed) → tear the socket down, since
- // sendErrorResponse no-ops once headers are sent.
- if (res.headersSent) {
- res.destroy(err);
- } else {
- // Drop the download headers set above so the JSON error body isn't offered
- // to the browser as an attachment named like a mesh file.
- res.removeHeader('Content-Disposition');
- sendErrorResponse(res, new ServerError('Mesh file not found', { status: 404, code: 'ASSET_MISSING' }));
- }
- });
- stream.pipe(res);
-}
-
router.get('/models/:id/asset', asyncHandler(async (req, res) => {
- streamMeshDownload(res, await getModelAsset(req.params.id), 'model/gltf-binary');
+ const { path, filename } = await getModelAsset(req.params.id);
+ streamAttachment(res, createReadStream(path), {
+ filename,
+ contentType: 'model/gltf-binary',
+ failure: new ServerError('Mesh file not found', { status: 404, code: 'ASSET_MISSING' }),
+ label: 'Image-to-3D asset',
+ });
}));
// The decoder's pre-decimation mesh. Registered before `/models/:id` so the more
@@ -319,7 +292,13 @@ router.get('/models/:id/asset', asyncHandler(async (req, res) => {
// with a different failure mode (see getModelFullMesh) rather than a variant of
// the served GLB.
router.get('/models/:id/full-mesh', asyncHandler(async (req, res) => {
- streamMeshDownload(res, await getModelFullMesh(req.params.id), 'model/obj');
+ const { path, filename } = await getModelFullMesh(req.params.id);
+ streamAttachment(res, createReadStream(path), {
+ filename,
+ contentType: 'model/obj',
+ failure: new ServerError('Mesh file not found', { status: 404, code: 'ASSET_MISSING' }),
+ label: 'Image-to-3D asset',
+ });
}));
router.get('/models/:id', asyncHandler(async (req, res) => {
diff --git a/server/services/backup.js b/server/services/backup.js
index ff5d0c4740..1bb7a654ce 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -7,7 +7,9 @@
*/
import { spawn } from '../lib/childProcess.js';
-import { access, readdir, readFile, stat, unlink } from 'fs/promises';
+import { killWithEscalation } from '../lib/killWithEscalation.js';
+import { access, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';
+import { PassThrough } from 'node:stream';
import { hostname } from 'os';
import { join, resolve, relative, isAbsolute } from 'path';
import { PATHS, ensureDir, readJSONFile, atomicWrite, sha256File } from '../lib/fileUtils.js';
@@ -25,6 +27,34 @@ import { reloadSettings } from './settings.js';
let isRunning = false;
const STATE_PATH = join(PATHS.data, 'backup', 'state.json');
+// A snapshot mid-assembly is a truncated tree that looks like a finished backup.
+// Two signals guard it, because neither alone is sufficient:
+// - `activeSnapshotId` catches the in-process case with no I/O.
+// - the `.in-progress` marker survives a hard crash or PM2 restart, which
+// resets module state while the partial directory stays on the drive.
+// The marker is removed on BOTH the success and failure paths — clearing it only
+// on success is what previously left a failed run's snapshot blocked forever.
+const SNAPSHOT_IN_PROGRESS_MARKER = '.in-progress';
+let activeSnapshotId = null;
+
+const markerPath = (snapshotDir) => join(snapshotDir, SNAPSHOT_IN_PROGRESS_MARKER);
+const markerExists = (snapshotDir) =>
+ access(markerPath(snapshotDir)).then(() => true, () => false);
+
+/**
+ * Reject a snapshot that is still being written. Every consumer that reads a
+ * snapshot as if it were finished — download, file restore, DB restore — must
+ * call this; restoring half a backup over live data is the worst outcome here.
+ */
+async function assertSnapshotComplete(snapshotDir, snapshotId) {
+ const incomplete = snapshotId === activeSnapshotId || await markerExists(snapshotDir);
+ if (incomplete) {
+ throw new ServerError(`Snapshot is still being written: ${snapshotId}`, {
+ status: 409,
+ code: 'SNAPSHOT_INCOMPLETE',
+ });
+ }
+}
// Serialize state read-merge-write so two saveState() calls (e.g. a run
// completing while the scheduler stamps a status) can't each read the same
@@ -235,16 +265,25 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
if (io) io.emit('backup:started', { snapshotId });
await ensureDir(dataDestDir);
+ activeSnapshotId = snapshotId;
+ await writeFile(markerPath(snapshotDir), '');
let changedFiles = [];
let manifest;
+ const clearInProgress = async () => {
+ await unlink(markerPath(snapshotDir)).catch(() => {});
+ activeSnapshotId = null;
+ };
+
const complete = async (result) => {
+ await clearInProgress();
isRunning = false;
return result;
};
const fail = async (err) => {
+ await clearInProgress();
isRunning = false;
await saveState({ lastRun: new Date().toISOString(), status: 'error', error: err.message, pgBackup: null });
if (io) io.emit('backup:failed', { snapshotId, error: err.message });
@@ -469,14 +508,20 @@ export async function listSnapshots(destPath) {
const snapshots = await Promise.all(
ids.map(async (id) => {
- const manifestPath = join(snapshotsDir, id, 'manifest.json');
+ const snapshotDir = join(snapshotsDir, id);
+ 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.
const manifest = await readJSONFile(manifestPath, null, { logError: false });
+ // 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 = id === activeSnapshotId || await markerExists(snapshotDir);
return {
id,
createdAt: manifest?.generatedAt ?? null,
- fileCount: manifest?.fileCount ?? 0
+ fileCount: manifest?.fileCount ?? 0,
+ incomplete
};
})
);
@@ -488,6 +533,92 @@ export async function listSnapshots(destPath) {
});
}
+const SNAPSHOT_ID_PATTERN = /^[\w\-.:T]+$/;
+
+function resolveSnapshotPath(destPath, snapshotId) {
+ if (!snapshotId || !SNAPSHOT_ID_PATTERN.test(snapshotId)) {
+ throw new ServerError(`Invalid snapshotId: ${snapshotId}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const snapshotsRoot = resolve(join(destPath, 'snapshots', MACHINE_HOST));
+ const snapshotDir = resolve(join(snapshotsRoot, snapshotId));
+ const rel = relative(snapshotsRoot, snapshotDir);
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
+ throw new ServerError(`Path traversal detected for snapshotId: ${snapshotId}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ return { snapshotsRoot, snapshotDir };
+}
+
+/**
+ * Open a gzip tar stream for one complete snapshot.
+ * @param {string} destPath - Path to external drive backup root
+ * @param {string} snapshotId - Snapshot ID to archive
+ * @returns {Promise<import('stream').Readable>}
+ */
+export async function openSnapshotStream(destPath, snapshotId) {
+ const { snapshotsRoot, snapshotDir } = resolveSnapshotPath(destPath, 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);
+
+ // 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
+ // the archiver, unreadable modes — and tar then blocks on the write forever,
+ // hanging the download with the process still alive. Keep the tail so a
+ // non-zero exit can say why rather than just reporting the code.
+ const proc = spawn('tar', ['-czf', '-', '-C', snapshotsRoot, snapshotId], { shell: false });
+ const archive = new PassThrough();
+ let stderrTail = '';
+ proc.stderr?.on('data', (chunk) => { stderrTail = (stderrTail + chunk).slice(-500); });
+
+ let finished = false;
+ const finish = (error = null) => {
+ if (finished) return;
+ finished = true;
+ if (error) archive.destroy(error);
+ else archive.end();
+ };
+
+ // Keep the response open until tar's close event. stdout can end before tar
+ // reports a read/permission failure; delaying EOF lets the route turn that
+ // non-zero exit into a failed download instead of a false 200 success.
+ proc.stdout.on('error', finish);
+ proc.stdout.pipe(archive, { end: false });
+ proc.on('error', finish);
+ proc.on('close', (code, signal) => {
+ if (code === 0) {
+ finish();
+ return;
+ }
+ const detail = code == null ? `signal ${signal || 'unknown'}` : `code ${code}`;
+ finish(new Error(`tar exited with ${detail}${stderrTail ? `: ${stderrTail.trim()}` : ''}`));
+ });
+ archive.abort = () => {
+ // Escalate like every other spawn-based job: the backup destination is an
+ // external/network mount, so a tar wedged on stalled I/O is the exact case
+ // SIGTERM alone does not clear.
+ if (proc.exitCode === null && proc.signalCode === null) {
+ // stillRunning is `true` on purpose: the helper already skips SIGKILL once
+ // the child has exited, and this proc is captured in the closure so there is
+ // no handle that could be swapped out from under us. Gating on the stream's
+ // own state instead would read as false by the time the timer fires (finish()
+ // runs on the next line) and silently disable the escalation.
+ killWithEscalation(proc, { label: `snapshot download ${snapshotId}`, stillRunning: () => true });
+ }
+ finish(new Error(`Snapshot download aborted: ${snapshotId}`));
+ };
+ return archive;
+}
+
/**
* Restore a snapshot back to PATHS.data using rsync.
* @param {string} destPath - Path to external drive backup root
@@ -497,18 +628,9 @@ export async function listSnapshots(destPath) {
* @param {string|null} [options.subdirFilter=null] - Limit restore to a subdirectory
*/
export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {}) {
- // Validate snapshotId to prevent path traversal
- if (!snapshotId || !/^[\w\-.:T]+$/.test(snapshotId)) {
- throw new Error(`Invalid snapshotId: ${snapshotId}`);
- }
- const snapshotsRoot = resolve(join(destPath, 'snapshots', MACHINE_HOST));
- const srcDir = join(snapshotsRoot, snapshotId, 'data');
- // Use path.relative to stay cross-platform and avoid prefix-match pitfalls
- // (e.g. /snaps vs /snaps2).
- const rel = relative(snapshotsRoot, resolve(srcDir));
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
- throw new Error(`Path traversal detected for snapshotId: ${snapshotId}`);
- }
+ const { snapshotsRoot, snapshotDir } = resolveSnapshotPath(destPath, snapshotId);
+ await assertSnapshotComplete(snapshotDir, snapshotId);
+ const srcDir = join(snapshotDir, 'data');
// Defense-in-depth for non-route callers (the route already validates via
// subdirFilterSchema). subdirFilter is interpolated into an rsync include arg,
@@ -549,15 +671,9 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
* @param {{dryRun?: boolean}} [options]
*/
export async function restorePostgres(destPath, snapshotId, { dryRun = true } = {}) {
- if (!snapshotId || !/^[\w\-.:T]+$/.test(snapshotId)) {
- throw new Error(`Invalid snapshotId: ${snapshotId}`);
- }
- const snapshotsRoot = resolve(join(destPath, 'snapshots', MACHINE_HOST));
- const sqlPath = join(snapshotsRoot, snapshotId, 'portos-db.sql');
- const rel = relative(snapshotsRoot, resolve(sqlPath));
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
- throw new Error(`Path traversal detected for snapshotId: ${snapshotId}`);
- }
+ const { snapshotDir } = resolveSnapshotPath(destPath, snapshotId);
+ await assertSnapshotComplete(snapshotDir, snapshotId);
+ const sqlPath = join(snapshotDir, 'portos-db.sql');
const info = await stat(sqlPath).catch(() => null);
// An empty/0-byte dump is as good as absent — restoring it is a silent no-op.
@@ -573,7 +689,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
// the dump key — have nothing to verify against, so we SKIP verification and
// proceed rather than hard-failing. Only a manifest that IS present AND
// carries a mismatching hash refuses the restore.
- const manifestPath = join(snapshotsRoot, snapshotId, 'manifest.json');
+ const manifestPath = join(snapshotDir, 'manifest.json');
const manifest = await readJSONFile(manifestPath, null);
const expectedHash = manifest?.files?.['../portos-db.sql'];
if (expectedHash) {
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index a5ac66df5d..6a974fd93a 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -61,6 +61,7 @@ vi.mock('./memoryBackend.js', () => ({
import { EventEmitter } from 'events';
import { createHash } from 'crypto';
import { hostname } from 'os';
+import { PassThrough } from 'node:stream';
import { spawn } from '../lib/childProcess.js';
// Partial mock: only override spawn. Preserve execFile et al. because
// backup.js transitively imports fileUtils.js, which promisifies execFile.
@@ -74,7 +75,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => ({
// used by backup.js + fileUtils.js keeps its real implementation.
vi.mock('fs/promises', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, stat: vi.fn(actual.stat), readFile: vi.fn(actual.readFile) };
+ return { ...actual, stat: vi.fn(actual.stat), readFile: vi.fn(actual.readFile), access: vi.fn(actual.access) };
});
import { checkHealth, getServerMajorVersion } from '../lib/db.js';
@@ -90,13 +91,30 @@ vi.mock('./settings.js', async (importOriginal) => ({
reloadSettings: vi.fn(async () => {}),
}));
import { reloadSettings } from './settings.js';
-import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, restoreSnapshot } from './backup.js';
+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot } from './backup.js';
+
+// fs.access is mocked file-wide because backup.js probes the .in-progress marker
+// with it. Restore the real implementation before EVERY test: vi.clearAllMocks()
+// resets call history but NOT implementations, so a single test's
+// mockResolvedValue would otherwise make every later test see a marker and 409.
+beforeEach(async () => {
+ const actual = await vi.importActual('fs/promises');
+ fs.access.mockImplementation(actual.access);
+});
+
+// Mirrors backup.js's MACHINE_HOST derivation so expected paths can be built
+// without hardcoding this machine's hostname.
+const machineHost = hostname().toLowerCase().replace(/[^\w.\-]/g, '_') || 'unknown';
// Helper: build a fake child process whose close/error we can drive.
function fakeProc() {
const proc = new EventEmitter();
- proc.stdout = new EventEmitter();
+ proc.stdout = new PassThrough();
proc.stderr = new EventEmitter();
+ proc.exitCode = null;
+ proc.signalCode = null;
+ proc.killed = false;
+ proc.kill = vi.fn(() => { proc.killed = true; });
return proc;
}
@@ -276,6 +294,145 @@ describe('listSnapshots', () => {
});
});
+describe('openSnapshotStream', () => {
+ afterEach(async () => {
+ const actual = await vi.importActual('fs/promises');
+ fs.stat.mockImplementation(actual.stat);
+ fs.access.mockImplementation(actual.access);
+ spawn.mockReset();
+ });
+
+ beforeEach(() => {
+ fs.access.mockRejectedValue(new Error('ENOENT'));
+ });
+
+ // An existing, COMPLETE snapshot directory, ready for tar: the directory stats
+ // fine while the .in-progress marker is absent.
+ function readySnapshot() {
+ fs.stat.mockResolvedValue({ isDirectory: () => true });
+ fs.access.mockRejectedValue(new Error('ENOENT')); // no .in-progress marker
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ return proc;
+ }
+
+ // Same directory, but a marker left behind by a crashed run.
+ function crashedSnapshot() {
+ fs.stat.mockResolvedValue({ isDirectory: () => true });
+ fs.access.mockResolvedValue(undefined); // .in-progress present
+ }
+
+ const ended = (stream) => new Promise((resolveEnd) => stream.once('end', resolveEnd));
+ const errored = (stream) => new Promise((resolveError) => stream.once('error', resolveError));
+
+ it.each([
+ ['a slash', 'snap/id'],
+ ['a wildcard', 'snap*id'],
+ ['a traversal id', '..'],
+ ])('rejects %s before touching the disk or spawning tar', async (_label, snapshotId) => {
+ await expect(openSnapshotStream('/dest', snapshotId))
+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(fs.stat).not.toHaveBeenCalled();
+ });
+
+ 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.
+ crashedSnapshot();
+
+ await expect(openSnapshotStream('/dest', 'snap-1'))
+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_INCOMPLETE' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('returns 404 for an unknown snapshot without spawning tar', async () => {
+ fs.stat.mockRejectedValue(new Error('ENOENT'));
+
+ await expect(openSnapshotStream('/dest', 'snap-1'))
+ .rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('spawns tar with the snapshot directory as its archive root', async () => {
+ const proc = readySnapshot();
+
+ const stream = await openSnapshotStream('/dest', 'snap-1');
+
+ expect(spawn).toHaveBeenCalledWith(
+ 'tar',
+ ['-czf', '-', '-C', resolve(join('/dest', 'snapshots', machineHost)), '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');
+
+ expect(fs.readFile).not.toHaveBeenCalled();
+ expect(fs.stat.mock.calls.flat().join(' ')).not.toContain('manifest.json');
+ const done = ended(stream);
+ stream.resume();
+ proc.emit('close', 0);
+ await expect(done).resolves.toBeUndefined();
+ });
+
+ it('fails the archive stream when tar exits unsuccessfully, reporting its stderr', async () => {
+ const proc = readySnapshot();
+
+ const stream = await openSnapshotStream('/dest', 'snap-1');
+ const failed = errored(stream);
+ proc.stderr.emit('data', Buffer.from('tar: Permission denied'));
+ proc.emit('close', 2);
+
+ await expect(failed).resolves.toMatchObject({
+ message: 'tar exited with code 2: tar: Permission denied',
+ });
+ });
+
+ it('escalates the kill when the response disconnects', async () => {
+ vi.useFakeTimers();
+ const proc = readySnapshot();
+
+ const stream = await openSnapshotStream('/dest', 'snap-1');
+ const failed = errored(stream);
+ stream.abort();
+
+ expect(proc.kill).toHaveBeenCalledWith('SIGTERM');
+ // A tar wedged on a stalled mount ignores SIGTERM. The escalation must still
+ // fire after the grace window — it is gated on the CHILD's exit state, not on
+ // the archive stream's, which abort() has already settled by this point.
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(proc.kill).toHaveBeenCalledWith('SIGKILL');
+ vi.useRealTimers();
+
+ await expect(failed).resolves.toMatchObject({ message: 'Snapshot download aborted: snap-1' });
+ });
+
+ it('does not escalate once tar has already exited', async () => {
+ vi.useFakeTimers();
+ const proc = readySnapshot();
+
+ const stream = await openSnapshotStream('/dest', 'snap-1');
+ stream.on('error', () => {});
+ proc.exitCode = 0;
+ stream.abort();
+
+ expect(proc.kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(proc.kill).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ });
+});
+
describe('dumpPostgres status classification', () => {
let dumpPostgres;
beforeEach(async () => {
@@ -530,6 +687,19 @@ describe('restorePostgres', () => {
expect(result).toEqual({ status: 'skipped', reason: 'no_dump' });
});
+ // portos-db.sql is still being written while a backup runs. Replaying a half
+ // dump into the live database is the most destructive thing this module can
+ // do, so the guard has to cover it — not just download and file restore.
+ it('refuses an incomplete snapshot before reading the dump', async () => {
+ fs.access.mockResolvedValue(undefined); // .in-progress present
+ const statSpy = vi.spyOn(fs, 'stat');
+
+ await expect(restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false }))
+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_INCOMPLETE' });
+ expect(statSpy).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
it('dry-run reports size/tableCount without spawning psql', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
@@ -1046,10 +1216,6 @@ describe('getState and saveState', () => {
// restoreSnapshot writes over the user's live data/ directory, so each of these
// is a data-loss-adjacent contract, not a style nit (issue #3917).
describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () => {
- // Mirrors backup.js's MACHINE_HOST derivation so the expected src path can be
- // built without hardcoding this machine's hostname.
- const machineHost = hostname().toLowerCase().replace(/[^\w.\-]/g, '_') || 'unknown';
-
beforeEach(() => {
spawn.mockReset();
reloadSettings.mockClear();
@@ -1339,6 +1505,51 @@ describe('runBackup lifecycle', () => {
await first;
});
+ // A snapshot mid-assembly would tar/rsync as a truncated tree that looks like
+ // a complete backup. Driven through the real runBackup rather than a stubbed
+ // marker so the guard is tested against the state that actually gates it.
+ it('refuses to download or restore the snapshot currently being written', async () => {
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const { openSnapshotStream: open, restoreSnapshot: restore } = await import('./backup.js');
+
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotId = io.emit.mock.calls[0][1].snapshotId;
+
+ await expect(open(destRoot, snapshotId))
+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_INCOMPLETE' });
+ await expect(restore(destRoot, snapshotId, { dryRun: true }))
+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_INCOMPLETE' });
+ // Only the rsync — neither guard reached tar or a second rsync.
+ expect(spawn).toHaveBeenCalledTimes(1);
+
+ proc.emit('close', 0);
+ await pending;
+ });
+
+ // The old on-disk '.in-progress' marker was never removed on failure, which
+ // left a failed snapshot permanently un-downloadable with no recovery path.
+ it('clears the in-progress guard when a run fails, leaving the snapshot downloadable', async () => {
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const { openSnapshotStream: open } = await import('./backup.js');
+
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotId = io.emit.mock.calls[0][1].snapshotId;
+ proc.emit('close', 23);
+ await expect(pending).rejects.toThrow(/rsync exited with code 23/);
+
+ const tar = fakeProc();
+ spawn.mockReturnValue(tar);
+ const stream = await open(destRoot, snapshotId);
+ expect(stream).toBeDefined();
+ stream.destroy();
+ });
+
it('on rsync failure: releases the lock, records status error, emits backup:failed, and rethrows', async () => {
const io = { emit: vi.fn() };
const proc = fakeProc();