diff --git a/web/src/App.tsx b/web/src/App.tsx index 50bb800..43b5c62 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -74,6 +74,11 @@ const AdminSecurityPage = lazy(() => default: m.AdminSecurityPage, })), ); +const AdminBackupPage = lazy(() => + import("@/pages/admin/AdminBackupPage").then((m) => ({ + default: m.AdminBackupPage, + })), +); const AboutPage = lazy(() => import("@/pages/about/AboutPage").then((m) => ({ default: m.AboutPage })), ); @@ -172,6 +177,7 @@ export function App() { } /> } /> + } /> } /> } /> diff --git a/web/src/components/backup/BackupCountsTable.tsx b/web/src/components/backup/BackupCountsTable.tsx new file mode 100644 index 0000000..7c88a5a --- /dev/null +++ b/web/src/components/backup/BackupCountsTable.tsx @@ -0,0 +1,62 @@ +import { useTranslation } from "react-i18next"; +import { BACKUP_TABLES, type BackupCounts } from "@/lib/backup"; + +/** + * Per-table row counts. `secondary` adds the third column used by the + * preflight view ("rows in file" vs "rows that will be written"). + */ +export function BackupCountsTable({ + counts, + secondary, + countLabel, +}: { + counts: BackupCounts; + secondary?: BackupCounts; + /** Overrides the first numeric column header (the import result reuses this + * table for "rows written"). */ + countLabel?: string; +}) { + const { t } = useTranslation(); + + return ( +
+ + + + + + {secondary && ( + + )} + + + + {BACKUP_TABLES.map((table) => ( + + + + {secondary && ( + + )} + + ))} + +
+ {t("backup.tableLabel")} + + {countLabel ?? t("backup.countLabel")} + + {t("backup.writeLabel")} +
+ {t(`backup.tables.${table}`)} + + {table} + + + {counts?.[table] ?? 0} + + {secondary[table] ?? 0} +
+
+ ); +} diff --git a/web/src/components/backup/BackupExportPanel.tsx b/web/src/components/backup/BackupExportPanel.tsx new file mode 100644 index 0000000..0e83c94 --- /dev/null +++ b/web/src/components/backup/BackupExportPanel.tsx @@ -0,0 +1,195 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { AlertTriangle, Download, ShieldAlert } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { downloadBlob, exportBackup, type BackupScope } from "@/lib/backup"; +import { describeBackupError } from "./describeBackupError"; + +const MIN_PASSPHRASE_LENGTH = 8; + +/** Export half of the backup闭环: options → download. */ +export function BackupExportPanel({ scope }: { scope: BackupScope }) { + const { t } = useTranslation(); + + const [encrypted, setEncrypted] = useState(true); + const [passphrase, setPassphrase] = useState(""); + const [passphraseConfirm, setPassphraseConfirm] = useState(""); + const [includeHistory, setIncludeHistory] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [successMsg, setSuccessMsg] = useState(""); + + const resetPassphrase = () => { + setPassphrase(""); + setPassphraseConfirm(""); + }; + + const handleExport = async (e: React.SyntheticEvent) => { + e.preventDefault(); + setError(""); + setSuccessMsg(""); + + if (encrypted) { + if (!passphrase) { + setError(t("backup.passphraseRequired")); + return; + } + if (passphrase.length < MIN_PASSPHRASE_LENGTH) { + setError( + t("backup.passphraseTooShort", { min: MIN_PASSPHRASE_LENGTH }), + ); + return; + } + if (passphrase !== passphraseConfirm) { + setError(t("backup.passphraseMismatch")); + return; + } + } + + setBusy(true); + try { + const { blob, filename } = await exportBackup(scope, { + encrypted, + passphrase: encrypted ? passphrase : undefined, + includeHistory, + }); + downloadBlob(blob, filename); + resetPassphrase(); + setSuccessMsg( + t( + encrypted + ? "backup.exportSuccessEncrypted" + : "backup.exportSuccessPlain", + { filename }, + ), + ); + } catch (err) { + setError(describeBackupError(err, t)); + } finally { + setBusy(false); + } + }; + + return ( +
+
+

{t("backup.exportTitle")}

+

+ {t("backup.exportDescription")} +

+
+ + {/* Encrypt (default on — spec §敏感性) */} +
+
+ +

+ {t("backup.encryptDescription")} +

+
+ { + setEncrypted(v); + setError(""); + if (!v) resetPassphrase(); + }} + /> +
+ + {encrypted && ( +
+
+ + setPassphrase(e.target.value)} + placeholder={t("backup.passphrasePlaceholder", { + min: MIN_PASSPHRASE_LENGTH, + })} + /> +
+
+ + setPassphraseConfirm(e.target.value)} + /> +
+

+ {t("backup.passphraseHint")} +

+
+ )} + + {/* Include notification_history (default off) */} +
+
+ +

+ {t("backup.includeHistoryDescription")} +

+
+ +
+ + {/* Two mandatory warnings, next to the export button (ONE-358 spec) */} +
+
+ +

+ {t("backup.masterKeyWarning")} +

+
+
+ +

+ {t("backup.apiKeyNotice")} +

