feat(admin): back the data up, and put it back, from the admin tool
A new BACKUP tab downloads the deployment's whole state — the SQLite file and both media folders, photos included — as one .tar.gz, and takes the same file back. That one artefact therefore does both jobs: the operator's backup and the data package that moves an install onto another box. The database is snapshotted through SQLite's own backup rather than copied, because the file is written to while the archive streams; the media folders are tarred straight off the volume, so no second copy of them is made. A restore replaces the data on disk and then exits — the container's restart policy brings the API back on the restored files, which is the only moment the open handle can be dropped. The state being replaced is tarred aside first, and the archive is checked for `..` entries before anything is unpacked. The API authenticates that route before it reads a byte, and nginx lets that one path past the body cap which holds everywhere else.
This commit is contained in:
@@ -15,13 +15,15 @@ import type { MsgKey } from './i18n/vi';
|
||||
// section. Every frame carries its own labels, section boxes,
|
||||
// QR code and delete button under its preview
|
||||
// Stats — the visitor counter: views, clicks and their breakdowns
|
||||
// Backup — the data dir out as one .tar.gz, and the route that puts a
|
||||
// .tar.gz back (the API replaces its data and restarts)
|
||||
// Close — leaves the frame and goes back to the landing page
|
||||
// The frame holds no privilege of its own — the API answers 403 unless the
|
||||
// signed-in account is on the ADMIN_EMAILS allowlist, so this is only a viewer.
|
||||
// ponytail: no pagination. The upload quota caps the table at a handful of
|
||||
// rows per account; add a page cursor when the strip outgrows one screen.
|
||||
type State = 'loading' | 'guest' | 'forbidden' | 'ready';
|
||||
type Tab = 'profile' | 'users' | 'pictures' | 'stats';
|
||||
type Tab = 'profile' | 'users' | 'pictures' | 'stats' | 'backup';
|
||||
|
||||
// Where a photo can be put. The boxes are independent — a photo may sit in all
|
||||
// three sections at once, and each section draws one random photo per visit out
|
||||
@@ -44,6 +46,7 @@ const MENU: { id: Tab; key: MsgKey }[] = [
|
||||
{ id: 'users', key: 'adm.tabUsers' },
|
||||
{ id: 'pictures', key: 'adm.tabPictures' },
|
||||
{ id: 'stats', key: 'adm.tabStats' },
|
||||
{ id: 'backup', key: 'adm.tabBackup' },
|
||||
];
|
||||
|
||||
export function Admin() {
|
||||
@@ -67,6 +70,7 @@ export function Admin() {
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [picked, setPicked] = useState<number[]>([]);
|
||||
const filePick = useRef<HTMLInputElement>(null);
|
||||
const restorePick = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const me = await api.me().catch(() => null);
|
||||
@@ -148,6 +152,31 @@ export function Admin() {
|
||||
});
|
||||
};
|
||||
|
||||
// The one action here that replaces everything. The API swaps its data on
|
||||
// disk and exits; the container's restart policy brings it back. So the page
|
||||
// waits for the API to answer again instead of showing a listing that is no
|
||||
// longer what the server holds — and the wait is bounded, because a restore
|
||||
// that never comes back is a thing the operator needs told.
|
||||
const restore = (file: File) => {
|
||||
if (!window.confirm(t('adm.restoreConfirm', { file: file.name }))) return;
|
||||
return run(async () => {
|
||||
await api.adminRestore(file);
|
||||
setNote(t('adm.restoreRunning'));
|
||||
for (let i = 0; i < 90; i += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
try {
|
||||
await api.me();
|
||||
await refreshPhotos();
|
||||
setNote(t('adm.restoreDone'));
|
||||
return;
|
||||
} catch {
|
||||
// Still down for its restart; keep waiting.
|
||||
}
|
||||
}
|
||||
setNote(t('adm.restoreSlow'));
|
||||
});
|
||||
};
|
||||
|
||||
// From the users table: open that account's album in the left column.
|
||||
const showOwner = (userId: number) => {
|
||||
setTab('pictures');
|
||||
@@ -673,6 +702,42 @@ export function Admin() {
|
||||
{tab === 'profile' ? <Profile onSaved={(msg) => setNote(msg)} /> : null}
|
||||
|
||||
{tab === 'stats' ? <Stats /> : null}
|
||||
|
||||
{tab === 'backup' ? (
|
||||
<>
|
||||
<p className="hint adm-sub">{t('adm.backupHint')}</p>
|
||||
<div className="adm-bulk">
|
||||
{/* A plain link, so the browser does the download and the
|
||||
session cookie authorises it — nothing here buffers a
|
||||
multi-hundred-megabyte archive in memory. */}
|
||||
<a className="btn primary" data-key="adm-backup-save" href={api.adminBackupUrl()}>
|
||||
{t('adm.backupSave')}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
className="btn adm-danger"
|
||||
data-key="adm-restore-pick"
|
||||
disabled={busy}
|
||||
onClick={() => restorePick.current?.click()}
|
||||
>
|
||||
{busy ? t('auth.busy') : t('adm.restorePick')}
|
||||
</button>
|
||||
<input
|
||||
ref={restorePick}
|
||||
type="file"
|
||||
hidden
|
||||
accept=".gz,application/gzip"
|
||||
data-key="adm-restore-input"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (file) void restore(file);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="hint adm-sub">{t('adm.restoreHint')}</p>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -314,6 +314,25 @@ export const api = {
|
||||
call<{ user: AdminUser }>(`/admin/users/${id}`, { method: 'PATCH', body: JSON.stringify(patch) }),
|
||||
adminDeleteUser: (id: number) => call<void>(`/admin/users/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// The whole data dir (SQLite + media) as one tar.gz, and the route that takes
|
||||
// the same file back. The download is a plain link — the session cookie rides
|
||||
// along — so nothing here fetches it.
|
||||
adminBackupUrl: () => '/api/admin/backup',
|
||||
// Raw bytes as the body, like a photo upload: the archive is already
|
||||
// compressed, so no multipart wrapper and nothing to re-encode. The API
|
||||
// replaces its data and restarts itself, so a 200 means "come back shortly".
|
||||
adminRestore: async (file: File) => {
|
||||
const res = await fetch('/api/admin/restore', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/gzip' },
|
||||
body: file,
|
||||
});
|
||||
const body = await readJson(res);
|
||||
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`);
|
||||
return body as unknown as { ok: boolean };
|
||||
},
|
||||
|
||||
// Own profile. The API wants `currentPassword` on every edit, even an email-only one.
|
||||
updateProfile: (body: { email?: string; password?: string; currentPassword: string }) =>
|
||||
call<{ user: User }>('/auth/me', { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
|
||||
@@ -282,6 +282,15 @@ export const en: Dict = {
|
||||
'adm.deleteSelected': 'DELETE SELECTED ({n})',
|
||||
'adm.userDeleteSelectedConfirm': 'Permanently delete the {n} selected accounts with all of their photos and recipes? This cannot be undone.',
|
||||
'adm.tabStats': 'STATS',
|
||||
'adm.tabBackup': 'BACKUP',
|
||||
'adm.backupHint': 'Download the whole system state — the accounts/recipes database and both media folders — as one .tar.gz. That same file is the data package which moves this install to another machine: restore with it.',
|
||||
'adm.backupSave': 'DOWNLOAD BACKUP',
|
||||
'adm.restorePick': 'RESTORE FROM FILE…',
|
||||
'adm.restoreHint': 'A restore replaces all current data with the file’s, then the API restarts itself. The data being replaced is archived aside in the data folder first.',
|
||||
'adm.restoreConfirm': 'Replace all current data with {file}? This cannot be undone. A safety archive is still kept in the data folder.',
|
||||
'adm.restoreRunning': 'Restoring — the API is restarting…',
|
||||
'adm.restoreDone': 'Restore finished.',
|
||||
'adm.restoreSlow': 'The API never answered. Check the container log, then reload.',
|
||||
|
||||
'stats.days': '{n} DAYS',
|
||||
'stats.hint': 'Traffic over the selected range.',
|
||||
|
||||
@@ -286,6 +286,15 @@ export const vi = {
|
||||
'adm.deleteSelected': 'XOÁ ĐÃ CHỌN ({n})',
|
||||
'adm.userDeleteSelectedConfirm': 'Xoá vĩnh viễn {n} tài khoản đã chọn cùng toàn bộ ảnh và công thức của chúng? Không hoàn tác được.',
|
||||
'adm.tabStats': 'THỐNG KÊ',
|
||||
'adm.tabBackup': 'SAO LƯU',
|
||||
'adm.backupHint': 'Tải toàn bộ dữ liệu của hệ thống — cơ sở dữ liệu tài khoản/công thức và hai thư mục ảnh — thành một tệp .tar.gz. Chính tệp này là gói dữ liệu để chuyển sang máy khác: khôi phục bằng nó.',
|
||||
'adm.backupSave': 'TẢI BẢN SAO LƯU',
|
||||
'adm.restorePick': 'KHÔI PHỤC TỪ TỆP…',
|
||||
'adm.restoreHint': 'Khôi phục thay toàn bộ dữ liệu hiện tại bằng dữ liệu trong tệp, sau đó API tự khởi động lại. Dữ liệu đang chạy được nén lại một bản an toàn trong thư mục data trước khi thay.',
|
||||
'adm.restoreConfirm': 'Thay toàn bộ dữ liệu hiện tại bằng tệp {file}? Không hoàn tác được. Một bản an toàn vẫn được giữ trong thư mục data.',
|
||||
'adm.restoreRunning': 'Đang khôi phục — API đang khởi động lại…',
|
||||
'adm.restoreDone': 'Đã khôi phục xong.',
|
||||
'adm.restoreSlow': 'API không trả lời lại. Kiểm tra nhật ký container rồi tải lại trang.',
|
||||
|
||||
// The traffic screen. Bucket names ('/app', a control's data-key, a browser
|
||||
// version) are machine values and stay as they are.
|
||||
|
||||
Reference in New Issue
Block a user