Files
OpenVPN-Monitoring-Simple/APP_UI/src/views/BackupRestore.vue
T

803 lines
41 KiB
Vue
Raw Normal View History

<template>
<div class="backup-page">
<!-- DESTINATIONS -->
<div class="config-card backup-card">
<div class="config-header">
<h1>Backup Destinations</h1>
</div>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
<span class="text-muted small">Where backup packages are stored. A backup goes to every selected destination.</span>
<button type="button" class="btn-action btn-action-save btn-sm" @click="openAdd" :disabled="!settings.types.length">
<i class="fas fa-plus"></i> Add destination
</button>
</div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Status</th>
<th>Last result</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="5" class="text-center py-4">
<div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</td>
</tr>
<tr v-else-if="destinations.length === 0">
<td colspan="5" class="empty-state text-center py-4">
<i class="fas fa-box-archive fa-2x mb-3 text-muted"></i>
<p class="text-muted mb-0">No destinations yet. Add one to start making backups.</p>
</td>
</tr>
<tr v-for="d in destinations" :key="d.id">
<td>
<div class="fw-semibold" style="color: var(--text-heading);">{{ d.name }}</div>
<div class="text-muted small">{{ destinationSummary(d) }}</div>
<div v-if="typeInfo(d.type)?.pins_host_key" class="small mt-1">
<span v-if="d.params.host_key" class="status-badge status-valid" :title="d.params.host_key">
<i class="fas fa-fingerprint me-1"></i>Host key trusted
</span>
<span v-else class="status-badge status-warning">
<i class="fas fa-triangle-exclamation me-1"></i>Host key not trusted: press Test and confirm it
</span>
</div>
<div v-if="plainFtp(d)" class="small mt-1">
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>No TLS: clear text</span>
</div>
</td>
<td><span class="status-badge status-client">{{ typeLabel(d.type) }}</span></td>
<td>
<span :class="['status-badge', d.enabled ? 'status-valid' : 'status-secondary']">
{{ d.enabled ? 'Enabled' : 'Disabled' }}
</span>
</td>
<td>
<span v-if="d.last_status" :class="['status-badge', d.last_status === 'ok' ? 'status-valid' : 'status-expired']"
:title="d.last_message">
{{ d.last_status === 'ok' ? 'OK' : 'Failed' }}
</span>
<span v-else class="text-muted small">never used</span>
<div v-if="d.last_at" class="text-muted small">{{ formatTime(d.last_at) }}</div>
</td>
<td>
<button class="btn btn-sm btn-link text-primary p-0 me-2" title="Test connection"
@click="testDestination(d)" :disabled="testingId === d.id">
<i v-if="testingId === d.id" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-plug"></i>
</button>
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Edit" @click="openEdit(d)" :disabled="isRunning">
<i class="fas fa-pen"></i>
</button>
<button class="btn btn-sm btn-link text-danger p-0" title="Delete" @click="askDelete(d)" :disabled="isRunning">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- BACKUP -->
<div class="config-card backup-card">
<div class="config-header">
<h1>Backup</h1>
</div>
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
<div>
<span v-if="settings.encryption_enabled" class="status-badge status-valid">
<i class="fas fa-lock me-1"></i>Packages are encrypted
</span>
<span v-else class="status-badge status-warning">
<i class="fas fa-triangle-exclamation me-1"></i>Packages are NOT encrypted
</span>
</div>
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="openPassphrase" :disabled="isRunning">
<i class="fas fa-key"></i> {{ settings.encryption_enabled ? 'Change passphrase' : 'Set passphrase' }}
</button>
</div>
<p class="text-muted small mb-3">
A package contains the CA private key, the certificates and the password hashes of the administrators.
<template v-if="!settings.encryption_enabled">Remote destinations need an encryption passphrase; a local folder can be used without it.</template>
<template v-else>Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.</template>
</p>
<div class="config-divider"></div>
<label class="config-label">Server name</label>
<div class="config-input-group">
<input type="text" class="config-input" v-model="serverNameInput" maxlength="63" autocomplete="off"
placeholder="e.g. vpn-main" :disabled="isRunning" @keyup.enter="saveServerName">
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="saveServerName"
:disabled="isRunning || saving || serverNameInput.trim() === settings.server_name">
<i class="fas fa-floppy-disk"></i> Save
</button>
</div>
<p class="text-muted small mt-2 mb-0">
Package names will start with <strong class="text-main">{{ settings.effective_server_name }}</strong>
<span v-if="settings.server_name_source === 'public_ip'">(the server address from the VPN settings: no name is set)</span>
<span v-else-if="settings.server_name_source === 'hostname'">(the host name, in a container a random identifier: set a name)</span>.
Letters, digits, '.' and '-'. Only packages with the same name in the same folder count for "copies to keep".
The name is not part of a package: set it again on a new server.
</p>
<div class="config-divider"></div>
<label class="config-label">Destinations for this backup</label>
<div v-if="enabledDestinations.length === 0" class="text-muted small mb-3">
No enabled destinations. Add or enable one above.
</div>
<div v-else class="mb-3">
<div v-for="d in enabledDestinations" :key="d.id" class="form-check mb-1">
<input class="form-check-input" type="checkbox" :id="'bk-dest-' + d.id" :value="d.id"
v-model="selectedIds" :disabled="needsPassphrase(d)">
<label class="form-check-label text-main" :for="'bk-dest-' + d.id">
{{ d.name }} <span class="text-muted small">({{ typeLabel(d.type) }})</span>
<span v-if="needsPassphrase(d)" class="text-muted small"> - set a passphrase first</span>
</label>
</div>
</div>
<div class="btn-action-group justify-content-center mt-3">
<button type="button" class="btn-action btn-action-primary" @click="runBackup"
:disabled="isRunning || selectedIds.length === 0">
<i v-if="isRunning && job.kind === 'backup'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-box-archive"></i>
Backup now
</button>
</div>
<!-- Progress and result of the last backup -->
<div v-if="job.kind === 'backup' && job.state !== 'idle'" class="nested-box fade-in mt-4">
<label class="nested-label d-flex justify-content-between">
<span>{{ job.state === 'running' ? 'Backup in progress' : 'Last backup' }}</span>
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
</label>
<ul class="backup-steps">
<li v-for="s in job.stages" :key="s.name">
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
</li>
</ul>
<div v-for="r in job.results" :key="r.destination_id" class="backup-result">
<span :class="['status-badge', resultBadge(r.state)]">
<i v-if="r.state === 'running'" class="fas fa-spinner fa-spin me-1"></i>{{ resultLabel(r.state) }}
</span>
<span class="fw-semibold ms-2" style="color: var(--text-heading);">{{ r.name }}</span>
<div v-if="r.message" class="text-muted small ms-1 mt-1">{{ r.message }}</div>
</div>
<div v-if="job.state !== 'running' && job.message" class="text-muted small mt-2">{{ job.message }}</div>
</div>
<!-- History -->
<div v-if="history.length" class="mt-4">
<label class="config-label">History</label>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr><th>Time</th><th>Action</th><th>Result</th><th>Details</th></tr>
</thead>
<tbody>
<tr v-for="h in history" :key="h.id">
<td>{{ formatTime(h.started_at) }}</td>
<td class="text-capitalize">{{ h.kind }}</td>
<td><span :class="['status-badge', jobBadge(h.state)]">{{ jobLabel(h.state) }}</span></td>
<td class="small text-muted">{{ h.message }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- RESTORE -->
<div class="config-card backup-card">
<div class="config-header">
<h1>Restore</h1>
</div>
<p class="text-muted small mb-3">
Restores the databases, the PKI and the client profiles from a package, also one made on another server.
The current state is saved to a local safety copy first.
</p>
<div class="config-row">
<div class="config-col">
<label class="config-label">Source</label>
<div class="select-container">
<select class="config-select" v-model="restore.sourceId" :disabled="isRunning">
<option :value="null" disabled>Select a destination</option>
<option v-for="d in destinations" :key="d.id" :value="d.id">{{ d.name }} ({{ typeLabel(d.type) }})</option>
</select>
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
</div>
<div v-if="restore.checking" class="text-muted small mt-2">
<i class="fas fa-spinner fa-spin me-1"></i>Checking the source...
</div>
<div v-else-if="restore.sourceError" class="mt-2">
<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Source check failed</span>
<div class="text-muted small mt-1">{{ restore.sourceError }}</div>
</div>
<div v-else-if="restore.sourceId !== null" class="mt-2">
<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Source reachable</span>
<span class="text-muted small ms-2">{{ restore.packages.length }} package(s) found</span>
</div>
</div>
</div>
<div class="config-row">
<div class="config-col">
<label class="config-label">Package (newest first)</label>
<div class="select-container">
<select class="config-select" v-model="restore.packageName"
:disabled="isRunning || restore.checking || restore.packages.length === 0">
<option :value="''" disabled>{{ restore.packages.length ? 'Select a package' : 'No packages' }}</option>
<option v-for="p in restore.packages" :key="p.name" :value="p.name">{{ packageLabel(p) }}</option>
</select>
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
</div>
</div>
</div>
<div v-if="selectedPackage && selectedPackage.encrypted" class="config-row">
<div class="config-col">
<label class="config-label">Package passphrase</label>
<input type="password" class="config-input" v-model="restore.passphrase" autocomplete="off"
placeholder="Passphrase used when the package was made">
</div>
</div>
<div class="btn-action-group justify-content-center">
<button type="button" class="btn-action btn-action-danger" @click="askRestore" :disabled="!canRestore">
<i v-if="isRunning && job.kind === 'restore'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-rotate-left"></i>
Restore
</button>
</div>
<!-- Progress and result of the restore -->
<div v-if="job.kind === 'restore' && job.state !== 'idle'" class="nested-box fade-in mt-4">
<label class="nested-label d-flex justify-content-between">
<span>{{ job.state === 'running' ? 'Restore in progress. Do not close the server.' : 'Last restore' }}</span>
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
</label>
<ul class="backup-steps">
<li v-for="s in job.stages" :key="s.name">
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
</li>
</ul>
<div v-if="job.state !== 'running' && job.message" class="small mt-2" :class="job.state === 'done' ? 'text-main' : 'text-danger'">
{{ job.message }}
</div>
<div v-for="(w, i) in job.warnings" :key="i" class="small mt-1">
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>{{ w }}</span>
</div>
<div v-if="restoreFinishedHere && job.relogin" class="mt-3">
<p class="text-main small mb-2">
The accounts now come from the package. Log in again with the account of the restored server.
Check the server address in the VPN settings if the package comes from another server.
</p>
<button type="button" class="btn-action btn-action-primary btn-sm" @click="logInAgain">
<i class="fas fa-sign-in-alt"></i> Log in again
</button>
</div>
</div>
</div>
<!-- Add / edit destination -->
<BaseModal id="destinationModal" :title="destForm.id ? 'Edit Destination' : 'Add Destination'" ref="destModal">
<template #body>
<form @submit.prevent="saveDestination" id="destForm" autocomplete="off">
<div class="mb-3">
<label class="form-label small fw-bold text-muted text-uppercase">Name</label>
<input type="text" class="form-control" v-model="destForm.name" maxlength="64" required placeholder="e.g. offsite-bucket">
</div>
<div class="mb-3">
<label class="form-label small fw-bold text-muted text-uppercase">Type</label>
<div class="select-container">
<select class="config-select" v-model="destForm.type" @change="onTypeChange">
<option v-for="t in settings.types" :key="t.id" :value="t.id">{{ t.label }}</option>
</select>
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
</div>
<div v-if="currentType && currentType.remote && !settings.encryption_enabled" class="form-text mt-2 small text-warning">
<i class="fas fa-triangle-exclamation me-1"></i>Backups to this type need an encryption passphrase.
</div>
</div>
<div v-for="f in currentFields" :key="f.name" class="mb-3">
<template v-if="f.kind === 'bool'">
<label class="form-label small fw-bold text-muted text-uppercase d-block">{{ f.label }}</label>
<div class="toggle-wrapper">
<label class="toggle-switch">
<input type="checkbox" v-model="destForm.params[f.name]">
<span class="toggle-slider"></span>
</label>
</div>
</template>
<template v-else-if="f.kind === 'secret'">
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
<input type="password" class="form-control" v-model="destForm.secrets[f.name]"
autocomplete="new-password"
:placeholder="secretIsSet(f.name) ? '(unchanged)' : ''">
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
</template>
<template v-else-if="f.kind === 'secret_multiline'">
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
<textarea class="form-control" rows="5" v-model="destForm.secrets[f.name]" spellcheck="false"
autocomplete="off" style="font-family: monospace; font-size: 12px;"
:placeholder="secretIsSet(f.name) ? '(unchanged: paste a new key to replace it)' : '-----BEGIN OPENSSH PRIVATE KEY-----'"></textarea>
</template>
<template v-else-if="f.kind === 'number'">
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
<input type="number" class="form-control" v-model.number="destForm.params[f.name]" min="1" max="65535">
</template>
<template v-else>
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
<input type="text" class="form-control" v-model="destForm.params[f.name]" :placeholder="f.default || ''">
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
</template>
<div v-if="f.warning && destForm.params[f.name] === f.warn_if" class="form-text mt-2 small text-warning">
<i class="fas fa-triangle-exclamation me-1"></i>{{ f.warning }}
</div>
</div>
<div v-if="currentType && currentType.pins_host_key" class="mb-3">
<label class="form-label small fw-bold text-muted text-uppercase">Server host key (SHA-256)</label>
<div v-if="destForm.params.host_key" class="small text-main" style="word-break: break-all;">
{{ destForm.params.host_key }}
</div>
<div v-else class="form-text small text-warning">
<i class="fas fa-triangle-exclamation me-1"></i>Not trusted yet. Save the destination, press Test and confirm the fingerprint. Nothing is copied before that.
</div>
<div class="form-text mt-1 text-muted small">Changing the host or the port clears the trusted key.</div>
</div>
<div class="mb-3">
<label class="form-label small fw-bold text-muted text-uppercase">Copies to keep</label>
<input type="number" class="form-control" v-model.number="destForm.retention_count" min="1" max="1000">
<div class="form-text mt-1 text-muted small">The oldest packages of this server beyond this number are deleted after a successful backup.</div>
</div>
<div class="mb-1 d-flex align-items-center">
<div class="toggle-wrapper me-2">
<label class="toggle-switch">
<input type="checkbox" v-model="destForm.enabled" id="destEnabled">
<span class="toggle-slider"></span>
</label>
</div>
<label class="user-select-none text-muted" for="destEnabled" style="cursor: pointer;">Enabled</label>
</div>
</form>
</template>
<template #footer>
<button type="button" class="btn-action btn-action-secondary" @click="destModal.hide()">Cancel</button>
<button type="submit" form="destForm" class="btn-action btn-action-save" :disabled="saving">
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
{{ destForm.id ? 'Save' : 'Add' }}
</button>
</template>
</BaseModal>
<!-- Passphrase -->
<BaseModal id="passphraseModal" title="Encryption Passphrase" ref="passModal">
<template #body>
<form @submit.prevent="savePassphrase" id="passForm" autocomplete="off">
<p class="text-main small">
Packages made after this change are encrypted with the new passphrase. Older packages keep the
passphrase they were made with: keep it as long as you need them.
</p>
<div class="mb-3">
<label class="form-label small fw-bold text-muted text-uppercase">New passphrase</label>
<input type="password" class="form-control" v-model="passForm.value" autocomplete="new-password"
placeholder="Min. 8 characters" required>
</div>
<div class="mb-2">
<label class="form-label small fw-bold text-muted text-uppercase">Confirm passphrase</label>
<input type="password" class="form-control" v-model="passForm.confirm" autocomplete="new-password" required>
</div>
</form>
</template>
<template #footer>
<button v-if="settings.encryption_enabled" type="button" class="btn-action btn-action-danger me-auto" @click="removePassphrase" :disabled="saving">
Remove passphrase
</button>
<button type="button" class="btn-action btn-action-secondary" @click="passModal.hide()">Cancel</button>
<button type="submit" form="passForm" class="btn-action btn-action-save" :disabled="saving">
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
Save
</button>
</template>
</BaseModal>
<ConfirmModal ref="deleteModal" @confirm="confirmDelete" />
<ConfirmModal ref="restoreModal" @confirm="confirmRestore" />
<ConfirmModal ref="trustModal" @confirm="confirmTrust" />
</div>
</template>
<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { useFormatters } from '../composables/useFormatters';
import BaseModal from '../components/BaseModal.vue';
import ConfirmModal from '../components/ConfirmModal.vue';
const { profilesApiClient } = useApi();
const toast = useToast();
const { formatBytes } = useFormatters();
const loading = ref(true);
const saving = ref(false);
const testingId = ref(null);
const settings = reactive({ encryption_enabled: false, default_retention: 14, local_root: '', types: [],
server_name: '', effective_server_name: '', server_name_source: 'hostname' });
const serverNameInput = ref('');
const destinations = ref([]);
const history = ref([]);
const selectedIds = ref([]);
const job = reactive({ kind: null, state: 'idle', stages: [], results: [], warnings: [], message: null, relogin: false });
const restoreFinishedHere = ref(false);
const destModal = ref(null);
const passModal = ref(null);
const deleteModal = ref(null);
const restoreModal = ref(null);
const trustModal = ref(null);
const destForm = reactive({ id: null, name: '', type: 'local', enabled: true, retention_count: 14, params: {}, secrets: {} });
const existingSecrets = ref({});
const passForm = reactive({ value: '', confirm: '' });
const restore = reactive({ sourceId: null, checking: false, sourceError: '', packages: [], packageName: '', passphrase: '' });
let pollTimer = null;
const errText = (e) => e.response?.data?.detail || e.message;
const isRunning = computed(() => job.state === 'running');
const enabledDestinations = computed(() => destinations.value.filter((d) => d.enabled));
const typeInfo = (id) => settings.types.find((t) => t.id === id);
const typeLabel = (id) => typeInfo(id)?.label || id;
const currentType = computed(() => typeInfo(destForm.type));
const currentFields = computed(() => currentType.value?.fields || []);
const needsPassphrase = (d) => !!typeInfo(d.type)?.remote && !settings.encryption_enabled;
const selectedPackage = computed(() => restore.packages.find((p) => p.name === restore.packageName) || null);
const canRestore = computed(() => !isRunning.value && !!selectedPackage.value
&& (!selectedPackage.value.encrypted || restore.passphrase.length > 0));
// --- formatting ---
const formatTime = (iso) => {
if (!iso) return '';
const d = new Date(iso);
return isNaN(d) ? iso : d.toLocaleString();
};
// Package time: UTC (as in the file name) and the browser's local time
const utcTime = (iso) => (iso ? iso.replace('T', ' ').replace(/(\.\d+)?Z$/, '') + ' UTC' : '');
const packageLabel = (p) => `${p.server_name} - ${utcTime(p.created_at)} (${formatTime(p.created_at)} local) - ${formatBytes(p.size)} - ${p.encrypted ? 'encrypted' : 'not encrypted'}`;
const destinationSummary = (d) => {
const p = d.params || {};
if (d.type === 'local') return `${settings.local_root || ''}/${p.folder || ''}`.replace('//', '/');
if (d.type === 's3') return `${p.bucket}${p.prefix ? '/' + p.prefix : ''} @ ${p.endpoint}`;
if (d.type === 'sftp') return `sftp://${p.username}@${p.host}:${p.port}/${p.directory}`;
if (d.type === 'ftp') return `${p.tls ? 'ftps' : 'ftp'}://${p.username}@${p.host}:${p.port}/${p.directory}`;
return '';
};
const plainFtp = (d) => d.type === 'ftp' && d.params && d.params.tls === false;
const STAGES = {
package: 'Create package', encrypt: 'Encrypt', upload: 'Send to destinations',
download: 'Download package', decrypt: 'Decrypt', verify: 'Verify and unpack',
prepare: 'Check and migrate databases', safety_backup: 'Save current state (safety copy)',
stop_openvpn: 'Stop OpenVPN if running', replace: 'Replace data', finalize: 'Regenerate server config, start OpenVPN'
};
const stageLabel = (n) => STAGES[n] || n;
const stageIcon = (s) => ({
pending: 'far fa-circle text-muted', running: 'fas fa-spinner fa-spin text-primary',
done: 'fas fa-check-circle text-success', error: 'fas fa-times-circle text-danger'
}[s] || 'far fa-circle text-muted');
const jobBadge = (s) => ({ done: 'status-valid', partial: 'status-warning', error: 'status-expired', interrupted: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
const jobLabel = (s) => ({ done: 'Success', partial: 'Partial', error: 'Failed', interrupted: 'Interrupted', running: 'Running' }[s] || s);
const resultBadge = (s) => ({ ok: 'status-valid', error: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
const resultLabel = (s) => ({ ok: 'Stored', error: 'Failed', running: 'Sending', pending: 'Waiting', skipped: 'Skipped' }[s] || s);
// --- loading ---
const loadSettings = async () => {
const res = await profilesApiClient.get('/backup/settings');
Object.assign(settings, res.data);
serverNameInput.value = settings.server_name || '';
};
const loadDestinations = async () => {
const res = await profilesApiClient.get('/backup/destinations');
destinations.value = res.data;
// Keep the choice of the user, drop what no longer exists or is not usable
const usable = new Set(enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id));
selectedIds.value = selectedIds.value.filter((id) => usable.has(id));
};
const loadHistory = async () => {
const res = await profilesApiClient.get('/backup/history', { params: { limit: 10 } });
history.value = res.data;
};
const selectAllUsable = () => {
selectedIds.value = enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id);
};
const stopPolling = () => {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
};
const startPolling = () => {
if (!pollTimer) pollTimer = setInterval(loadStatus, 2000);
};
const loadStatus = async () => {
const wasRunning = job.state === 'running';
try {
const res = await profilesApiClient.get('/backup/status');
Object.assign(job, res.data);
} catch (e) {
return; // keep polling, the next tick may succeed
}
if (job.state === 'running') {
startPolling();
return;
}
stopPolling();
if (wasRunning) await onJobFinished();
};
const onJobFinished = async () => {
if (job.kind === 'restore') {
restoreFinishedHere.value = true;
toast.show(job.message || 'Restore finished', job.state === 'done' ? 'success' : 'error');
} else {
toast.show(job.message || 'Backup finished', job.state === 'done' ? 'success' : (job.state === 'partial' ? 'warning' : 'error'));
}
try {
await Promise.all([loadDestinations(), loadHistory()]);
} catch (e) { /* the session may be gone after a restore: the interceptor redirects */ }
if (job.kind === 'restore') await checkSource();
};
// --- destinations ---
const defaultsFor = (typeId) => {
const params = {};
(typeInfo(typeId)?.fields || []).forEach((f) => {
if (!f.kind.startsWith('secret')) params[f.name] = f.default ?? (f.kind === 'bool' ? false : '');
});
return params;
};
const secretIsSet = (name) => !!existingSecrets.value[name];
const openAdd = () => {
const type = settings.types[0]?.id || 'local';
Object.assign(destForm, { id: null, name: '', type, enabled: true, retention_count: settings.default_retention,
params: defaultsFor(type), secrets: {} });
existingSecrets.value = {};
destModal.value.show();
};
const openEdit = (d) => {
Object.assign(destForm, { id: d.id, name: d.name, type: d.type, enabled: d.enabled,
retention_count: d.retention_count, params: { ...defaultsFor(d.type), ...d.params }, secrets: {} });
existingSecrets.value = { ...d.secrets };
destModal.value.show();
};
const onTypeChange = () => {
destForm.params = defaultsFor(destForm.type);
destForm.secrets = {};
existingSecrets.value = {};
};
const saveDestination = async () => {
saving.value = true;
const body = { name: destForm.name, type: destForm.type, enabled: destForm.enabled,
retention_count: destForm.retention_count, params: destForm.params, secrets: destForm.secrets };
try {
if (destForm.id) await profilesApiClient.put(`/backup/destinations/${destForm.id}`, body);
else await profilesApiClient.post('/backup/destinations', body);
toast.show('Destination saved.', 'success');
destModal.value.hide();
await loadDestinations();
if (!destForm.id) selectAllUsable();
} catch (e) {
toast.show(errText(e), 'error');
} finally {
saving.value = false;
}
};
const testDestination = async (d) => {
testingId.value = d.id;
try {
const res = await profilesApiClient.post(`/backup/destinations/${d.id}/test`);
if (res.data.needs_trust) askTrust(d, res.data);
else toast.show(res.data.message, res.data.ok ? 'success' : 'error');
await loadDestinations();
} catch (e) {
toast.show(errText(e), 'error');
} finally {
testingId.value = null;
}
};
// SFTP: the server shows its host key; the administrator compares the fingerprint and trusts it
const askTrust = (d, r) => {
trustModal.value.open({
title: r.key_changed ? 'Host Key Changed' : 'Trust This Server?',
message:
(r.key_changed
? 'WARNING: the server now shows a different host key than the trusted one. This happens after a reinstall of the server, but also during an attack.\n\n'
: `The server of "${d.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.\n\n`) +
`Type: ${r.key_type}\nSHA-256: ${r.fingerprint}\n\n` +
'Packages are sent only to a server with exactly this key.',
confirmText: r.key_changed ? 'Trust the new key' : 'Trust',
confirmBtnClass: r.key_changed ? 'btn-action-danger' : 'btn-action-primary',
data: { id: d.id, name: d.name, fingerprint: r.fingerprint }
});
};
const confirmTrust = async (t) => {
try {
await profilesApiClient.post(`/backup/destinations/${t.id}/trust-host-key`, { fingerprint: t.fingerprint });
toast.show(`Host key of ${t.name} trusted. Press Test to check the connection.`, 'success');
await loadDestinations();
} catch (e) {
toast.show(errText(e), 'error');
}
};
const askDelete = (d) => {
deleteModal.value.open({
title: 'Delete Destination?',
message: `Delete "${d.name}"? Packages already stored there are not deleted.`,
confirmText: 'Yes, Delete',
data: d
});
};
const confirmDelete = async (d) => {
try {
await profilesApiClient.delete(`/backup/destinations/${d.id}`);
toast.show(`${d.name} deleted.`, 'success');
if (restore.sourceId === d.id) restore.sourceId = null;
await loadDestinations();
} catch (e) {
toast.show(errText(e), 'error');
}
};
// --- passphrase ---
const openPassphrase = () => {
passForm.value = '';
passForm.confirm = '';
passModal.value.show();
};
const savePassphrase = async () => {
if (passForm.value !== passForm.confirm) {
toast.show('Passphrases do not match.', 'error');
return;
}
await updateSettings({ passphrase: passForm.value }, 'Passphrase saved.');
};
const removePassphrase = async () => {
await updateSettings({ clear_passphrase: true }, 'Passphrase removed. New packages are not encrypted.');
};
const saveServerName = async () => {
const value = serverNameInput.value.trim();
if (value === (settings.server_name || '')) return;
saving.value = true;
try {
const res = await profilesApiClient.put('/backup/settings', { server_name: value });
Object.assign(settings, res.data);
serverNameInput.value = settings.server_name || '';
toast.show(value ? 'Server name saved.' : 'Server name cleared.', 'success');
} catch (e) {
toast.show(errText(e), 'error');
} finally {
saving.value = false;
}
};
const updateSettings = async (body, okText) => {
saving.value = true;
try {
const res = await profilesApiClient.put('/backup/settings', body);
Object.assign(settings, res.data);
toast.show(okText, 'success');
passModal.value.hide();
await loadDestinations();
} catch (e) {
toast.show(errText(e), 'error');
} finally {
saving.value = false;
}
};
// --- backup ---
const runBackup = async () => {
try {
await profilesApiClient.post('/backup/run', { destination_ids: selectedIds.value });
restoreFinishedHere.value = false;
job.kind = 'backup';
job.state = 'running';
await loadStatus();
startPolling();
} catch (e) {
if (e.response?.status === 409) await loadStatus();
toast.show(errText(e), 'error');
}
};
// --- restore ---
const checkSource = async () => {
restore.packages = [];
restore.packageName = '';
restore.passphrase = '';
restore.sourceError = '';
if (restore.sourceId === null) return;
restore.checking = true;
try {
const res = await profilesApiClient.get(`/backup/destinations/${restore.sourceId}/packages`);
restore.packages = res.data.packages;
} catch (e) {
restore.sourceError = errText(e);
} finally {
restore.checking = false;
}
};
watch(() => restore.sourceId, checkSource);
const askRestore = () => {
const p = selectedPackage.value;
restoreModal.value.open({
title: 'Restore from Backup?',
message:
`Package: ${p.server_name}, ${utcTime(p.created_at)} (${formatTime(p.created_at)} local)\n\n` +
'This replaces:\n' +
'- the monitoring database (statistics, administrator accounts, 2FA),\n' +
'- the profiler database and the server settings,\n' +
'- the PKI (CA, keys, certificates) and the client profiles.\n\n' +
'OpenVPN is stopped and started again; connected clients are disconnected. ' +
'The current state is saved to a local safety copy first. You will have to log in again.',
confirmText: 'Yes, Restore',
confirmBtnClass: 'btn-action-danger',
data: p
});
};
const confirmRestore = async (p) => {
try {
await profilesApiClient.post('/backup/restore', {
destination_id: restore.sourceId,
package: p.name,
passphrase: p.encrypted ? restore.passphrase : null
});
restoreFinishedHere.value = false;
restore.passphrase = '';
job.kind = 'restore';
job.state = 'running';
await loadStatus();
startPolling();
} catch (e) {
toast.show(errText(e), 'error');
}
};
const logInAgain = () => {
localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user');
window.location.href = '/login';
};
onMounted(async () => {
try {
await loadSettings();
await loadDestinations();
selectAllUsable();
await Promise.all([loadHistory(), loadStatus()]);
} catch (e) {
toast.show(`Failed to load backup settings: ${errText(e)}`, 'error');
} finally {
loading.value = false;
}
});
onUnmounted(stopPolling);
</script>