+
+
+ + {error && ( +

+ {error} +

+ )} + {successMsg && ( +

+ {successMsg} +

+ )} + + +
+ ); +} diff --git a/web/src/components/backup/BackupImportPanel.tsx b/web/src/components/backup/BackupImportPanel.tsx new file mode 100644 index 0000000..06d22dc --- /dev/null +++ b/web/src/components/backup/BackupImportPanel.tsx @@ -0,0 +1,594 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { + AlertTriangle, + CheckCircle2, + FileJson, + Info, + ShieldAlert, + Upload, +} from "lucide-react"; +import { ConfirmDialog } from "@/components/ConfirmDialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + MAX_BACKUP_BYTES, + type BackupImportResult, + type BackupPreview, + type BackupScope, + executeBackupImport, + previewBackupImport, + type ImportMode, +} from "@/lib/backup"; +import { cn } from "@/lib/utils"; +import { BackupCountsTable } from "./BackupCountsTable"; +import { describeBackupError, describeBlocker } from "./describeBackupError"; + +type PickedFile = { name: string; size: number; text: string }; + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +/** Import half of the backup 闭环: pick file → preflight → confirm → result. */ +export function BackupImportPanel({ scope }: { scope: BackupScope }) { + const { t } = useTranslation(); + + const isInstance = scope === "instance"; + + const [file, setFile] = useState(null); + const [fileInputKey, setFileInputKey] = useState(0); + const [passphrase, setPassphrase] = useState(""); + const [mode, setMode] = useState("restore"); + const [preview, setPreview] = useState(null); + const [result, setResult] = useState(null); + const [busy, setBusy] = useState<"preview" | "import" | null>(null); + const [error, setError] = useState(""); + const [confirmOpen, setConfirmOpen] = useState(false); + + const tableLabel = (name: string) => + t(`backup.tables.${name}`, { defaultValue: name }); + + const reset = () => { + setFile(null); + setFileInputKey((k) => k + 1); + setPassphrase(""); + setPreview(null); + setResult(null); + setError(""); + }; + + const handleFileChange = async (e: React.ChangeEvent) => { + const picked = e.target.files?.[0]; + setPreview(null); + setResult(null); + setError(""); + if (!picked) { + setFile(null); + return; + } + if (picked.size > MAX_BACKUP_BYTES) { + setFile(null); + e.target.value = ""; + setError(t("backup.errors.payloadTooLarge")); + return; + } + try { + setFile({ + name: picked.name, + size: picked.size, + text: await picked.text(), + }); + } catch { + setFile(null); + e.target.value = ""; + setError(t("backup.errors.fileReadFailed")); + } + }; + + const handlePreview = async () => { + if (!file) { + setError(t("backup.fileRequired")); + return; + } + setBusy("preview"); + setError(""); + setResult(null); + try { + const data = await previewBackupImport(scope, { + fileText: file.text, + passphrase: passphrase || undefined, + mode: isInstance ? mode : undefined, + }); + setPreview(data); + if (data.mode) setMode(data.mode); + } catch (err) { + setPreview(null); + setError(describeBackupError(err, t)); + } finally { + setBusy(null); + } + }; + + const handleExecute = async () => { + if (!file || !preview) return; + setConfirmOpen(false); + setBusy("import"); + setError(""); + try { + const data = await executeBackupImport(scope, { + fileText: file.text, + passphrase: passphrase || undefined, + mode: isInstance ? mode : undefined, + }); + setResult(data); + // Clear the picked file + passphrase so a second click cannot re-import. + setFile(null); + setPassphrase(""); + setPreview(null); + setFileInputKey((k) => k + 1); + } catch (err) { + setError(describeBackupError(err, t)); + } finally { + setBusy(null); + } + }; + + const confirmIsRestore = preview?.mode === "restore"; + + const conflictRows: { label: string; tone: "danger" | "warning" }[] = []; + if (preview) { + const c = preview.conflicts; + if (c.target_users > 0) { + conflictRows.push({ + label: t("backup.conflictTargetUsers", { count: c.target_users }), + tone: "danger", + }); + } + if (c.email_conflicts?.length) { + conflictRows.push({ + label: t("backup.conflictEmailConflicts", { + emails: c.email_conflicts.join(", "), + }), + tone: "danger", + }); + } + if (c.config_overwritten) { + conflictRows.push({ + label: t("backup.conflictConfigOverwritten"), + tone: "warning", + }); + } + if (c.settings_overwritten?.length) { + conflictRows.push({ + label: t("backup.conflictSettingsOverwritten", { + keys: c.settings_overwritten.join(", "), + }), + tone: "warning", + }); + } + if (c.skipped_orphan_payments > 0) { + conflictRows.push({ + label: t("backup.conflictSkippedOrphan", { + count: c.skipped_orphan_payments, + }), + tone: "warning", + }); + } + if (c.skipped_foreign_items > 0) { + conflictRows.push({ + label: t("backup.conflictSkippedForeignItems", { + count: c.skipped_foreign_items, + }), + tone: "warning", + }); + } + if (c.skipped_foreign_payments > 0) { + conflictRows.push({ + label: t("backup.conflictSkippedForeignPayments", { + count: c.skipped_foreign_payments, + }), + tone: "warning", + }); + } + if (c.skipped_history_rows > 0) { + conflictRows.push({ + label: t("backup.conflictSkippedHistory", { + count: c.skipped_history_rows, + }), + tone: "warning", + }); + } + } + + return ( +
+ void handleExecute()} + onCancel={() => setConfirmOpen(false)} + /> + +
+

{t("backup.importTitle")}

+

+ {t("backup.importDescription")} +

