Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
799 changes: 799 additions & 0 deletions backend/internal/backup.js

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion backend/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ const importer = new signale.Signale({ scope: "Importer ", ...opts });
const setup = new signale.Signale({ scope: "Setup ", ...opts });
const ipRanges = new signale.Signale({ scope: "IP Ranges", ...opts });
const remoteVersion = new signale.Signale({ scope: "Remote Version", ...opts });
const backup = new signale.Signale({ scope: "Backup ", ...opts });

const debug = (logger, ...args) => {
if (isDebugMode()) {
logger.debug(...args);
}
};

export { debug, global, migrate, express, access, nginx, ssl, certbot, importer, setup, ipRanges, remoteVersion };
export { debug, global, migrate, express, access, nginx, ssl, certbot, importer, setup, ipRanges, remoteVersion, backup };
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
"@apidevtools/json-schema-ref-parser": "^11.7.0",
"ajv": "^8.17.1",
"archiver": "^5.3.0",
"archiver-zip-encrypted": "^2.0.0",
"batchflow": "^0.4.0",
"bcrypt": "^5.0.0",
"body-parser": "^1.20.3",
"compression": "^1.7.4",
"express": "^4.22.0",
"express-fileupload": "^1.5.2",
"unzipper": "^0.12.3",
"gravatar": "^1.8.2",
"jsonwebtoken": "^9.0.2",
"knex": "2.4.2",
Expand Down
63 changes: 63 additions & 0 deletions backend/routes/backup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import express from "express";
import internalBackup from "../internal/backup.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import { debug, backup as logger } from "../logger.js";

const router = express.Router({
caseSensitive: true,
strict: true,
mergeParams: true,
});