+
+ + {result ? ( + /* ---------------- Result ---------------- */ +
+
+ +
+

+ {t("backup.resultTitle")} +

+

+ {t("backup.resultTotal", { count: result.total_written })} ·{" "} + {t( + result.mode === "restore" + ? "backup.modeRestoreShort" + : "backup.modeMergeShort", + )} +

+
+
+ + + + {result.notices.length > 0 && ( +
    + {result.notices.map((notice) => ( +
  • + + {notice} +
  • + ))} +
+ )} + +
+ +
+

{t("backup.reloginNotice")}

+ {result.mode === "restore" &&

{t("backup.apiKeyNotice")}

} +
+
+ + {result.warnings?.length > 0 && ( +
+

+ {t("backup.warningsTitle")} +

+
    + {result.warnings.map((warning) => ( +
  • · {warning}
  • + ))} +
+
+ )} + + +
+ ) : ( + /* ---------------- Pick + preflight ---------------- */ +
+
+ + +

+ {file + ? t("backup.selectedFile", { + name: file.name, + size: formatBytes(file.size), + }) + : t("backup.fileHint", { max: formatBytes(MAX_BACKUP_BYTES) })} +

+
+ +
+ + { + setPassphrase(e.target.value); + setPreview(null); + }} + placeholder={t("backup.filePassphrasePlaceholder")} + /> +

+ {t("backup.filePassphraseHint")} +

+
+ + {isInstance ? ( +
+ + +

+ {t( + mode === "restore" + ? "backup.modeRestoreHint" + : "backup.modeMergeHint", + )} +

+
+ ) : ( +
+ +

+ {t("backup.modeFixedMerge")} +

+
+ )} + +
+ +
+

{t("backup.reloginNotice")}

+

{t("backup.apiKeyNotice")}

+
+
+ + {error && !preview && ( +

+ {error} +

+ )} + + {!preview && ( + + )} + + {preview && ( +
+
+

{t("backup.previewTitle")}

+ + {preview.can_execute + ? t("backup.canExecute") + : t("backup.cannotExecute")} + +
+ +

+ {t("backup.previewSummary", { + version: preview.format_version, + scope: t( + preview.scope === "instance" + ? "backup.scopeInstance" + : "backup.scopeUser", + ), + mode: t( + preview.mode === "restore" + ? "backup.modeRestoreShort" + : "backup.modeMergeShort", + ), + encryption: t( + preview.encrypted + ? "backup.encryptedYes" + : "backup.encryptedNo", + ), + date: new Date(preview.exported_at).toLocaleString(), + })} +

+ + + +
+

+ {t("backup.usersTitle")} +

+ {preview.users.length === 0 ? ( +

+ {t("backup.usersEmpty")} +

+ ) : ( +
    + {preview.users.map((user) => ( +
  • + {user.email} + + {user.role} + +
  • + ))} +
+ )} +
+ +
+

+ {t("backup.conflictsTitle")} +

+ {conflictRows.length === 0 ? ( +

+ {t("backup.noConflicts")} +

+ ) : ( +
    + {conflictRows.map((row) => ( +
  • + + {row.label} +
  • + ))} +
+ )} +
+ + {preview.ignored_tables.length > 0 && ( +
+

+ {t("backup.ignoredTablesTitle")} +

+
    + {preview.ignored_tables.map((table) => ( +
  • + {tableLabel(table)} +
  • + ))} +
+
+ )} + + {preview.blockers.length > 0 && ( +
+

+ {t("backup.blockersTitle")} +

+
    + {preview.blockers.map((blocker) => ( +
  • + · {describeBlocker(blocker, t)} + + {blocker.code} + +
  • + ))} +
+
+ )} + + {preview.warnings.length > 0 && ( +
+

+ {t("backup.warningsTitle")} +

+
    + {preview.warnings.map((warning) => ( +
  • · {warning}
  • + ))} +
+
+ )} + + {error && ( +

+ {error} +

+ )} + +
+ + +
+
+ )} +
+ )} +
+ ); +} diff --git a/web/src/components/backup/BackupSection.tsx b/web/src/components/backup/BackupSection.tsx new file mode 100644 index 0000000..fd681a8 --- /dev/null +++ b/web/src/components/backup/BackupSection.tsx @@ -0,0 +1,31 @@ +import { useTranslation } from "react-i18next"; +import type { BackupScope } from "@/lib/backup"; +import { BackupExportPanel } from "./BackupExportPanel"; +import { BackupImportPanel } from "./BackupImportPanel"; + +/** + * Shared 导出 / 导入 block, used by both entry points: + * - personal scope (`scope="user"`) in Settings → 备份与恢复 + * - instance scope (`scope="instance"`) in Admin → 备份与恢复 + */ +export function BackupSection({ scope }: { scope: BackupScope }) { + const { t } = useTranslation(); + + return ( +
+
+

{t("backup.title")}

+

+ {t( + scope === "instance" + ? "backup.instanceDescription" + : "backup.userDescription", + )} +

+
+ + + +
+ ); +} diff --git a/web/src/components/backup/describeBackupError.ts b/web/src/components/backup/describeBackupError.ts new file mode 100644 index 0000000..31e80c6 --- /dev/null +++ b/web/src/components/backup/describeBackupError.ts @@ -0,0 +1,47 @@ +import type { TFunction } from "i18next"; +import { ApiError } from "@/lib/api"; + +/** + * Machine code → i18n key for the backup endpoints (CONTRACT.md §6). The + * server messages are Chinese-only, so known codes are localized on the + * client; unknown codes fall back to the server message. + */ +const ERROR_KEYS: Record = { + PASSPHRASE_REQUIRED: "backup.errors.passphraseRequired", + DECRYPT_FAILED: "backup.errors.decryptFailed", + INVALID_ENVELOPE: "backup.errors.invalidFile", + INVALID_FORMAT: "backup.errors.invalidFile", + INVALID_FILE: "backup.errors.invalidFile", + INVALID_ROW: "backup.errors.invalidFile", + UNSUPPORTED_FORMAT_VERSION: "backup.errors.unsupportedVersion", + MODE_NOT_ALLOWED: "backup.errors.modeNotAllowed", + MERGE_SOURCE_NOT_FOUND: "backup.errors.mergeSourceNotFound", + RESTORE_TARGET_NOT_EMPTY: "backup.errors.restoreTargetNotEmpty", + PAYLOAD_TOO_LARGE: "backup.errors.payloadTooLarge", + STALE_PREVIEW: "backup.errors.stalePreview", + WRITE_FAILED: "backup.errors.writeFailed", + RESTORE_COUNT_MISMATCH: "backup.errors.writeFailed", + API_KEY_NOT_ALLOWED: "backup.errors.sessionOnly", +}; + +export function describeBackupError(err: unknown, t: TFunction): string { + if (err instanceof ApiError) { + const key = err.code ? ERROR_KEYS[err.code] : undefined; + if (key) return t(key); + if (err.status === 413) return t("backup.errors.payloadTooLarge"); + if (err.status === 403) return t("backup.errors.forbidden"); + if (err.message) return err.message; + } + if (err instanceof Error && err.message) return err.message; + return t("common.error"); +} + +/** Localized text for a preflight blocker code, falling back to server text. */ +export function describeBlocker( + blocker: { code: string; message: string }, + t: TFunction, +): string { + return t(`backup.blockerCodes.${blocker.code}`, { + defaultValue: blocker.message, + }); +} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index d107cd5..f1ee942 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -6,6 +6,8 @@ class ApiError extends Error { constructor( public status: number, message: string, + public code?: string, + public details?: unknown, ) { super(message); this.name = "ApiError"; @@ -44,10 +46,15 @@ async function parseBody(response: Response): Promise { return response.json(); } -async function request( +/** + * Performs the request and returns the raw `Response` (after the shared + * session/refresh handling). Used for endpoints whose body is not JSON — + * e.g. the export endpoints, which stream the download file itself. + */ +async function requestResponse( path: string, options: RequestInit & { skipRedirect?: boolean } = {}, -): Promise { +): Promise { const { skipRedirect: skip, ...fetchOptions } = options; const skipRedirect = skip || isPublicAuthPath(path); const impersonateId = sessionStorage.getItem("impersonate_user_id"); @@ -86,7 +93,7 @@ async function request( credentials: "include", headers, }); - if (retryRes.ok) return parseBody(retryRes); + if (retryRes.ok) return retryRes; if (retryRes.status === 401) { window.location.href = "/login"; throw new ApiError(401, "Unauthorized"); @@ -94,7 +101,12 @@ async function request( const retryBody = await retryRes .json() .catch(() => ({ error: "Unknown error" })); - throw new ApiError(retryRes.status, retryBody.error || "Request failed"); + throw new ApiError( + retryRes.status, + retryBody.error || "Request failed", + retryBody.code, + retryBody.details, + ); } window.location.href = "/login"; @@ -105,10 +117,22 @@ async function request( const body = await response .json() .catch(() => ({ error: "Unknown error" })); - throw new ApiError(response.status, body.error || "Request failed"); + throw new ApiError( + response.status, + body.error || "Request failed", + body.code, + body.details, + ); } - return parseBody(response); + return response; +} + +async function request( + path: string, + options: RequestInit & { skipRedirect?: boolean } = {}, +): Promise { + return parseBody(await requestResponse(path, options)); } export const api = { @@ -120,6 +144,13 @@ export const api = { body: data ? JSON.stringify(data) : undefined, ...opts, }), + /** POST returning the unparsed `Response` (file downloads, streams). */ + postRaw: (path: string, data?: unknown, opts?: { skipRedirect?: boolean }) => + requestResponse(path, { + method: "POST", + body: data ? JSON.stringify(data) : undefined, + ...opts, + }), put: (path: string, data?: unknown, opts?: { skipRedirect?: boolean }) => request(path, { method: "PUT", diff --git a/web/src/lib/backup.ts b/web/src/lib/backup.ts new file mode 100644 index 0000000..911865c --- /dev/null +++ b/web/src/lib/backup.ts @@ -0,0 +1,167 @@ +import { api } from "@/lib/api"; + +/** + * Export / import ("backup") HTTP surface. + * + * Contract: `worker/src/lib/backup/CONTRACT.md` (backend ONE-359). Session + * cookie auth only — these endpoints reject API keys by design, so callers + * must never route them through the API-key path. + */ + +/** The seven tables carried by an export file, in server order. */ +export const BACKUP_TABLES = [ + "users", + "user_2fa", + "items", + "payment_history", + "notification_configs", + "system_settings", + "notification_history", +] as const; + +export type BackupTable = (typeof BACKUP_TABLES)[number]; + +export type BackupScope = "user" | "instance"; + +export type ImportMode = "restore" | "merge"; + +export type BackupCounts = Record; + +/** Server-side request body cap (10 MB), see CONTRACT.md §2. */ +export const MAX_BACKUP_BYTES = 10 * 1024 * 1024; + +export interface BackupExportOptions { + encrypted: boolean; + passphrase?: string; + includeHistory: boolean; +} + +export interface BackupDownload { + blob: Blob; + filename: string; +} + +export interface BackupPreview { + ok: boolean; + mode: ImportMode; + scope: BackupScope; + encrypted: boolean; + format_version: number; + app_version: string; + exported_at: string; + counts: BackupCounts; + will_write: BackupCounts; + users: { id: string; email: string; role: string }[]; + can_execute: boolean; + blockers: { code: string; message: string }[]; + conflicts: { + target_users: number; + email_conflicts: string[]; + settings_overwritten: string[]; + config_overwritten: boolean; + skipped_orphan_payments: number; + skipped_foreign_items: number; + skipped_foreign_payments: number; + skipped_history_rows: number; + }; + ignored_tables: string[]; + warnings: string[]; +} + +export interface BackupImportResult { + ok: boolean; + mode: ImportMode; + scope: BackupScope; + written: BackupCounts; + total_written: number; + notices: string[]; + warnings: string[]; +} + +export interface BackupImportRequest { + /** Raw file text: the API accepts the export file as a JSON string. */ + fileText: string; + passphrase?: string; + mode?: ImportMode; +} + +function scopeBase(scope: BackupScope): string { + return scope === "user" ? "/me" : "/admin"; +} + +function filenameFromDisposition(header: string | null): string | null { + if (!header) return null; + const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(header); + return match ? decodeURIComponent(match[1]) : null; +} + +function fallbackFilename(scope: BackupScope, encrypted: boolean): string { + const stamp = new Date() + .toISOString() + .replace(/\.\d+Z$/, "Z") + .replace(/[-:]/g, ""); + return `enotify-${scope}-${stamp}-${encrypted ? "encrypted" : "plain"}.json`; +} + +/** Exports and returns the file as a blob plus the server-chosen filename. */ +export async function exportBackup( + scope: BackupScope, + options: BackupExportOptions, +): Promise { + const response = await api.postRaw(`${scopeBase(scope)}/export`, { + encrypted: options.encrypted, + ...(options.passphrase ? { passphrase: options.passphrase } : {}), + include_history: options.includeHistory, + }); + + return { + blob: await response.blob(), + filename: + filenameFromDisposition(response.headers.get("Content-Disposition")) ?? + fallbackFilename(scope, options.encrypted), + }; +} + +function importBody({ fileText, passphrase, mode }: BackupImportRequest) { + return { + file: fileText, + ...(passphrase ? { passphrase } : {}), + ...(mode ? { mode } : {}), + }; +} + +/** Dry run: parses the file and reports what an import would do. Writes nothing. */ +export async function previewBackupImport( + scope: BackupScope, + request: BackupImportRequest, +): Promise { + return api.post( + `${scopeBase(scope)}/import/preview`, + importBody(request), + ); +} + +/** Executes the import (one server-side transaction). */ +export async function executeBackupImport( + scope: BackupScope, + request: BackupImportRequest, +): Promise { + return api.post( + `${scopeBase(scope)}/import`, + importBody(request), + ); +} + +/** Hands a blob to the browser's download machinery. */ +export function downloadBlob(blob: Blob, filename: string): void { + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = filename; + anchor.rel = "noopener"; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + // Revoking immediately can cancel the download in some browsers. + window.setTimeout(() => URL.revokeObjectURL(url), 1000); +} diff --git a/web/src/locales/en.json b/web/src/locales/en.json index d080070..a4af695 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -272,7 +272,8 @@ "apiKeysExpired": "Expired", "apiKeysRevokeTitle": "Revoke API key", "apiKeysRevokeConfirm": "Revoke \"{{name}}\"? Scripts using this key will stop working immediately.", - "apiKeysRevokeSuccess": "API key revoked" + "apiKeysRevokeSuccess": "API key revoked", + "backup": "Backup & restore" }, "about": { "title": "About", @@ -354,7 +355,8 @@ "dbInitialized": "Database initialized successfully", "dbUpgradeFailed": "Upgrade failed, please try again later", "dbUpgradeUnauthorized": "Please sign in again", - "dbUpgradeForbidden": "Administrator permission required" + "dbUpgradeForbidden": "Administrator permission required", + "backup": "Backup & restore" }, "channels": { "title": "Channel Management", @@ -433,5 +435,119 @@ "summary": "Due preview", "daysLeft": "remaining", "daysUnit": "d" + }, + "backup": { + "title": "Backup & restore", + "userDescription": "Export your own eNotify data as a single JSON file, or restore / merge your own data from an export file.", + "instanceDescription": "Export the whole instance as a single JSON file, or restore the entire instance from an export file (disaster recovery) / merge your own data.", + "exportTitle": "Export", + "exportDescription": "Pack the data into one JSON file and download it. Encrypted export is on by default.", + "encrypt": "Encrypt the export (recommended)", + "encryptDescription": "Protects the file with a passphrase (WebCrypto AES-GCM-256 + PBKDF2). Without the passphrase a leaked file cannot be read.", + "passphrase": "Passphrase", + "passphrasePlaceholder": "At least {{min}} characters", + "passphraseConfirm": "Confirm passphrase", + "passphraseHint": "The passphrase is not stored and never logged. Keep it safe — a forgotten passphrase means the file cannot be restored.", + "passphraseRequired": "A passphrase is required when encryption is on", + "passphraseTooShort": "The passphrase needs at least {{min}} characters", + "passphraseMismatch": "The two passphrases do not match", + "includeHistory": "Include notification history", + "includeHistoryDescription": "Notification history is a delivery log and is excluded by default. Enable it only if you need the past delivery records.", + "exportAction": "Export & download", + "exporting": "Exporting…", + "exportSuccessEncrypted": "Encrypted file {{filename}} downloaded — keep it with its passphrase.", + "exportSuccessPlain": "Plain-text file {{filename}} downloaded — it contains every credential, store it safely right away.", + "masterKeyWarning": "This file contains channel tokens, SMTP / mail passwords, TOTP secrets and every other credential — it is equivalent to a master key. Keep it offline and never send it over chat, email or a cloud link.", + "apiKeyNotice": "API keys are not part of the export (the server only stores hashes, so they cannot be exported). Re-issue them after a restore.", + "importTitle": "Import", + "importDescription": "Pick an export file → preflight (writes nothing) → confirm → import.", + "selectFile": "Choose an export file", + "fileHint": "eNotify JSON export files only, up to {{max}}.", + "selectedFile": "Selected: {{name}} ({{size}})", + "fileRequired": "Choose an export file first", + "filePassphrase": "File passphrase", + "filePassphrasePlaceholder": "Leave empty for unencrypted files", + "filePassphraseHint": "Required for encrypted files — use the passphrase chosen at export time. It is only used for this request and is never stored.", + "targetMode": "Import mode", + "modeRestore": "Restore (default)", + "modeRestoreHint": "Writes the whole file back into this instance and requires it to have no users yet — meant for disaster recovery.", + "modeMerge": "Merge", + "modeMergeHint": "Merges only the personal data in the file into your own account: items and payments get new IDs and your channel config is overwritten by the file.", + "modeRestoreShort": "Restore", + "modeMergeShort": "Merge", + "modeFixedMerge": "Personal imports are always a merge: only the rows that belong to you are merged into your account.", + "reloginNotice": "All users have to sign in again after an import.", + "previewAction": "Preflight (writes nothing)", + "previewing": "Running preflight…", + "reexecutePreview": "Run preflight again", + "previewTitle": "Preflight result", + "previewSummary": "Format v{{version}} · {{scope}} scope · {{mode}} · {{encryption}} · exported {{date}}", + "scopeUser": "Personal", + "scopeInstance": "Instance", + "encryptedYes": "encrypted", + "encryptedNo": "not encrypted (plain)", + "tableLabel": "Table", + "countLabel": "Rows in file", + "writeLabel": "Will write", + "usersTitle": "Users in the file", + "usersEmpty": "The file contains no users", + "conflictsTitle": "Conflicts & skipped rows", + "noConflicts": "No conflicts", + "conflictTargetUsers": "The target instance already has {{count}} user(s); restore mode requires an empty instance", + "conflictEmailConflicts": "Email conflicts: {{emails}}", + "conflictConfigOverwritten": "Your channel config will be overwritten row by row by the file", + "conflictSettingsOverwritten": "System settings that will be overwritten: {{keys}}", + "conflictSkippedOrphan": "Payments without a matching item will be skipped: {{count}}", + "conflictSkippedForeignItems": "Items belonging to other accounts will be ignored: {{count}}", + "conflictSkippedForeignPayments": "Payments belonging to other accounts will be ignored: {{count}}", + "conflictSkippedHistory": "Notification history rows will not be imported: {{count}}", + "ignoredTablesTitle": "Tables ignored by this import", + "blockersTitle": "Why the import cannot run", + "warningsTitle": "Notices", + "canExecute": "Preflight passed — ready to import", + "cannotExecute": "Preflight failed — import disabled", + "confirmImport": "Confirm import", + "confirmRestoreTitle": "Restore this instance?", + "confirmRestoreMessage": "The whole file will be written into this instance and this cannot be undone. Afterwards every user has to sign in again and API keys must be re-issued.", + "confirmMergeTitle": "Merge into your account?", + "confirmMergeMessage": "Your personal data will be merged from the file: items and payments get new IDs and your channel config will be overwritten. This cannot be undone.", + "importing": "Importing…", + "resultTitle": "Import finished", + "resultTotal": "{{count}} rows written in total", + "importAnother": "Import another file", + "tables": { + "users": "Users", + "user_2fa": "Two-factor auth", + "items": "Notifications", + "payment_history": "Payments", + "notification_configs": "Notification configs", + "system_settings": "System settings", + "notification_history": "Notification history" + }, + "errors": { + "passphraseRequired": "This file is encrypted — enter the passphrase used at export time", + "decryptFailed": "Wrong passphrase or corrupted file. Nothing was written", + "invalidFile": "This is not a valid eNotify export file", + "unsupportedVersion": "The file format is newer than this server supports — upgrade eNotify first", + "modeNotAllowed": "This file cannot be used with the selected import mode", + "mergeSourceNotFound": "The file contains no data for your account, so it cannot be merged", + "restoreTargetNotEmpty": "This instance already has users, so restore mode is unavailable (no overwrite option)", + "payloadTooLarge": "The file exceeds the 10 MB limit", + "stalePreview": "The data changed after the preflight — run it again", + "writeFailed": "The write failed and the whole import was rolled back — nothing changed", + "fileReadFailed": "Could not read the file — is it a valid JSON export?", + "sessionOnly": "This action only works from a signed-in session, not with an API key", + "forbidden": "You are not allowed to do that" + }, + "blockerCodes": { + "RESTORE_TARGET_NOT_EMPTY": "The target instance is not empty; restore mode needs an instance with no users", + "REFERENCE_MISSING": "The file references rows that do not exist", + "DUPLICATE_KEY": "The file contains duplicate primary keys", + "MISSING_COLUMN": "File rows are missing required columns", + "UNSUPPORTED_FORMAT_VERSION": "The file format is newer than this server supports", + "MERGE_SOURCE_NOT_FOUND": "The file contains no data for your account", + "MODE_NOT_ALLOWED": "This file cannot be used with the selected import mode" + }, + "writtenLabel": "Rows written" } } diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index beaaa3c..a986a87 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -272,7 +272,8 @@ "apiKeysExpired": "已过期", "apiKeysRevokeTitle": "吊销 API Key", "apiKeysRevokeConfirm": "确定吊销「{{name}}」?吊销后使用该 Key 的脚本将立即失效。", - "apiKeysRevokeSuccess": "API Key 已吊销" + "apiKeysRevokeSuccess": "API Key 已吊销", + "backup": "备份与恢复" }, "about": { "title": "关于", @@ -354,7 +355,8 @@ "dbInitialized": "数据库初始化成功", "dbUpgradeFailed": "升级失败,请稍后再试", "dbUpgradeUnauthorized": "请重新登录", - "dbUpgradeForbidden": "需要管理员权限" + "dbUpgradeForbidden": "需要管理员权限", + "backup": "备份与恢复" }, "channels": { "title": "通道管理", @@ -433,5 +435,119 @@ "summary": "到期预览", "daysLeft": "剩余", "daysUnit": "天" + }, + "backup": { + "title": "备份与恢复", + "userDescription": "导出你本人的 eNotify 数据为单个 JSON 文件,或从导出文件恢复 / 合并你自己的数据。", + "instanceDescription": "导出全站数据为单个 JSON 文件,或从导出文件恢复整个实例(灾难恢复)/ 合并你自己的数据。", + "exportTitle": "导出", + "exportDescription": "把数据打包成一个 JSON 文件下载。加密导出默认开启。", + "encrypt": "加密导出(推荐)", + "encryptDescription": "用口令加密文件(WebCrypto AES-GCM-256 + PBKDF2)。文件泄露时没有口令也无法读取。", + "passphrase": "口令", + "passphrasePlaceholder": "至少 {{min}} 个字符", + "passphraseConfirm": "确认口令", + "passphraseHint": "口令不会被保存,也不会出现在日志里;请自行妥善记录,忘记口令后无法恢复该文件。", + "passphraseRequired": "开启加密时必须填写口令", + "passphraseTooShort": "口令至少需要 {{min}} 个字符", + "passphraseMismatch": "两次输入的口令不一致", + "includeHistory": "包含通知历史", + "includeHistoryDescription": "通知历史是发送日志,默认不导出;仅在需要保留历史发送记录时开启。", + "exportAction": "导出并下载", + "exporting": "正在导出…", + "exportSuccessEncrypted": "已下载加密文件 {{filename}},请用口令妥善保管。", + "exportSuccessPlain": "已下载明文文件 {{filename}},其中包含全部凭证,请立即妥善保管。", + "masterKeyWarning": "这个文件包含渠道 token、SMTP / 邮件密码、TOTP 密钥等全部凭证,等同主钥匙包:请离线妥善保管,不要经聊天、邮件或网盘链接传输。", + "apiKeyNotice": "API Key 不在导出范围内(服务端只保存哈希,无法导出),恢复后需要重新签发。", + "importTitle": "导入", + "importDescription": "选择导出文件 → 预检(不写入任何数据)→ 确认 → 导入。", + "selectFile": "选择导出文件", + "fileHint": "仅支持 eNotify 导出的 JSON 文件,大小上限 {{max}}。", + "selectedFile": "已选择:{{name}}({{size}})", + "fileRequired": "请先选择导出文件", + "filePassphrase": "文件口令", + "filePassphrasePlaceholder": "未加密的文件留空", + "filePassphraseHint": "加密文件必须填写导出时设置的口令;口令只在本次请求中使用,不会被保存。", + "targetMode": "导入模式", + "modeRestore": "恢复模式(默认)", + "modeRestoreHint": "把文件中的全站数据写回本实例,要求当前实例还没有任何用户;用于灾难恢复。", + "modeMerge": "合并模式", + "modeMergeHint": "只把文件中的个人数据合并到当前账号:条目与缴费会生成新 ID,渠道配置会被文件整行覆盖。", + "modeRestoreShort": "恢复模式", + "modeMergeShort": "合并模式", + "modeFixedMerge": "个人档导入固定为合并模式:只把文件里属于你本人的数据合并到当前账号。", + "reloginNotice": "导入后所有用户需要重新登录。", + "previewAction": "预检(不写入)", + "previewing": "正在预检…", + "reexecutePreview": "重新预检", + "previewTitle": "预检结果", + "previewSummary": "文件格式 v{{version}} · {{scope}}档 · {{mode}} · {{encryption}} · 导出于 {{date}}", + "scopeUser": "个人", + "scopeInstance": "全站", + "encryptedYes": "已加密", + "encryptedNo": "未加密(明文)", + "tableLabel": "数据表", + "countLabel": "文件行数", + "writeLabel": "将写入", + "usersTitle": "文件中的用户", + "usersEmpty": "文件不包含用户", + "conflictsTitle": "冲突与跳过", + "noConflicts": "没有冲突", + "conflictTargetUsers": "目标实例当前已有 {{count}} 个用户,恢复模式要求目标为空", + "conflictEmailConflicts": "同邮箱冲突:{{emails}}", + "conflictConfigOverwritten": "当前账号的渠道配置会被文件内容整行覆盖", + "conflictSettingsOverwritten": "会被文件内容覆盖的系统设置:{{keys}}", + "conflictSkippedOrphan": "找不到对应条目的缴费记录将被跳过:{{count}} 条", + "conflictSkippedForeignItems": "属于其他账号的条目将被忽略:{{count}} 条", + "conflictSkippedForeignPayments": "属于其他账号的缴费记录将被忽略:{{count}} 条", + "conflictSkippedHistory": "通知历史不会导入:{{count}} 条", + "ignoredTablesTitle": "本次导入会忽略的表", + "blockersTitle": "无法执行导入的原因", + "warningsTitle": "提示", + "canExecute": "预检通过,可以导入", + "cannotExecute": "预检未通过,无法导入", + "confirmImport": "确认导入", + "confirmRestoreTitle": "确认恢复这个实例?", + "confirmRestoreMessage": "将把文件中的全站数据写入当前实例,操作不可撤销。恢复后所有用户需要重新登录,API Key 需要重新签发。", + "confirmMergeTitle": "确认合并到当前账号?", + "confirmMergeMessage": "将把文件中的个人数据合并到当前账号,条目与缴费会生成新 ID,渠道配置会被覆盖。操作不可撤销。", + "importing": "正在导入…", + "resultTitle": "导入完成", + "resultTotal": "共写入 {{count}} 行", + "importAnother": "再导入一个文件", + "tables": { + "users": "用户", + "user_2fa": "两步验证", + "items": "通知条目", + "payment_history": "缴费记录", + "notification_configs": "通知配置", + "system_settings": "系统设置", + "notification_history": "通知历史" + }, + "errors": { + "passphraseRequired": "该文件已加密,请填写导出时设置的口令", + "decryptFailed": "口令错误或文件已损坏,未写入任何数据", + "invalidFile": "这不是有效的 eNotify 导出文件", + "unsupportedVersion": "文件格式版本高于当前服务支持的版本,请先升级 eNotify", + "modeNotAllowed": "该文件不能用于所选的导入模式", + "mergeSourceNotFound": "文件里没有属于当前账号的数据,无法合并", + "restoreTargetNotEmpty": "当前实例已经有用户,恢复模式不可用(不提供覆盖)", + "payloadTooLarge": "文件超过 10 MB 上限,无法导入", + "stalePreview": "预检之后数据发生了变化,请重新预检", + "writeFailed": "写入失败,本次导入已整体回滚,数据没有任何变化", + "fileReadFailed": "读取文件失败,请确认是有效的 JSON 导出文件", + "sessionOnly": "该操作只支持登录会话,不能用 API Key 调用", + "forbidden": "没有权限执行该操作" + }, + "blockerCodes": { + "RESTORE_TARGET_NOT_EMPTY": "目标实例非空,恢复模式要求实例没有任何用户", + "REFERENCE_MISSING": "文件内存在缺失的引用(行引用了不存在的记录)", + "DUPLICATE_KEY": "文件内存在重复的主键", + "MISSING_COLUMN": "文件行缺少必填列", + "UNSUPPORTED_FORMAT_VERSION": "文件格式版本高于当前服务支持的版本", + "MERGE_SOURCE_NOT_FOUND": "文件里没有属于当前账号的数据", + "MODE_NOT_ALLOWED": "该文件不能用于所选的导入模式" + }, + "writtenLabel": "实际写入行数" } } diff --git a/web/src/pages/admin/AdminBackupPage.tsx b/web/src/pages/admin/AdminBackupPage.tsx new file mode 100644 index 0000000..cf54e06 --- /dev/null +++ b/web/src/pages/admin/AdminBackupPage.tsx @@ -0,0 +1,10 @@ +import { BackupSection } from "@/components/backup/BackupSection"; + +/** Admin 区「备份与恢复」:全站(instance)档导出 / 导入。 */ +export function AdminBackupPage() { + return ( +
+ +
+ ); +} diff --git a/web/src/pages/admin/AdminPage.tsx b/web/src/pages/admin/AdminPage.tsx index 2add308..17f1869 100644 --- a/web/src/pages/admin/AdminPage.tsx +++ b/web/src/pages/admin/AdminPage.tsx @@ -1,7 +1,14 @@ import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import { NavLink, Outlet, useLocation, useNavigate } from "react-router"; -import { Users, Settings, Mail, ShieldCheck, ChevronRight } from "lucide-react"; +import { + Users, + Settings, + Mail, + ShieldCheck, + ChevronRight, + DatabaseBackup, +} from "lucide-react"; import { cn } from "@/lib/utils"; import { useIsMobile } from "@/hooks/useIsMobile"; @@ -16,6 +23,7 @@ export function AdminPage() { const tabs = [ { to: "/admin/users", label: t("admin.users"), icon: Users }, { to: "/admin/app", label: t("admin.appSettings"), icon: Settings }, + { to: "/admin/backup", label: t("admin.backup"), icon: DatabaseBackup }, { to: "/admin/email", label: t("admin.emailProvider"), icon: Mail }, { to: "/admin/security", diff --git a/web/src/pages/settings/SettingsPage.tsx b/web/src/pages/settings/SettingsPage.tsx index d4fe54c..078344d 100644 --- a/web/src/pages/settings/SettingsPage.tsx +++ b/web/src/pages/settings/SettingsPage.tsx @@ -20,6 +20,7 @@ import { Copy, Check, AlertTriangle, + DatabaseBackup, } from "lucide-react"; import QRCode from "qrcode"; import { api } from "@/lib/api"; @@ -28,6 +29,7 @@ import { useTheme } from "@/components/ThemeProvider"; import { useIsMobile } from "@/hooks/useIsMobile"; import { ConfirmDialog } from "@/components/ConfirmDialog"; import { PasswordPromptDialog } from "@/components/PasswordPromptDialog"; +import { BackupSection } from "@/components/backup/BackupSection"; import { cn, serializeRegistrationCredential, @@ -38,7 +40,13 @@ import { // Types // --------------------------------------------------------------------------- -type TabId = "account" | "security" | "sessions" | "apiKeys" | "preferences"; +type TabId = + | "account" + | "security" + | "sessions" + | "apiKeys" + | "backup" + | "preferences"; function StatusBadge({ ok }: { ok: boolean }) { const { t } = useTranslation(); @@ -1331,6 +1339,7 @@ export function SettingsPage() { "account", "security", "apiKeys", + "backup", "sessions", "preferences", ]; @@ -1374,6 +1383,11 @@ export function SettingsPage() { label: t("settings.apiKeys"), icon: , }, + { + id: "backup", + label: t("settings.backup"), + icon: , + }, { id: "sessions", label: t("settings.sessions"), @@ -1390,6 +1404,11 @@ export function SettingsPage() { { id: "account" as TabId, label: t("settings.account"), icon: User }, { id: "security" as TabId, label: t("settings.security"), icon: Shield }, { id: "apiKeys" as TabId, label: t("settings.apiKeys"), icon: KeyRound }, + { + id: "backup" as TabId, + label: t("settings.backup"), + icon: DatabaseBackup, + }, { id: "sessions" as TabId, label: t("settings.sessions"), icon: Monitor }, { id: "preferences" as TabId, @@ -1472,6 +1491,7 @@ export function SettingsPage() { {activeTab === "account" && } {activeTab === "security" && } {activeTab === "apiKeys" && } + {activeTab === "backup" && } {activeTab === "sessions" && } {activeTab === "preferences" && }