/**
* Export Configuration
*
* GET /api/backup/export
*/
router
.route("/export")
.options((_req, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
.get(async (req, res, next) => {
try {
req.setTimeout(300000); // 5 minutes timeout for large exports
const password = req.query.password || null;
const result = await internalBackup.exportAll(res.locals.access, password);
res.status(200).download(result.fileName);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
});

/**
* Import Configuration
*
* POST /api/backup/import
*/
router
.route("/import")
.options((_req, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
.post(async (req, res, next) => {
if (!req.files || !req.files.backup) {
res.status(400).send({ error: { message: "No backup file uploaded" } });
return;
}

try {
req.setTimeout(600000); // 10 minutes timeout for large imports
const password = req.body.password || null;
const result = await internalBackup.importAll(res.locals.access, req.files.backup, password);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
});

export default router;
2 changes: 2 additions & 0 deletions backend/routes/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import errs from "../lib/error.js";
import pjson from "../package.json" with { type: "json" };
import { isSetup } from "../setup.js";
import auditLogRoutes from "./audit-log.js";
import backupRoutes from "./backup.js";
import accessListsRoutes from "./nginx/access_lists.js";
import certificatesHostsRoutes from "./nginx/certificates.js";
import deadHostsRoutes from "./nginx/dead_hosts.js";
Expand Down Expand Up @@ -48,6 +49,7 @@ router.use("/audit-log", auditLogRoutes);
router.use("/reports", reportsRoutes);
router.use("/settings", settingsRoutes);
router.use("/version", versionRoutes);
router.use("/backup", backupRoutes);
router.use("/nginx/proxy-hosts", proxyHostsRoutes);
router.use("/nginx/redirection-hosts", redirectionHostsRoutes);
router.use("/nginx/dead-hosts", deadHostsRoutes);
Expand Down
29 changes: 29 additions & 0 deletions frontend/src/api/backend/backup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as api from "./base";

export interface ImportResult {
success: boolean;
message: string;
}

export async function exportBackup(password?: string): Promise<void> {
const params = password ? `?password=${encodeURIComponent(password)}` : "";
await api.download(
{
url: `/backup/export${params}`,
},
`npm-backup-${Date.now()}.zip`,
);
}

export async function importBackup(file: File, password?: string): Promise<ImportResult> {
const formData = new FormData();
formData.append("backup", file);
if (password) {
formData.append("password", password);
}

return await api.post({
url: "/backup/import",
data: formData,
});
}
1 change: 1 addition & 0 deletions frontend/src/api/backend/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./backup";
export * from "./checkVersion";
export * from "./createAccessList";
export * from "./createCertificate";
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/components/Table/Formatter/EventFormatter.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IconArrowsCross, IconBolt, IconBoltOff, IconDisc, IconLock, IconShield, IconUser } from "@tabler/icons-react";
import { IconArchive, IconArrowsCross, IconBolt, IconBoltOff, IconDisc, IconLock, IconShield, IconUser } from "@tabler/icons-react";
import cn from "classnames";
import type { AuditLog } from "src/api/backend";
import { useLocaleState } from "src/context";
Expand All @@ -17,6 +17,8 @@ const getEventValue = (event: AuditLog) => {
return event.meta?.incomingPort || "N/A";
case "certificate":
return event.meta?.domainNames?.join(", ") || event.meta?.niceName || "N/A";
case "backup":
return event.meta?.exportedAt || event.meta?.importedAt || "N/A";
default:
return `UNKNOWN EVENT TYPE: ${event.objectType}`;
}
Expand Down Expand Up @@ -58,6 +60,9 @@ const getIcon = (row: AuditLog) => {
case "certificate":
ico = <IconShield size={16} className={c} />;
break;
case "backup":
ico = <IconArchive size={16} className={c} />;
break;
}

return ico;
Expand Down
1 change: 1 addition & 0 deletions frontend/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./useAccessList";
export * from "./useBackup";
export * from "./useAccessLists";
export * from "./useAuditLog";
export * from "./useAuditLogs";
Expand Down
33 changes: 33 additions & 0 deletions frontend/src/hooks/useBackup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { exportBackup, importBackup, type ImportResult } from "src/api/backend";
import AuthStore from "src/modules/AuthStore";

const useExportBackup = () => {
return useMutation<void, Error, string | undefined>({
mutationFn: (password?: string) => exportBackup(password),
});
};

interface ImportBackupParams {
file: File;
password?: string;
}

const useImportBackup = () => {
const queryClient = useQueryClient();

return useMutation<ImportResult, Error, ImportBackupParams>({
mutationFn: ({ file, password }: ImportBackupParams) => importBackup(file, password),
onSuccess: () => {
// Force logout user and do a full navigation to ensure fresh state
AuthStore.clear();
queryClient.clear();
// Small delay to ensure backend has fully completed
setTimeout(() => {
window.location.href = "/";
}, 1000);
},
});
};

export { useExportBackup, useImportBackup };
75 changes: 75 additions & 0 deletions frontend/src/locale/src/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,12 @@
"object.event.enabled": {
"defaultMessage": "Enabled {object}"
},
"object.event.exported": {
"defaultMessage": "Exported {object}"
},
"object.event.imported": {
"defaultMessage": "Imported {object}"
},
"object.event.renewed": {
"defaultMessage": "Renewed {object}"
},
Expand Down Expand Up @@ -650,6 +656,75 @@
"settings": {
"defaultMessage": "Settings"
},
"settings.backup": {
"defaultMessage": "Backup & Restore"
},
"settings.backup.export.button": {
"defaultMessage": "Export Backup"
},
"settings.backup.export.description": {
"defaultMessage": "Download a backup of all your configuration including hosts, access lists, certificates, users, and settings."
},
"settings.backup.export.password.confirm": {
"defaultMessage": "Confirm password"
},
"settings.backup.export.password.enable": {
"defaultMessage": "Protect with password"
},
"settings.backup.export.password.label": {
"defaultMessage": "Password"
},
"settings.backup.export.password.mismatch": {
"defaultMessage": "Passwords do not match"
},
"settings.backup.export.secrets-warning": {
"defaultMessage": "This backup may contain sensitive data including SSL certificates, private keys, DNS provider credentials, and htpasswd files. Consider using password protection."
},
"settings.backup.export.success": {
"defaultMessage": "Backup exported successfully"
},
"settings.backup.export.title": {
"defaultMessage": "Export Configuration"
},
"settings.backup.import.confirm.button": {
"defaultMessage": "Import Backup"
},
"settings.backup.import.confirm.file": {
"defaultMessage": "File"
},
"settings.backup.import.confirm.logout": {
"defaultMessage": "You will be logged out and required to log in again after the import is complete."
},
"settings.backup.import.confirm.message": {
"defaultMessage": "Are you sure you want to import this backup? All existing hosts, access lists, certificates, users, and settings will be replaced."
},
"settings.backup.import.confirm.title": {
"defaultMessage": "Confirm Import"
},
"settings.backup.import.confirm.warning": {
"defaultMessage": "This will permanently delete all existing configuration!"
},
"settings.backup.import.description": {
"defaultMessage": "Restore configuration from a previously exported backup file."
},
"settings.backup.import.password.hint": {
"defaultMessage": "Enter password if the backup is encrypted"
},
"settings.backup.import.password.label": {
"defaultMessage": "Password (if encrypted)"
},
"settings.backup.import.progress": {
"defaultMessage": "Importing backup... This may take a few minutes."
},
"settings.backup.import.success": {
"defaultMessage": "Backup imported successfully. You may need to refresh the page."
},
"settings.backup.import.title": {
"defaultMessage": "Import Configuration"
},
"settings.backup.import.warning": {
"defaultMessage": "Warning: Importing a backup will replace ALL existing configuration data. This action cannot be undone."
},
"settings.default-site": {
"defaultMessage": "Default Site"
},
Expand Down
Loading