Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(desktop): copy scheduled backups to WebDAV (#763)

Dariusz Koryto714f5b7029ea
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 07b05b69..0ebd9aeb 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -24,6 +24,7 @@
"electron-updater": "^6.6.2",
"fflate": "0.8.3",
"npm": "11.21.0",
+ "webdav": "^5.10.0",
"zod": "4.6.6"
}
}
diff --git a/apps/desktop/src/main/backup-ipc.mjs b/apps/desktop/src/main/backup-ipc.mjs
index c487d2a9..7c99765c 100644
--- a/apps/desktop/src/main/backup-ipc.mjs
+++ b/apps/desktop/src/main/backup-ipc.mjs
@@ -32,6 +32,9 @@ export const registerBackupIpc = ({ ipcMain, manager, getWindow, dialog, shell }
case "delete-history": value = await manager.deleteHistory(input?.name, input.backupSetId); break;
case "prepare-import": value = await manager.prepareImport(input?.id, input?.password); break;
case "confirm-import": manager.confirmImport(); value = manager.status(); break;
+ case "offsite-save": value = await manager.saveOffsite(input?.config, input?.password, input.backupSetId); void manager.tick(); break;
+ case "offsite-test": value = await manager.testOffsite(input?.config, input?.password, input.backupSetId); break;
+ case "offsite-upload": value = manager.uploadOffsiteNow(input.backupSetId); break;
default: throw Object.assign(new Error("Unknown backup action"), { code: "backup_invalid_action" });
}
if (action !== "status") checkScope();
diff --git a/apps/desktop/src/main/backup-manager.mjs b/apps/desktop/src/main/backup-manager.mjs
index 824299f6..32112bb0 100644
--- a/apps/desktop/src/main/backup-manager.mjs
+++ b/apps/desktop/src/main/backup-manager.mjs
@@ -31,8 +31,10 @@ const ownedDirectoriesExist = async (paths) => {
};
export class BackupManager {
- constructor({ userData, defaultDirectory, secureStorage, platform = process.platform, workerFactory, onChange = () => {}, onSuccess = () => {}, onDiagnostic = () => {}, version = { edgeeverVersion: "unknown", buildId: "unknown" } }) {
- Object.assign(this, { userData, defaultDirectory, secureStorage, platform, onChange, onSuccess, onDiagnostic, version });
+ constructor({ userData, defaultDirectory, secureStorage, platform = process.platform, workerFactory, offsite = null, onChange = () => {}, onSuccess = () => {}, onDiagnostic = () => {}, version = { edgeeverVersion: "unknown", buildId: "unknown" } }) {
+ Object.assign(this, { userData, defaultDirectory, secureStorage, platform, offsite, onChange, onSuccess, onDiagnostic, version });
+ // Off-site copies report through the same status but never join the local backup queue.
+ if (offsite) offsite.onChange = () => this.emit();
this.workerFactory = workerFactory ?? ((data) => new Worker(new URL("../../build/backup-worker.mjs", import.meta.url), { workerData: data }));
this.generation = 0; this.context = null; this.record = null; this.task = null; this.operation = null; this.closed = false; this.transitioning = false;
this.approvedDirectories = new Set([defaultDirectory]);
@@ -58,7 +60,7 @@ export class BackupManager {
lastCheck: r.lastCheck ?? null, lastSuccessAt: r.lastSuccessAt ?? null, lastRestoreAt: r.lastRestoreAt ?? null, nextDueAt: r.config.enabled ? nextBackupAt(r.scheduleAnchorAt ?? r.lastSuccessAt, r.config.interval) : null,
error: r.error ?? null, warning: r.warning ?? null, importError: r.importError ?? null, importWarning: r.importWarning ?? null, history: r.history.filter((item) => item.directory === r.config.directory), task: this.task,
pendingPublication: r.pending ? { name: r.pending.name, encrypted: r.pending.encrypted } : null,
- target: { baseUrl: this.context.baseUrl, accountId: this.context.accountId } });
+ target: { baseUrl: this.context.baseUrl, accountId: this.context.accountId }, offsite: this.offsite?.status() ?? null });
}
emit() { try { this.onChange(this.status()); } catch { /* A renderer can disappear while background work continues. */ } }
exclusive(action) {
@@ -78,6 +80,7 @@ export class BackupManager {
if (generation !== this.generation) return;
this.approvedDirectories = new Set([this.defaultDirectory]);
this.context = next; this.record = null; this.selection = null; this.initializationError = null;
+ await this.offsite?.setScope(null);
if (!next) { this.transitioning = false; this.emit(); return; }
this.scope = accountScopeKey(next.baseUrl, next.accountId);
await assertDirectory(join(this.userData, "scheduled-backups"), true);
@@ -93,6 +96,7 @@ export class BackupManager {
this.approvedDirectories.add(this.record.config.directory);
await this.cleanStaging();
await this.persist();
+ if (generation === this.generation) await this.offsite?.setScope(this.scope, this.record.backupSetId);
if (generation === this.generation) { this.transitioning = false; this.emit(); }
});
if (generation === this.generation && this.record?.pending && !this.operation) await this.recoverPublication();
@@ -180,7 +184,9 @@ export class BackupManager {
}
catch { this.secureUnavailable = true; this.emit(); throw backupError("backup_secure_storage_unavailable", "Unlock secure storage or set the backup password again."); }
}
+ latestLocalBackup() { return this.record?.history.filter((item) => item.directory === this.record.config.directory).at(-1); }
async tick(now = Date.now()) {
+ if (!this.closed && !this.transitioning && this.record && !this.initializationError) this.offsite?.tick(this.latestLocalBackup(), this.record.config.retention);
if (this.closed || this.transitioning || !this.record?.config.enabled || this.operation || this.checking) return;
this.checking = true;
const record = this.record; const generation = this.generation;
@@ -374,7 +380,10 @@ export class BackupManager {
await rm(path, { force: true }); this.record.history = this.record.history.filter((item) => item !== old);
} catch { this.record.warning = { code: "backup_cleanup_failed" }; }
}
- await this.persist(); return true;
+ await this.persist();
+ // Starts in the background; its result never changes this backup's status.
+ if (isCurrent() && entry.directory === this.record.config.directory) this.offsite?.enqueue(entry, this.record.config.retention);
+ return true;
}
async cleanStaging() {
if (this.record.activePart) {
@@ -499,5 +508,17 @@ export class BackupManager {
this.assertReady(); if (!this.operation || this.task?.kind !== "import" || this.task.phase !== "ready") throw backupError("backup_import_not_ready", "Wait for the archive check to finish.");
this.task = { ...this.task, phase: "restoring" }; this.emit(); this.operation.worker.postMessage({ type: "confirm" });
}
- async close() { this.closed = true; this.startupController?.abort(); ++this.generation; await this.cancel(); await this.queue; }
+ saveOffsite(config, password, expected) {
+ this.assertReady(); this.assertScope(expected);
+ return this.offsite.save(config, password).then(() => this.status());
+ }
+ testOffsite(config, password, expected) { this.assertReady(); this.assertScope(expected); return this.offsite.test(config, password); }
+ uploadOffsiteNow(expected) {
+ this.assertReady(); this.assertScope(expected);
+ const latest = this.latestLocalBackup();
+ if (!latest) throw backupError("offsite_no_backup", "Run a local backup first.");
+ if (!this.offsite.tick(latest, this.record.config.retention, { force: true }) && !this.offsite.upload) throw backupError("offsite_already_uploaded", "The latest backup is already copied.");
+ return this.status();
+ }
+ async close() { this.closed = true; this.startupController?.abort(); ++this.generation; await this.offsite?.setScope(null); await this.cancel(); await this.queue; }
}
diff --git a/apps/desktop/src/main/backup-offsite.mjs b/apps/desktop/src/main/backup-offsite.mjs
new file mode 100644
index 00000000..638fa7ec
--- /dev/null
+++ b/apps/desktop/src/main/backup-offsite.mjs
@@ -0,0 +1,321 @@
+import { randomUUID } from "node:crypto";
+import { lstat, open, readFile, rename, rm } from "node:fs/promises";
+import { isIP } from "node:net";
+import { join, posix } from "node:path";
+import { Transform } from "node:stream";
+import { backupError } from "./backup-settings.mjs";
+
+export const DEFAULT_OFFSITE_FOLDER = "/EdgeEver/backups";
+const RETRY_AFTER_MS = 3600000;
+const STALL_TIMEOUT_MS = 120000;
+
+const privateHost = (hostname) => {
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".lan") || host.endsWith(".home.arpa") || !host.includes(".") && !isIP(host)) return true;
+ if (isIP(host) === 4) {
+ const [a, b] = host.split(".").map(Number);
+ return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
+ }
+ return isIP(host) === 6 && (host === "::1" || /^f[cd]/.test(host) || host.startsWith("fe80:"));
+};
+
+export const normalizeOffsiteConfig = (input) => {
+ if (input === undefined) return { enabled: false, url: "", username: "", folder: DEFAULT_OFFSITE_FOLDER };
+ if (!input || typeof input.enabled !== "boolean" || typeof input.url !== "string" || typeof input.username !== "string" || typeof input.folder !== "string") {
+ throw backupError("offsite_invalid_configuration", "The off-site copy settings are invalid.");
+ }
+ const rawUrl = input.url.trim();
+ let url = "";
+ if (rawUrl) {
+ let parsed;
+ try { parsed = new URL(rawUrl); } catch { throw backupError("offsite_invalid_url", "Enter a valid WebDAV address."); }
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) throw backupError("offsite_invalid_url", "Enter the address without a username, password, query or fragment.");
+ // Basic authentication sends the password with every request.
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && privateHost(parsed.hostname))) throw backupError("offsite_insecure_url", "Use an https:// address. http:// is only allowed on a local network.");
+ url = parsed.href.replace(/\/+$/, "");
+ }
+ const folder = `/${input.folder.trim().split("/").filter(Boolean).join("/")}`;
+ if (folder.length > 512 || Array.from(folder).some((character) => character.charCodeAt(0) < 32) || /\\/.test(folder) || folder.split("/").some((part) => part === "." || part === "..")) {
+ throw backupError("offsite_invalid_folder", "Enter a remote folder without . or .. segments.");
+ }
+ const username = input.username.trim();
+ if (username.length > 256) throw backupError("offsite_invalid_configuration", "The username is too long.");
+ if (input.enabled && (!url || !username)) throw backupError("offsite_invalid_configuration", "Enter the WebDAV address and username.");
+ return { enabled: input.enabled, url, username, folder: folder === "/" ? DEFAULT_OFFSITE_FOLDER : folder };
+};
+
+const stalled = () => backupError("offsite_stalled", "The WebDAV server stopped responding.");
+// Rejects when the signal aborts, even if a request ignores its signal.
+const whenAborted = (signal) => new Promise((_resolve, reject) => {
+ if (signal.aborted) reject(signal.reason);
+ else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
+});
+
+const targetKey = (config) => JSON.stringify([config.url, config.username, config.folder]);
+// The saved password belongs to the server and account it was entered for.
+const credentialKey = (config) => JSON.stringify([config.url, config.username]);
+
+export const offsiteErrorInfo = (error) => {
+ if (error?.code?.startsWith?.("offsite_")) return { code: error.code, message: error.message };
+ const status = error?.status ?? error?.response?.status;
+ if (status === 401 || status === 403) return { code: "offsite_auth_failed", message: "The WebDAV server rejected the username or password.", status };
+ if (status === 413) return { code: "offsite_file_too_large", message: "The backup file is too large for this WebDAV server.", status };
+ if (status === 507) return { code: "offsite_storage_full", message: "The WebDAV server has no space left.", status };
+ if (Number.isInteger(status)) return { code: "offsite_upload_failed", message: `The WebDAV server answered ${status}.`, status };
+ const cause = error?.cause?.code ?? error?.code;
+ if (["ENOTFOUND", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ConnectionRefused", "FailedToOpenSocket"].includes(cause)) return { code: "offsite_unreachable", message: "The WebDAV server could not be reached." };
+ return { code: "offsite_upload_failed", message: "The off-site copy failed." };
+};
+
+/**
+ * Copies completed local backups to WebDAV. It keeps its own state and never
+ * runs inside the local backup queue, so a slow or failed upload cannot block
+ * local backups or change their result.
+ */
+export class OffsiteBackup {
+ constructor({ userData, secureStorage, platform = process.platform, clientFactory, onChange = () => {}, now = () => Date.now(), stallTimeoutMs = STALL_TIMEOUT_MS }) {
+ Object.assign(this, { userData, secureStorage, platform, onChange, now, stallTimeoutMs });
+ this.clientFactory = clientFactory ?? (async (url, options) => (await import("webdav")).createClient(url, options));
+ this.generation = 0; this.scope = null; this.backupSetId = null; this.record = null; this.upload = null; this.queued = null;
+ }
+ directory() { return join(this.userData, "scheduled-backups"); }
+ statePath() { return join(this.directory(), `${this.scope}.offsite.json`); }
+ secretPath(passwordId = this.record?.passwordId, scope = this.scope) { return join(this.directory(), `${scope}.offsite.${passwordId}.secret`); }
+ secureAvailable() {
+ try { return this.secureStorage.isEncryptionAvailable() && !(this.platform === "linux" && this.secureStorage.getSelectedStorageBackend?.() === "basic_text"); } catch { return false; }
+ }
+ async persist() {
+ const path = this.statePath(); const temporary = `${path}.${randomUUID()}.tmp`;
+ const file = await open(temporary, "wx", 0o600);
+ try { await file.writeFile(JSON.stringify(this.record)); await file.sync(); await file.close(); await rename(temporary, path); }
+ finally { await file.close().catch(() => {}); await rm(temporary, { force: true }); }
+ }
+ status() {
+ if (!this.record) return null;
+ const r = this.record;
+ return structuredClone({ config: r.config, passwordSet: Boolean(r.passwordId), secureStorageAvailable: this.secureAvailable(),
+ lastAttemptAt: r.lastAttemptAt ?? null, lastSuccessAt: r.lastSuccessAt ?? null, lastUploaded: r.uploads.at(-1) ? { name: r.uploads.at(-1).name, size: r.uploads.at(-1).size, uploadedAt: r.uploads.at(-1).uploadedAt } : null,
+ error: r.error ?? null, warning: r.warning ?? null, task: this.upload ? { name: this.upload.name, sent: this.upload.sent, total: this.upload.total } : null });
+ }
+ emit() { try { this.onChange(this.status()); } catch { /* A renderer can disappear while uploads continue. */ } }
+
+ /** Called when the backup account changes; cancels any upload for the previous one. */
+ async setScope(scope, backupSetId) {
+ const generation = ++this.generation;
+ this.cancel();
+ this.scope = scope ?? null; this.backupSetId = backupSetId ?? null; this.record = null; this.queued = null;
+ if (!this.scope || !/^[a-f0-9-]{36}$/.test(this.backupSetId ?? "")) { this.emit(); return; }
+ // A missing or unreadable state file starts with the option turned off.
+ const stored = await readFile(this.statePath(), "utf8").then(JSON.parse).catch(() => null);
+ if (generation !== this.generation) return;
+ const valid = stored && Array.isArray(stored.uploads) && stored.uploads.every((item) => typeof item?.name === "string" && typeof item.remotePath === "string" && typeof item.target === "string" && Number.isSafeInteger(item.size));
+ let config;
+ try { config = normalizeOffsiteConfig(valid ? stored.config : undefined); } catch { config = normalizeOffsiteConfig(undefined); }
+ this.record = valid ? { ...stored, config } : { config, uploads: [] };
+ if (this.record.passwordId !== undefined && !/^[a-f0-9-]{36}$/.test(this.record.passwordId)) delete this.record.passwordId;
+ this.emit();
+ // An interrupted upload leaves a .part file; remove it on the next start.
+ if (this.record.activePart) void this.removeActivePart(generation);
+ }
+ assertReady() { if (!this.record) throw backupError("backup_login_required", "Sign in to an EdgeEver instance first."); }
+
+ async save(config, password) {
+ this.assertReady(); const generation = this.generation;
+ const normalized = normalizeOffsiteConfig(config);
+ const previous = this.record;
+ const next = { ...previous, config: normalized, error: null };
+ let newSecret;
+ if (password !== undefined) {
+ if (typeof password !== "string" || !password.length) throw backupError("offsite_password_required", "Enter the WebDAV password.");
+ if (!this.secureAvailable() || !await this.secureStorage.isAsyncEncryptionAvailable().catch(() => false)) throw backupError("offsite_secure_storage_unavailable", "Unlock secure storage to save the WebDAV password.");
+ next.passwordId = randomUUID(); newSecret = this.secretPath(next.passwordId);
+ const file = await open(newSecret, "wx", 0o600);
+ try { await file.writeFile(await this.secureStorage.encryptStringAsync(password)); await file.sync(); } finally { await file.close(); }
+ }
+ // A new address or username never reuses the saved password, so it cannot be sent to another server.
+ const dropSecret = !newSecret && previous.passwordId && credentialKey(previous.config) !== credentialKey(normalized);
+ if (dropSecret) delete next.passwordId;
+ if (normalized.enabled && !next.passwordId) { if (newSecret) await rm(newSecret, { force: true }); throw backupError("offsite_password_required", "Enter the WebDAV password."); }
+ if (generation !== this.generation) { if (newSecret) await rm(newSecret, { force: true }); throw backupError("backup_account_changed", "The backup account changed."); }
+ // Turning the copy off or pointing it elsewhere stops the running upload before it can publish.
+ if (!normalized.enabled || targetKey(previous.config) !== targetKey(normalized)) this.cancel();
+ this.record = next;
+ try { await this.persist(); }
+ catch (error) { this.record = previous; if (newSecret) await rm(newSecret, { force: true }); throw error; }
+ if ((newSecret || dropSecret) && previous.passwordId) await rm(this.secretPath(previous.passwordId), { force: true }).catch(() => {});
+ this.emit(); return this.status();
+ }
+
+ /** Reads the password saved with `record` in `scope`, captured by the caller before any await. */
+ async password(record = this.record, scope = this.scope) {
+ if (!record?.passwordId) throw backupError("offsite_password_required", "Enter the WebDAV password.");
+ if (!this.secureAvailable() || !await this.secureStorage.isAsyncEncryptionAvailable().catch(() => false)) throw backupError("offsite_secure_storage_unavailable", "Unlock secure storage to use the saved WebDAV password.");
+ try {
+ const path = this.secretPath(record.passwordId, scope);
+ const { result, shouldReEncrypt } = await this.secureStorage.decryptStringAsync(await readFile(path));
+ if (shouldReEncrypt) { const temporary = `${path}.${randomUUID()}.tmp`;
+ const file = await open(temporary, "wx", 0o600);
+ try { await file.writeFile(await this.secureStorage.encryptStringAsync(result)); await file.sync(); await file.close(); await rename(temporary, path); }
+ finally { await file.close().catch(() => {}); await rm(temporary, { force: true }); }
+ }
+ return result;
+ } catch { throw backupError("offsite_secure_storage_unavailable", "Unlock secure storage or enter the WebDAV password again."); }
+ }
+ async client(config, password) { return this.clientFactory(config.url, { username: config.username, password }); }
+
+ /** Bounds one WebDAV request by the stall timeout and by `parent`, so a stuck request cannot block later copies. */
+ async request(run, parent) {
+ const controller = new AbortController();
+ const aborted = whenAborted(controller.signal); aborted.catch(() => {});
+ const timer = setTimeout(() => controller.abort(stalled()), this.stallTimeoutMs); timer.unref?.();
+ const forward = () => controller.abort(parent.reason);
+ if (parent?.aborted) forward(); else parent?.addEventListener("abort", forward, { once: true });
+ try { return await Promise.race([run(controller.signal), aborted]); }
+ finally { clearTimeout(timer); parent?.removeEventListener("abort", forward); }
+ }
+
+ /** Checks the address and credentials and that the folder can be created. Does not change saved settings. */
+ async test(config, password) {
+ this.assertReady();
+ // An account switch during any await must not mix this test with another account's password.
+ const generation = this.generation; const record = this.record; const scope = this.scope;
+ const assertScope = () => { if (generation !== this.generation) throw backupError("backup_account_changed", "The backup account changed."); };
+ const normalized = normalizeOffsiteConfig({ ...config, enabled: false });
+ if (!normalized.url || !normalized.username) throw backupError("offsite_invalid_configuration", "Enter the WebDAV address and username.");
+ if (!(typeof password === "string" && password.length) && credentialKey(record.config) !== credentialKey(normalized)) {
+ throw backupError("offsite_password_required", "Enter the WebDAV password for this address and username.");
+ }
+ const secret = typeof password === "string" && password.length ? password : await this.password(record, scope);
+ assertScope();
+ try {
+ const client = await this.client(normalized, secret);
+ await this.request((signal) => client.createDirectory(normalized.folder, { recursive: true, signal }));
+ assertScope();
+ await this.request((signal) => client.stat(normalized.folder, { signal }));
+ assertScope();
+ return { ok: true };
+ } catch (error) {
+ if (error?.code === "backup_account_changed") throw error;
+ throw Object.assign(new Error(offsiteErrorInfo(error).message), offsiteErrorInfo(error));
+ }
+ }
+
+ /**
+ * Queue the latest completed local backup. Only the newest request is kept;
+ * an older archive is skipped once a newer one exists.
+ */
+ enqueue(entry, retention) {
+ if (!this.record?.config.enabled || !entry?.name) return;
+ this.queued = { entry, retention };
+ if (!this.upload) void this.drain();
+ }
+ /** Hourly check: retry the latest local archive if its copy failed or never ran. */
+ tick(latest, retention, { force = false } = {}) {
+ if (!this.record?.config.enabled || !latest || this.upload) return false;
+ const key = targetKey(this.record.config);
+ if (this.record.uploads.some((item) => item.name === latest.name && item.target === key)) return false;
+ if (!force && this.record.lastAttemptAt && Date.parse(this.record.lastAttemptAt) + RETRY_AFTER_MS > this.now()) return false;
+ this.enqueue(latest, retention); return true;
+ }
+ cancel() { this.upload?.controller.abort(); this.queued = null; }
+
+ async drain() {
+ while (this.queued && !this.upload) {
+ const { entry, retention } = this.queued; this.queued = null;
+ if (this.record?.config.enabled) await this.uploadEntry(entry, retention);
+ }
+ }
+
+ async uploadEntry(entry, retention) {
+ const generation = this.generation; const record = this.record; const scope = this.scope; const config = record.config; const key = targetKey(config);
+ const controller = new AbortController();
+ const current = () => generation === this.generation && !controller.signal.aborted;
+ const remoteFolder = posix.join(config.folder, this.backupSetId);
+ const finalPath = posix.join(remoteFolder, entry.name);
+ const partPath = `${finalPath}.${randomUUID()}.part`;
+ this.upload = { controller, name: entry.name, sent: 0, total: entry.size };
+ this.record.lastAttemptAt = new Date(this.now()).toISOString(); this.record.error = null;
+ await this.persist().catch(() => {}); this.emit();
+ let file; let client; let stall;
+ try {
+ const localPath = join(entry.directory, this.backupSetId, entry.name);
+ const info = await lstat(localPath).catch((error) => { if (error.code === "ENOENT") return null; throw error; });
+ // Local retention may already have replaced this archive with a newer one.
+ if (!info) return;
+ if (!info.isFile() || info.isSymbolicLink()) throw backupError("offsite_source_changed", "The local backup file was replaced. It was not uploaded.");
+ // Keep the file open so local retention can delete it without breaking the upload.
+ file = await open(localPath, "r");
+ const size = (await file.stat()).size;
+ if (size !== entry.size) throw backupError("offsite_source_changed", "The local backup file changed. It was not uploaded.");
+ client = await this.client(config, await this.password(record, scope));
+ if (!current()) return;
+ await this.request((signal) => client.createDirectory(remoteFolder, { recursive: true, signal }), controller.signal);
+ this.record.activePart = { path: partPath, target: key }; await this.persist();
+ const arm = () => { clearTimeout(stall); stall = setTimeout(() => controller.abort(backupError("offsite_stalled", "The WebDAV server stopped responding.")), this.stallTimeoutMs); stall.unref?.(); };
+ let emittedAt = 0;
+ // Count bytes as the request reads them. A "data" listener on the body
+ // would switch it to flowing mode and drop chunks read before the upload starts.
+ const body = new Transform({ transform: (chunk, _encoding, callback) => {
+ this.upload.sent += chunk.length; arm();
+ if (this.now() - emittedAt >= 1000) { emittedAt = this.now(); this.emit(); }
+ callback(null, chunk);
+ } });
+ arm();
+ const source = file.createReadStream({ autoClose: false });
+ source.on("error", (error) => body.destroy(error));
+ source.pipe(body);
+ // The library leaves streams chunked; many WebDAV servers and proxies need an explicit length.
+ await Promise.race([whenAborted(controller.signal), client.putFileContents(partPath, body, { headers: { "Content-Length": String(size) }, overwrite: true, signal: controller.signal })]);
+ clearTimeout(stall);
+ if (!current()) return;
+ await this.request((signal) => client.moveFile(partPath, finalPath, { overwrite: true, signal }), controller.signal);
+ delete this.record.activePart;
+ const remote = await this.request((signal) => client.stat(finalPath, { signal }), controller.signal);
+ if (remote?.size !== undefined && remote.size !== size) throw backupError("offsite_size_mismatch", "The uploaded copy has a different size. It will be uploaded again.");
+ if (!current()) return;
+ this.record.uploads = [...this.record.uploads.filter((item) => !(item.target === key && item.remotePath === finalPath)), { name: entry.name, remotePath: finalPath, target: key, size, uploadedAt: new Date(this.now()).toISOString() }];
+ this.record.lastSuccessAt = this.record.uploads.at(-1).uploadedAt; this.record.error = null;
+ await this.persist();
+ await this.applyRetention(client, key, retention, current);
+ } catch (error) {
+ if (generation !== this.generation) return;
+ const stalled = controller.signal.reason?.code === "offsite_stalled";
+ // A cancelled upload (settings changed) is not a failure.
+ this.record.error = controller.signal.aborted && !stalled ? null : offsiteErrorInfo(stalled ? controller.signal.reason : error);
+ if (client && this.record.activePart?.path === partPath) {
+ await this.request((signal) => client.deleteFile(partPath, { signal })).then(() => { delete this.record.activePart; }).catch(() => {});
+ }
+ await this.persist().catch(() => {});
+ } finally {
+ clearTimeout(stall);
+ await file?.close().catch(() => {});
+ if (this.upload?.controller === controller) this.upload = null;
+ if (generation === this.generation) this.emit();
+ }
+ }
+
+ async applyRetention(client, key, retention, current) {
+ const owned = this.record.uploads.filter((item) => item.target === key).sort((a, b) => b.uploadedAt.localeCompare(a.uploadedAt));
+ let failed = false;
+ for (const old of owned.slice(Math.max(1, retention))) {
+ if (!current()) return;
+ try { await this.request((signal) => client.deleteFile(old.remotePath, { signal })); }
+ catch (error) { if ((error?.status ?? error?.response?.status) !== 404) { failed = true; continue; } }
+ this.record.uploads = this.record.uploads.filter((item) => item !== old);
+ }
+ this.record.warning = failed ? { code: "offsite_cleanup_failed" } : null;
+ await this.persist();
+ }
+
+ async removeActivePart(generation) {
+ const part = this.record?.activePart;
+ if (!part || part.target !== targetKey(this.record.config)) { if (this.record) { delete this.record.activePart; await this.persist().catch(() => {}); } return; }
+ try {
+ const record = this.record; const scope = this.scope;
+ const client = await this.client(record.config, await this.password(record, scope));
+ if (generation !== this.generation) return;
+ await this.request((signal) => client.deleteFile(part.path, { signal })).catch((error) => { if ((error?.status ?? error?.response?.status) !== 404) throw error; });
+ if (generation === this.generation) { delete this.record.activePart; await this.persist(); }
+ } catch { /* Retried on the next start; a leftover .part never replaces a real copy. */ }
+ }
+}
diff --git a/apps/desktop/src/main/backup-offsite.test.mjs b/apps/desktop/src/main/backup-offsite.test.mjs
new file mode 100644
index 00000000..61b4ca06
--- /dev/null
+++ b/apps/desktop/src/main/backup-offsite.test.mjs
@@ -0,0 +1,351 @@
+import { describe, expect, test } from "bun:test";
+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { OffsiteBackup, normalizeOffsiteConfig, offsiteErrorInfo } from "./backup-offsite.mjs";
+
+const SET = "11111111-2222-3333-4444-555555555555";
+const secureStorage = (available = true) => ({
+ isEncryptionAvailable: () => available, isAsyncEncryptionAvailable: async () => available,
+ encryptStringAsync: async (s) => Buffer.from(`sealed:${s}`), decryptStringAsync: async (b) => ({ result: b.toString().slice(7), shouldReEncrypt: false }),
+});
+
+// In-memory WebDAV server with hooks to fail or hold individual calls.
+const fakeServer = () => {
+ const files = new Map(); const calls = []; const hooks = {};
+ const fail = (status) => Object.assign(new Error(`HTTP ${status}`), { status });
+ const run = async (name, ...args) => { calls.push([name, args[0]]); if (hooks[name]) await hooks[name](...args); };
+ const client = {
+ createDirectory: async (path, options) => run("createDirectory", path, options),
+ stat: async (path, options) => { await run("stat", path, options); if (path.endsWith("/backups") || !path.includes(".")) return { type: "directory" }; if (!files.has(path)) throw fail(404); return { size: files.get(path).length }; },
+ putFileContents: async (path, stream, options) => {
+ calls.push(["putFileContents:options", path, options]);
+ await run("putFileContents", path, options);
+ const chunks = []; for await (const chunk of stream) { if (options.signal?.aborted) throw options.signal.reason ?? new Error("aborted"); chunks.push(chunk); }
+ files.set(path, Buffer.concat(chunks));
+ },
+ moveFile: async (from, to, options) => { await run("moveFile", from, to, options); files.set(to, files.get(from)); files.delete(from); },
+ deleteFile: async (path) => { await run("deleteFile", path); if (!files.has(path)) throw fail(404); files.delete(path); },
+ };
+ return { files, calls, hooks, client, fail, factory: async (url, options) => { calls.push(["connect", url, options.username, options.password]); return client; } };
+};
+
+const setup = async ({ secure = true } = {}) => {
+ const root = await mkdtemp(join(tmpdir(), "edgeever-offsite-"));
+ const userData = join(root, "private"); const backups = join(root, "backups");
+ await mkdir(join(userData, "scheduled-backups"), { recursive: true }); await mkdir(join(backups, SET), { recursive: true });
+ const server = fakeServer(); const changes = []; let clock = Date.parse("2026-10-29T10:00:00Z");
+ const offsite = new OffsiteBackup({ userData, secureStorage: secureStorage(secure), clientFactory: server.factory, onChange: (status) => changes.push(status), now: () => clock, stallTimeoutMs: 50 });
+ await offsite.setScope("scope-a", SET);
+ const archive = async (name, body = "archive") => { await writeFile(join(backups, SET, name), body); return { name, directory: backups, size: Buffer.byteLength(body), completedAt: new Date(clock).toISOString() }; };
+ const enable = () => offsite.save({ enabled: true, url: "https://dav.example.com/remote.php/dav/files/me/", username: "me", folder: "/EdgeEver/backups" }, "app-password");
+ const settle = async () => { for (let i = 0; i < 50 && (offsite.upload || offsite.queued); i += 1) await new Promise((r) => setTimeout(r, 5)); };
+ return { root, userData, backups, offsite, server, changes, archive, enable, settle, advance: (ms) => { clock += ms; }, cleanup: () => rm(root, { recursive: true, force: true }) };
+};
+
+describe("off-site settings", () => {
+ test("requires https except on a local network and rejects unsafe folders", () => {
+ expect(normalizeOffsiteConfig(undefined)).toEqual({ enabled: false, url: "", username: "", folder: "/EdgeEver/backups" });
+ expect(normalizeOffsiteConfig({ enabled: true, url: " https://dav.example.com/dav/ ", username: " me ", folder: "Backups//EdgeEver/" })).toEqual({ enabled: true, url: "https://dav.example.com/dav", username: "me", folder: "/Backups/EdgeEver" });
+ for (const url of ["http://nas.local:5005", "http://192.168.1.10/dav", "http://nas/dav", "http://[fd00::1]/dav", "http://localhost:8080"]) {
+ expect(normalizeOffsiteConfig({ enabled: true, url, username: "u", folder: "/" }).url).toBe(new URL(url).href.replace(/\/+$/, ""));
+ }
+ const code = (input) => { try { normalizeOffsiteConfig(input); return null; } catch (error) { return error.code; } };
+ expect(code({ enabled: true, url: "http://dav.example.com", username: "u", folder: "/" })).toBe("offsite_insecure_url");
+ expect(code({ enabled: true, url: "https://u:[email protected]", username: "u", folder: "/" })).toBe("offsite_invalid_url");
+ expect(code({ enabled: true, url: "ftp://dav.example.com", username: "u", folder: "/" })).toBe("offsite_insecure_url");
+ expect(code({ enabled: true, url: "https://dav.example.com", username: "u", folder: "/a/../b" })).toBe("offsite_invalid_folder");
+ expect(code({ enabled: true, url: "", username: "u", folder: "/" })).toBe("offsite_invalid_configuration");
+ });
+
+ test("stores the password only through secure storage and never in the state file", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ const state = await readFile(join(f.userData, "scheduled-backups", "scope-a.offsite.json"), "utf8");
+ expect(state).not.toContain("app-password");
+ expect(JSON.stringify(f.offsite.status())).not.toContain("app-password");
+ expect(f.offsite.status().passwordSet).toBe(true);
+ // Saving again without a password keeps the stored one.
+ await f.offsite.save({ ...f.offsite.status().config, folder: "/Other" });
+ expect(f.offsite.status().passwordSet).toBe(true);
+ } finally { await f.cleanup(); }
+ });
+
+ test("never sends the saved password to a different address or username", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ const saved = f.offsite.status().config;
+ const secrets = async () => (await readdir(join(f.userData, "scheduled-backups"))).filter((name) => name.endsWith(".secret"));
+ expect(await secrets()).toHaveLength(1);
+ // Testing another server without typing a password does not use the saved one.
+ for (const changed of [{ url: "https://attacker.example.com/dav" }, { username: "someone-else" }]) {
+ await expect(f.offsite.test({ ...saved, ...changed })).rejects.toMatchObject({ code: "offsite_password_required" });
+ }
+ expect(f.server.calls.some(([name]) => name === "connect")).toBe(false);
+ // Saving a new address without a password is refused while enabled, and forgets the password when disabled.
+ await expect(f.offsite.save({ ...saved, url: "https://attacker.example.com/dav" })).rejects.toMatchObject({ code: "offsite_password_required" });
+ expect(f.offsite.status()).toMatchObject({ config: saved, passwordSet: true });
+ await f.offsite.save({ ...saved, enabled: false, url: "https://attacker.example.com/dav" });
+ expect(f.offsite.status().passwordSet).toBe(false);
+ expect(await secrets()).toHaveLength(0);
+ // The same address keeps working with its saved password.
+ await f.enable();
+ expect(await f.offsite.test(f.offsite.status().config)).toEqual({ ok: true });
+ expect(f.server.calls.find(([name]) => name === "connect").slice(1)).toEqual(["https://dav.example.com/remote.php/dav/files/me", "me", "app-password"]);
+ } finally { await f.cleanup(); }
+ });
+
+ test("refuses to save a password without usable secure storage", async () => {
+ const f = await setup({ secure: false });
+ try {
+ await expect(f.enable()).rejects.toMatchObject({ code: "offsite_secure_storage_unavailable" });
+ expect(f.offsite.status().config.enabled).toBe(false);
+ } finally { await f.cleanup(); }
+ });
+
+ test("maps server answers to actionable errors", () => {
+ expect(offsiteErrorInfo({ status: 401 }).code).toBe("offsite_auth_failed");
+ expect(offsiteErrorInfo({ response: { status: 413 } }).code).toBe("offsite_file_too_large");
+ expect(offsiteErrorInfo({ status: 507 }).code).toBe("offsite_storage_full");
+ expect(offsiteErrorInfo({ cause: { code: "ENOTFOUND" } }).code).toBe("offsite_unreachable");
+ expect(offsiteErrorInfo(new Error("x")).code).toBe("offsite_upload_failed");
+ });
+});
+
+describe("off-site upload", () => {
+ test("uploads to a .part file, moves it into place and checks the size", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.offsite.enqueue(await f.archive("one.zip", "hello archive"), 3); await f.settle();
+ const final = `/EdgeEver/backups/${SET}/one.zip`;
+ expect(f.server.files.get(final)?.toString()).toBe("hello archive");
+ const put = f.server.calls.find(([name]) => name === "putFileContents");
+ expect(put[1]).toMatch(new RegExp(`^/EdgeEver/backups/${SET}/one\\.zip\\.[a-f0-9-]+\\.part$`));
+ // Streams are sent with an explicit length; some servers reject chunked uploads.
+ expect(f.server.calls.find(([name]) => name === "putFileContents:options")[2].headers).toEqual({ "Content-Length": "13" });
+ expect([...f.server.files.keys()].some((path) => path.endsWith(".part"))).toBe(false);
+ expect(f.server.calls.find(([name]) => name === "connect").slice(2)).toEqual(["me", "app-password"]);
+ const status = f.offsite.status();
+ expect(status.lastUploaded).toMatchObject({ name: "one.zip", size: 13 });
+ expect(status.error).toBeNull(); expect(status.task).toBeNull();
+ } finally { await f.cleanup(); }
+ });
+
+ test("a failed upload removes the .part file, records the error and keeps nothing as uploaded", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.server.hooks.moveFile = async () => { throw f.server.fail(507); };
+ f.offsite.enqueue(await f.archive("one.zip"), 3); await f.settle();
+ expect([...f.server.files.keys()]).toEqual([]);
+ expect(f.offsite.status().error.code).toBe("offsite_storage_full");
+ expect(f.offsite.status().lastSuccessAt).toBeNull();
+ } finally { await f.cleanup(); }
+ });
+
+ test("a size mismatch after the move is reported and the archive is retried later", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ const entry = await f.archive("one.zip", "12345");
+ f.server.hooks.moveFile = async (from) => { f.server.files.set(from, Buffer.from("123")); };
+ f.offsite.enqueue(entry, 3); await f.settle();
+ expect(f.offsite.status().error.code).toBe("offsite_size_mismatch");
+ delete f.server.hooks.moveFile;
+ // Hourly retry waits for an hour after the failed attempt.
+ expect(f.offsite.tick(entry, 3)).toBe(false);
+ f.advance(3600001);
+ expect(f.offsite.tick(entry, 3)).toBe(true); await f.settle();
+ expect(f.offsite.status().error).toBeNull();
+ expect(f.offsite.tick(entry, 3, { force: true })).toBe(false);
+ } finally { await f.cleanup(); }
+ });
+
+ test("a stalled server is aborted and reported", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.server.hooks.putFileContents = (_path, options) => new Promise((_resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason)));
+ f.offsite.enqueue(await f.archive("one.zip"), 3);
+ for (let i = 0; i < 100 && f.offsite.upload; i += 1) await new Promise((r) => setTimeout(r, 10));
+ expect(f.offsite.status().error.code).toBe("offsite_stalled");
+ } finally { await f.cleanup(); }
+ });
+
+ test("switching account cancels the running upload without touching the new account", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ let release;
+ f.server.hooks.putFileContents = () => new Promise((resolve) => { release = resolve; });
+ f.offsite.enqueue(await f.archive("one.zip"), 3);
+ for (let i = 0; i < 50 && !release; i += 1) await new Promise((r) => setTimeout(r, 5));
+ await f.offsite.setScope("scope-b", SET);
+ release();
+ await new Promise((r) => setTimeout(r, 30));
+ expect(f.offsite.status()).toMatchObject({ config: { enabled: false }, error: null, lastUploaded: null, task: null });
+ expect(f.offsite.upload).toBeNull();
+ expect([...f.server.files.keys()].filter((path) => path.endsWith("one.zip"))).toEqual([]);
+ } finally { await f.cleanup(); }
+ });
+
+ test("retention deletes only copies this device uploaded, after a newer upload succeeded", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.server.files.set(`/EdgeEver/backups/${SET}/manual.zip`, Buffer.from("keep"));
+ for (const name of ["a.zip", "b.zip", "c.zip"]) { f.offsite.enqueue(await f.archive(name), 2); await f.settle(); f.advance(1000); }
+ const remaining = [...f.server.files.keys()].sort();
+ expect(remaining).toEqual([`/EdgeEver/backups/${SET}/b.zip`, `/EdgeEver/backups/${SET}/c.zip`, `/EdgeEver/backups/${SET}/manual.zip`]);
+ // A failed upload never deletes the older copies.
+ f.server.hooks.putFileContents = async () => { throw f.server.fail(500); };
+ f.offsite.enqueue(await f.archive("d.zip"), 1); await f.settle();
+ expect([...f.server.files.keys()]).toHaveLength(3);
+ // Copies under another address or folder are never deleted.
+ delete f.server.hooks.putFileContents;
+ await f.offsite.save({ ...f.offsite.status().config, folder: "/Elsewhere" });
+ f.offsite.enqueue(await f.archive("e.zip"), 1); await f.settle();
+ expect(f.server.files.has(`/EdgeEver/backups/${SET}/c.zip`)).toBe(true);
+ expect(f.server.files.has(`/Elsewhere/${SET}/e.zip`)).toBe(true);
+ } finally { await f.cleanup(); }
+ });
+
+ test("a cleanup failure is a warning and does not fail the upload", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.offsite.enqueue(await f.archive("a.zip"), 1); await f.settle(); f.advance(1000);
+ f.server.hooks.deleteFile = async () => { throw f.server.fail(403); };
+ f.offsite.enqueue(await f.archive("b.zip"), 1); await f.settle();
+ expect(f.offsite.status()).toMatchObject({ error: null, warning: { code: "offsite_cleanup_failed" }, lastUploaded: { name: "b.zip" } });
+ } finally { await f.cleanup(); }
+ });
+
+ test("skips archives that local retention already removed or that changed size", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.offsite.enqueue({ name: "gone.zip", directory: f.backups, size: 3 }, 3); await f.settle();
+ expect(f.server.calls.some(([name]) => name === "putFileContents")).toBe(false);
+ expect(f.offsite.status().error).toBeNull();
+ const entry = await f.archive("changed.zip", "abc");
+ f.offsite.enqueue({ ...entry, size: 99 }, 3); await f.settle();
+ expect(f.offsite.status().error.code).toBe("offsite_source_changed");
+ } finally { await f.cleanup(); }
+ });
+
+ test("does nothing while the option is off", async () => {
+ const f = await setup();
+ try {
+ f.offsite.enqueue(await f.archive("one.zip"), 3); await f.settle();
+ expect(f.server.calls).toEqual([]);
+ expect(f.offsite.tick({ name: "one.zip", directory: f.backups, size: 7 }, 3, { force: true })).toBe(false);
+ } finally { await f.cleanup(); }
+ });
+
+ test("test connection uses the entered password without saving it", async () => {
+ const f = await setup();
+ try {
+ await expect(f.offsite.test({ url: "https://dav.example.com/dav", username: "me", folder: "/EdgeEver/backups" }, "typed")).resolves.toEqual({ ok: true });
+ expect(f.server.calls[0]).toEqual(["connect", "https://dav.example.com/dav", "me", "typed"]);
+ expect(f.offsite.status().passwordSet).toBe(false);
+ f.server.hooks.createDirectory = async () => { throw f.server.fail(401); };
+ await expect(f.offsite.test({ url: "https://dav.example.com/dav", username: "me", folder: "/x" }, "wrong")).rejects.toMatchObject({ code: "offsite_auth_failed" });
+ } finally { await f.cleanup(); }
+ });
+
+ test("removes a .part left by an interrupted upload on the next start", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ const part = `/EdgeEver/backups/${SET}/one.zip.abc.part`;
+ f.server.files.set(part, Buffer.from("partial"));
+ f.offsite.record.activePart = { path: part, target: JSON.stringify(["https://dav.example.com/remote.php/dav/files/me", "me", "/EdgeEver/backups"]) };
+ await f.offsite.persist();
+ await f.offsite.setScope("scope-a", SET);
+ for (let i = 0; i < 50 && f.server.files.has(part); i += 1) await new Promise((r) => setTimeout(r, 5));
+ expect(f.server.files.has(part)).toBe(false);
+ } finally { await f.cleanup(); }
+ });
+});
+
+describe("review regressions", () => {
+ test("a connection test keeps the password of the account it started in", async () => {
+ const f = await setup();
+ try {
+ // Account A saves its password; account B saves a different one.
+ await f.enable();
+ await f.offsite.setScope("scope-b", SET);
+ await f.offsite.save({ enabled: true, url: "https://dav.example.com/remote.php/dav/files/me/", username: "me", folder: "/EdgeEver/backups" }, "password-of-b");
+ await f.offsite.setScope("scope-a", SET);
+ // Hold decryption so the account can switch while the test reads A's password.
+ let release; const storage = f.offsite.secureStorage; const decrypt = storage.decryptStringAsync;
+ storage.decryptStringAsync = async (bytes) => { await new Promise((resolve) => { release = resolve; }); return decrypt(bytes); };
+ const pending = f.offsite.test(f.offsite.status().config);
+ for (let i = 0; i < 50 && !release; i += 1) await new Promise((r) => setTimeout(r, 5));
+ await f.offsite.setScope("scope-b", SET);
+ release();
+ await expect(pending).rejects.toMatchObject({ code: "backup_account_changed" });
+ storage.decryptStringAsync = decrypt;
+ // No request went out, and B's password was never read for A's test.
+ expect(f.server.calls.filter(([name]) => name === "connect")).toEqual([]);
+ } finally { await f.cleanup(); }
+ });
+
+ test("turning the copy off stops a running upload before it publishes", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ let started = false;
+ f.server.hooks.putFileContents = (_path, options) => { started = true; return new Promise((_resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason))); };
+ f.offsite.enqueue(await f.archive("one.zip"), 3);
+ for (let i = 0; i < 50 && !started; i += 1) await new Promise((r) => setTimeout(r, 5));
+ await f.offsite.save({ ...f.offsite.status().config, enabled: false });
+ await f.settle();
+ expect(f.offsite.upload).toBeNull();
+ expect(f.server.calls.some(([name]) => name === "moveFile")).toBe(false);
+ expect([...f.server.files.keys()].filter((path) => path.endsWith("one.zip"))).toEqual([]);
+ expect(f.offsite.status()).toMatchObject({ config: { enabled: false }, error: null, lastUploaded: null });
+ // A copy queued while the option was off never starts.
+ delete f.server.hooks.putFileContents;
+ f.offsite.enqueue(await f.archive("two.zip"), 3); await f.settle();
+ expect(f.server.calls.filter(([name]) => name === "putFileContents")).toHaveLength(1);
+ } finally { await f.cleanup(); }
+ });
+
+ for (const name of ["createDirectory", "moveFile", "stat"]) {
+ test(`a stuck ${name} request is bounded and later copies still run`, async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ // The request never settles and ignores its signal.
+ f.server.hooks[name] = () => new Promise(() => {});
+ f.offsite.enqueue(await f.archive("one.zip"), 3);
+ for (let i = 0; i < 100 && (f.offsite.upload || f.offsite.queued); i += 1) await new Promise((r) => setTimeout(r, 10));
+ expect(f.offsite.upload).toBeNull();
+ expect(f.offsite.status().error.code).toBe("offsite_stalled");
+ delete f.server.hooks[name];
+ f.offsite.enqueue(await f.archive("two.zip"), 3); await f.settle();
+ expect(f.offsite.status()).toMatchObject({ error: null, lastUploaded: { name: "two.zip" } });
+ } finally { await f.cleanup(); }
+ });
+ }
+
+ test("stuck cleanup and connection-test requests are bounded too", async () => {
+ const f = await setup();
+ try {
+ await f.enable();
+ f.server.hooks.moveFile = async () => { throw f.server.fail(500); };
+ f.server.hooks.deleteFile = () => new Promise(() => {});
+ f.offsite.enqueue(await f.archive("one.zip"), 3);
+ for (let i = 0; i < 100 && f.offsite.upload; i += 1) await new Promise((r) => setTimeout(r, 10));
+ expect(f.offsite.upload).toBeNull();
+ expect(f.offsite.status().error.code).toBe("offsite_upload_failed");
+ f.server.hooks.stat = () => new Promise(() => {});
+ await expect(f.offsite.test(f.offsite.status().config)).rejects.toMatchObject({ code: "offsite_stalled" });
+ } finally { await f.cleanup(); }
+ });
+});
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 468b9216..e21f9434 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -8,6 +8,7 @@ import { backgroundNodeExecutable } from "./background-node.mjs";
import { fileURLToPath, pathToFileURL } from "node:url";
import { release as operatingSystemRelease } from "node:os";
import { BackupManager } from "./backup-manager.mjs";
+import { OffsiteBackup } from "./backup-offsite.mjs";
import { createBackupWorkerFactory } from "./backup-worker.mjs";
import { registerBackupIpc } from "./backup-ipc.mjs";
import { SidecarRpcClient } from "./rpc.mjs";
@@ -1934,6 +1935,7 @@ const startApplication = async () => {
});
backupManager = new BackupManager({
userData: app.getPath("userData"), defaultDirectory: join(app.getPath("documents"), "EdgeEver Backups"), secureStorage: safeStorage,
+ offsite: new OffsiteBackup({ userData: app.getPath("userData"), secureStorage: safeStorage }),
workerFactory: createBackupWorkerFactory({ utilityProcess, session: session.defaultSession }),
version: { edgeeverVersion: app.getVersion(), buildId: app.getVersion() },
onChange: (status) => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send("desktop:backup-status", status); },
diff --git a/apps/web/src/components/settings/DesktopOffsiteBackup.tsx b/apps/web/src/components/settings/DesktopOffsiteBackup.tsx
new file mode 100644
index 00000000..85fe7476
--- /dev/null
+++ b/apps/web/src/components/settings/DesktopOffsiteBackup.tsx
@@ -0,0 +1,108 @@
+import { useEffect, useRef, useState } from "react";
+import { ChevronRight, CloudUpload, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { DesktopBackupStatus, DesktopOffsiteConfig } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import { describeDesktopBackupError } from "@/lib/desktop-backup";
+import { formatBytes } from "@/lib/format-bytes";
+
+const DEFAULT_FOLDER = "/EdgeEver/backups";
+const emptyConfig: DesktopOffsiteConfig = { enabled: false, url: "", username: "", folder: DEFAULT_FOLDER };
+
+/** Status lines for the WebDAV copy, shown inside the backup status box. */
+export const DesktopOffsiteStatusLines = ({ status, disabled, onUpload }: {
+ status: DesktopBackupStatus;
+ disabled: boolean;
+ onUpload: () => void;
+}) => {
+ const { t } = useTranslation();
+ const offsite = status.offsite;
+ if (!offsite?.config.enabled) return null;
+ const date = (value: string | null) => value ? new Date(value).toLocaleString() : t("desktopBackup.never");
+ return <div className="grid gap-1.5 border-t border-slate-200/70 pt-1.5" data-offsite-status>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="font-medium text-slate-800">{t("desktopBackup.offsite.lastSuccess", { time: date(offsite.lastSuccessAt) })}</p>
+ {!offsite.task && status.history.length ? <Button type="button" size="sm" variant="ghost" className="h-6 px-2 text-xs font-normal" disabled={disabled} onClick={onUpload}><CloudUpload className="h-3.5 w-3.5" />{t("desktopBackup.offsite.uploadNow")}</Button> : null}
+ </div>
+ {offsite.task ? <p className="flex items-center gap-2"><Loader2 className="h-3.5 w-3.5 animate-spin" />{t("desktopBackup.offsite.uploading", { name: offsite.task.name, sent: formatBytes(offsite.task.sent), total: formatBytes(offsite.task.total) })}</p> : offsite.lastUploaded ? <p className="break-all text-muted-foreground">{t("desktopBackup.offsite.lastUploaded", { name: offsite.lastUploaded.name, size: formatBytes(offsite.lastUploaded.size) })}</p> : null}
+ {offsite.error ? <p className="break-words text-destructive" role="alert">{t("desktopBackup.offsite.failed", { message: describeDesktopBackupError(t, offsite.error) })}</p> : null}
+ {offsite.warning ? <p className="text-amber-700">{describeDesktopBackupError(t, offsite.warning)}</p> : null}
+ </div>;
+};
+
+/** Collapsible WebDAV settings. Saved explicitly because the fields only make sense together. */
+export const DesktopOffsiteSettings = ({ status, disabled }: { status: DesktopBackupStatus; disabled: boolean }) => {
+ const { t } = useTranslation();
+ const bridge = window.edgeeverDesktop;
+ const saved = status.offsite?.config ?? emptyConfig;
+ const savedKey = JSON.stringify(saved);
+ const [config, setConfig] = useState<DesktopOffsiteConfig>(saved);
+ const [password, setPassword] = useState("");
+ const [changePassword, setChangePassword] = useState(false);
+ const [working, setWorking] = useState<"save" | "test" | null>(null);
+ const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
+ const scope = useRef(status.backupSetId);
+ useEffect(() => {
+ setConfig(JSON.parse(savedKey) as DesktopOffsiteConfig);
+ setPassword(""); setChangePassword(false);
+ }, [savedKey, status.backupSetId]);
+ useEffect(() => { scope.current = status.backupSetId; setMessage(null); setWorking(null); }, [status.backupSetId]);
+ if (!bridge?.backup || status.offsite === undefined) return null;
+ const offsite = status.offsite;
+ // The saved password only applies to the address and username it was entered for.
+ const credentialsChanged = config.url.trim().replace(/\/+$/, "") !== saved.url || config.username.trim() !== saved.username;
+ const passwordSet = Boolean(offsite?.passwordSet) && !credentialsChanged;
+ const secureUnavailable = offsite ? !offsite.secureStorageAvailable : false;
+ const passwordEditable = !passwordSet || changePassword;
+ const dirty = JSON.stringify(config) !== savedKey || Boolean(password);
+ const complete = Boolean(config.url.trim() && config.username.trim() && (password || passwordSet));
+ const run = async (kind: "save" | "test") => {
+ const expected = status.backupSetId;
+ setWorking(kind); setMessage(null);
+ try {
+ const input = { backupSetId: expected, config, ...(password ? { password } : {}) };
+ if (kind === "test") {
+ await bridge.backup("offsite-test", input);
+ if (scope.current === expected) setMessage({ tone: "success", text: t("desktopBackup.offsite.testComplete") });
+ } else {
+ await bridge.backup("offsite-save", input);
+ if (scope.current === expected) { setPassword(""); setChangePassword(false); setMessage({ tone: "success", text: t("desktopBackup.offsite.saved") }); }
+ }
+ } catch (failure) {
+ if (scope.current === expected) setMessage({ tone: "error", text: describeDesktopBackupError(t, failure) });
+ } finally { if (scope.current === expected) setWorking(null); }
+ };
+ const field = "grid gap-1.5 text-xs font-medium text-slate-700";
+ return <details className="group border-t pt-3" data-offsite-settings>
+ <summary className="flex cursor-pointer items-center gap-1.5 text-xs font-medium text-slate-700 select-none transition-colors hover:text-slate-900 list-none [&::-webkit-details-marker]:hidden">
+ <ChevronRight className="h-3.5 w-3.5 text-slate-400 transition-transform duration-200 group-open:rotate-90" />
+ <span>{t("desktopBackup.offsite.title")}</span>
+ </summary>
+ <form className="mt-3.5 grid gap-3.5" onSubmit={(event) => { event.preventDefault(); if (!working && (!config.enabled || complete)) void run("save"); }}>
+ <p className="text-xs leading-5 text-muted-foreground">{t("desktopBackup.offsite.description")}</p>
+ <fieldset disabled={disabled || Boolean(working)} className="grid min-w-0 gap-3.5 disabled:opacity-60">
+ <label className="flex items-center justify-between gap-3 text-xs font-medium text-slate-700">
+ <span>{t("desktopBackup.offsite.enable")}</span>
+ <Switch checked={config.enabled} onCheckedChange={(enabled) => setConfig({ ...config, enabled })} />
+ </label>
+ <label className={field}><span>{t("desktopBackup.offsite.url")}</span><Input className="h-8 text-xs" type="url" inputMode="url" autoComplete="off" spellCheck={false} placeholder="https://dav.example.com/remote.php/dav/files/me" value={config.url} onChange={(event) => setConfig({ ...config, url: event.target.value })} /></label>
+ <div className="grid gap-3.5 sm:grid-cols-2">
+ <label className={field}><span>{t("desktopBackup.offsite.username")}</span><Input className="h-8 text-xs" autoComplete="username" spellCheck={false} value={config.username} onChange={(event) => setConfig({ ...config, username: event.target.value })} /></label>
+ <label className={field}><span>{t("desktopBackup.offsite.folder")}</span><Input className="h-8 font-mono text-xs" spellCheck={false} placeholder={DEFAULT_FOLDER} value={config.folder} onChange={(event) => setConfig({ ...config, folder: event.target.value })} /></label>
+ </div>
+ {passwordEditable
+ ? <label className={field}><span>{t("desktopBackup.offsite.password")}</span><Input className="h-8 text-xs" type="password" autoComplete="new-password" value={password} onChange={(event) => setPassword(event.target.value)} /><span className="font-normal text-muted-foreground">{t("desktopBackup.offsite.passwordHint")}</span></label>
+ : <div className="flex items-center justify-between gap-2 text-xs"><span className="text-muted-foreground">{t("desktopBackup.offsite.passwordSet")}</span><Button type="button" variant="ghost" size="sm" className="h-7 text-xs font-normal" onClick={() => setChangePassword(true)}>{t("desktopBackup.changePassword")}</Button></div>}
+ {secureUnavailable ? <p className="text-xs text-amber-700">{t("desktopBackup.offsite.secureUnavailable")}</p> : null}
+ {config.url.trim().startsWith("http://") ? <p className="text-xs text-muted-foreground">{t("desktopBackup.offsite.httpLocalOnly")}</p> : null}
+ </fieldset>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button type="submit" size="sm" className="bg-foreground text-background hover:bg-foreground/90" disabled={disabled || Boolean(working) || !dirty || (config.enabled && !complete)}>{working === "save" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}{t("desktopBackup.offsite.save")}</Button>
+ <Button type="button" size="sm" variant="outline" disabled={disabled || Boolean(working) || !complete} onClick={() => void run("test")}>{working === "test" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}{t("desktopBackup.offsite.test")}</Button>
+ </div>
+ {message ? <p className={message.tone === "error" ? "break-words text-xs text-destructive" : "text-xs text-emerald-700"} role={message.tone === "error" ? "alert" : "status"}>{message.text}</p> : null}
+ </form>
+ </details>;
+};
diff --git a/apps/web/src/components/settings/DesktopScheduledBackupCard.tsx b/apps/web/src/components/settings/DesktopScheduledBackupCard.tsx
index de76a435..e24cf947 100644
--- a/apps/web/src/components/settings/DesktopScheduledBackupCard.tsx
+++ b/apps/web/src/components/settings/DesktopScheduledBackupCard.tsx
@@ -11,6 +11,7 @@ import { describeDesktopBackupError, useDesktopBackup } from "@/lib/desktop-back
import { formatBytes } from "@/lib/format-bytes";
import { DesktopBackupImport } from "./DesktopBackupImport";
import { DesktopBackupRunDialog } from "./DesktopBackupRunDialog";
+import { DesktopOffsiteSettings, DesktopOffsiteStatusLines } from "./DesktopOffsiteBackup";
import { SETTINGS_CARD_DESCRIPTION_CLASSNAME, SETTINGS_CARD_HEADER_CLASSNAME, SETTINGS_CARD_ICON_CLASSNAME, SETTINGS_CARD_TITLE_CLASSNAME } from "./settings-ui";
const defaultBackupName = () => {
@@ -123,6 +124,7 @@ export const DesktopScheduledBackupCard = () => {
<p className={dirty ? "text-amber-700" : "text-muted-foreground"}>{dirty ? t(saving ? "desktopBackup.savingSettings" : "desktopBackup.completePassword") : status.config.enabled ? t("desktopBackup.nextDue", { time: status.nextDueAt ? date(status.nextDueAt) : t("desktopBackup.whenReady") }) : t("desktopBackup.autoOff")}</p>
{error || status.error ? <p className="break-words text-destructive" role="alert">{error ?? describeDesktopBackupError(t, status.error)}</p> : null}
{status.warning ? <p className="text-amber-700">{describeDesktopBackupError(t, status.warning)}</p> : null}
+ <DesktopOffsiteStatusLines status={status} disabled={saving} onUpload={() => void attempt(() => bridge.backup("offsite-upload", { backupSetId: status.backupSetId }))} />
</div>
<details className="group border-t pt-3">
<summary className="flex cursor-pointer items-center gap-1.5 text-xs font-medium text-slate-700 select-none transition-colors hover:text-slate-900 list-none [&::-webkit-details-marker]:hidden">
@@ -171,6 +173,7 @@ export const DesktopScheduledBackupCard = () => {
{dirty || saving ? <p className="text-xs text-muted-foreground" role="status">{t(saving ? "desktopBackup.savingSettings" : "desktopBackup.completePassword")}</p> : null}
</div>
</details>
+ <DesktopOffsiteSettings status={status} disabled={saving} />
<section className="grid gap-2.5 border-t pt-3" aria-label={t("desktopBackup.history", { count: status.history.length })}>
<h3 className="text-xs font-medium text-slate-700">{t("desktopBackup.history", { count: status.history.length })}</h3>
{status.history.length ? <ul className="divide-y divide-slate-100">{[...status.history].reverse().map((item) => <li key={item.name} className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 py-2.5 first:pt-0 last:pb-0">
diff --git a/bun.lock b/bun.lock
index 179e40b1..d77a31d2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -116,6 +116,7 @@
"electron-updater": "^6.6.2",
"fflate": "0.8.3",
"npm": "11.21.0",
+ "webdav": "^5.10.0",
"zod": "4.6.6",
},
"devDependencies": {
diff --git a/docs/changes/2026-11-02-desktop-webdav-offsite.md b/docs/changes/2026-11-02-desktop-webdav-offsite.md
new file mode 100644
index 00000000..259310d1
--- /dev/null
+++ b/docs/changes/2026-11-02-desktop-webdav-offsite.md
@@ -0,0 +1,34 @@
+# Desktop scheduled backups: optional WebDAV off-site copy
+
+[简体中文](2026-11-02-desktop-webdav-offsite.zh-CN.md)
+
+Related Issue: #723 (P2 of the backup plan; continues #61 and #650)
+
+## Problem and outcome
+
+Desktop scheduled backups are written to a local folder only. Users without a cloud-drive client, or who keep backups on a NAS or a WebDAV provider, had no automatic off-site copy. After each completed local backup, the desktop app can now copy the archive to a WebDAV server (Nextcloud, Synology/QNAP, Hetzner Storage Box, Koofr, pCloud, 坚果云, Alist and similar). The design is in [section 12 of the scheduled backup design](../desktop-scheduled-backup-design.md).
+
+## Scope
+
+- Desktop main process: new `backup-offsite.mjs`; `backup-manager.mjs` reports off-site status, queues an upload after publication, retries from the hourly check and cancels on account changes; three IPC actions (`offsite-save`, `offsite-test`, `offsite-upload`); `webdav` added to the desktop app dependencies because the main process is not bundled.
+- Settings → Import and export → Backup and restore: a collapsible “Off-site copy (WebDAV)” section and a separate status line with **Upload now**.
+- Shared IPC types and translations for all five catalogs.
+- Unchanged: archive format, local backup results, API, Cloudflare/Docker runtimes, database and migrations, sync, Web WebDAV card.
+
+## Risks and recovery
+
+- **Password disclosure.** Stored only through Electron `safeStorage` in a scope-bound `.secret` file; never in state, renderer status, logs, the archive or the EdgeEver server. No plaintext fallback. The saved password is bound to the address and username, so changing either, or testing another server, requires entering it again. `https://` is required except for local-network hosts.
+- **Deleting a good remote copy.** Remote retention deletes only files this backup set recorded as uploaded to the same target, only after a newer copy succeeded.
+- **Blocking local backups.** Uploads run outside the local backup queue and never change its result.
+- **Rollback.** Turning the option off stops uploads and keeps local and remote files. Older versions ignore `<scope>.offsite.json` and the off-site `.secret` file (verified below).
+
+## Verification
+
+- Unit tests (`backup-offsite.test.mjs`, 15 tests, mocked WebDAV): upload through `.part` and move, size check, `.part` cleanup, cancellation, account switch mid-upload, stall timeout, retention ownership, retry of the latest archive, password handling, explicit `Content-Length`.
+- Integration (`bun run test:webdav`, real `rclone serve webdav` 1.69, under Bun and Node): test connection with right and wrong password, plain and encrypted archives byte-for-byte without leftover `.part`, retention that keeps foreign files, wrong saved password, HTTP 413 size limit reported as “file too large” with no `.part`, unreachable server. Docker Desktop was unavailable locally, so rclone ran directly and the size limit was emulated with a 64 KiB proxy instead of the nginx container from `tests/webdav/compose.yml`.
+- Desktop app on macOS (Electron, unpackaged, local self-hosted server): connection test; plain backup copied, downloaded back from WebDAV and restored after the note was deleted; encrypted backup copied as-is (`EDGB` header, no plaintext) and restored with its password; a wrong WebDAV password fails only the copy while the local backup succeeds, and **Upload now** recovers it; the password is absent from status and every state file; settings UI renders the section and status line.
+- Upgrade: a profile created by the current `main` build with an encrypted local backup opened in the new build with settings, password and history intact; the off-site option started off and, once enabled, uploaded the backup made by the old build. Opening that profile again with the old build ran a new local backup normally.
+- Found and fixed during verification: progress counting on the request body dropped the first chunks of larger files, and the `webdav` library sends streams chunked, which some servers reject; uploads now count bytes in a transform and send an explicit `Content-Length`.
+- Review follow-up: connection tests and uploads read the password of the account they started in and stop after an account switch; turning the option off cancels a running upload; folder creation, `MOVE`, size check, cleanup, retention and the connection test are bounded by the stall timeout even when a request ignores cancellation. Six regression tests cover these and fail on the previous version.
+- `bun run typecheck`, `bun run typecheck:mobile`, `bun run lint`, `bun run build:web`, `bun run test`.
+- Not verified: Windows and Linux runtime (no local machines; CI does not run this flow), packaged builds, Nextcloud and commercial providers without test accounts.
diff --git a/docs/changes/2026-11-02-desktop-webdav-offsite.zh-CN.md b/docs/changes/2026-11-02-desktop-webdav-offsite.zh-CN.md
new file mode 100644
index 00000000..7707f026
--- /dev/null
+++ b/docs/changes/2026-11-02-desktop-webdav-offsite.zh-CN.md
@@ -0,0 +1,34 @@
+# 桌面定时备份:可选的 WebDAV 异地副本
+
+[English](2026-11-02-desktop-webdav-offsite.md)
+
+关联 Issue:#723(备份方案 P2;延续 #61 与 #650)
+
+## 问题与结果
+
+桌面定时备份只写入本地文件夹。没有网盘客户端、或希望把备份放到 NAS / WebDAV 服务的用户,缺少自动的异地副本。现在每次本地备份完成后,桌面端可以把归档复制到 WebDAV 服务器(Nextcloud、群晖/威联通、Hetzner Storage Box、Koofr、pCloud、坚果云、Alist 等)。设计见[定时备份设计第 12 节](../desktop-scheduled-backup-design.zh-CN.md)。
+
+## 范围
+
+- 桌面主进程:新增 `backup-offsite.mjs`;`backup-manager.mjs` 报告异地副本状态、发布后排队上传、在每小时检查时重试、切换账号时取消;新增三个 IPC 操作(`offsite-save`、`offsite-test`、`offsite-upload`);因为主进程不打包,`webdav` 加入桌面应用依赖。
+- 设置 → 导入与导出 → 备份与恢复:可折叠的“异地副本(WebDAV)”区域,以及带“立即上传”的独立状态行。
+- 共享 IPC 类型与五种语言的翻译。
+- 不变:归档格式、本地备份结果、API、Cloudflare/Docker 运行时、数据库与迁移、同步、Web 端 WebDAV 卡片。
+
+## 风险与恢复
+
+- **密码泄露。** 只通过 Electron `safeStorage` 保存在绑定范围的 `.secret` 文件中;不会出现在状态、渲染进程状态、日志、归档或 EdgeEver 服务端。没有明文回退。已保存的密码绑定地址和用户名,修改其中任何一项或测试其他服务器时都必须重新输入。除局域网地址外必须使用 `https://`。
+- **误删有效的远程副本。** 远程保留只删除本备份集记录为已上传到同一目标的文件,并且只在更新的副本上传成功之后删除。
+- **阻塞本地备份。** 上传在本地备份队列之外运行,不改变本地备份结果。
+- **回滚。** 关闭选项即停止上传,本地和远程文件均保留。旧版本会忽略 `<scope>.offsite.json` 和异地副本的 `.secret` 文件(见下方验证)。
+
+## 验证
+
+- 单元测试(`backup-offsite.test.mjs`,15 项,模拟 WebDAV):经 `.part` 上传并移动、大小核对、`.part` 清理、取消、上传中切换账号、停滞超时、保留归属、重试最新归档、密码处理、明确的 `Content-Length`。
+- 集成测试(`bun run test:webdav`,真实 `rclone serve webdav` 1.69,分别在 Bun 和 Node 下运行):正确/错误密码的连接测试、普通与加密归档逐字节一致且无残留 `.part`、保留策略不删除他人文件、保存的密码错误、HTTP 413 大小限制提示“文件过大”且无 `.part`、服务器不可达。本地 Docker Desktop 不可用,因此直接运行 rclone,并用 64 KiB 代理模拟大小限制,未使用 `tests/webdav/compose.yml` 中的 nginx 容器。
+- macOS 桌面端(Electron 未打包,本地自托管服务端):连接测试;普通备份上传后从 WebDAV 下载,删除笔记后恢复成功;加密备份原样上传(`EDGB` 头、无明文),用密码恢复成功;WebDAV 密码错误时只有副本失败、本地备份成功,“立即上传”可恢复;状态和所有状态文件中都不含密码;设置界面正确显示该区域与状态行。
+- 升级:由当前 `main` 构建创建、含加密本地备份的配置目录,用新构建打开后设置、密码和历史均保留;异地副本默认关闭,启用后上传了旧版本创建的备份。再用旧构建打开该目录,可正常执行新的本地备份。
+- 验证中发现并修复:在请求体上统计进度会丢失较大文件开头的数据块;`webdav` 库以分块方式发送流,部分服务器不接受。现在改为在转换流中计数,并发送明确的 `Content-Length`。
+- 评审后修复:连接测试与上传只读取启动时所属账号的密码,账号切换后停止;关闭选项会取消正在进行的上传;创建文件夹、`MOVE`、核对大小、清理、保留策略和连接测试都受停滞超时限制,即使请求不响应取消。六项回归测试覆盖这些情况,并在旧版本上失败。
+- `bun run typecheck`、`bun run typecheck:mobile`、`bun run lint`、`bun run build:web`、`bun run test`。
+- 未验证:Windows 与 Linux 运行时(无本地设备,CI 不运行此流程)、打包构建、Nextcloud 及无测试账号的商业服务。
diff --git a/docs/desktop-scheduled-backup-design.md b/docs/desktop-scheduled-backup-design.md
index a939a5cd..e2e366da 100644
--- a/docs/desktop-scheduled-backup-design.md
+++ b/docs/desktop-scheduled-backup-design.md
@@ -20,7 +20,7 @@ This delivery excludes:
The coverage description in Settings should say “Backs up synchronized notes and attachments.” A backup does not push pending local changes or substitute local caches when the network is unavailable. A network failure preserves the last successful result until a retry can run.
-Existing SQLite snapshots remain a separate local recovery mechanism. WebDAV and S3 transfers, OS-level scheduling after the app exits, browser-based password export and decryption, and native mobile entry points remain outside this delivery. Existing ordinary ZIP import and export on the Web remain available.
+Existing SQLite snapshots remain a separate local recovery mechanism. S3 transfers (the optional WebDAV copy is described in section 12), OS-level scheduling after the app exits, browser-based password export and decryption, and native mobile entry points remain outside this delivery. Existing ordinary ZIP import and export on the Web remain available.
## 2. Defaults and settings
@@ -232,3 +232,17 @@ Record platform, cross-version, and large-archive evidence separately. A small-f
- [Import/export card](../apps/web/src/components/settings/DataExportCard.tsx), [renderer hibernation](../apps/desktop/src/main/renderer-hibernate.mjs), and [account isolation](../apps/desktop/src/main/account-scope.mjs): retain existing entry points while keeping background work independent of the renderer.
- [Cross-runtime storage contracts](../apps/api/src/storage-contract.ts) and [self-hosting architecture](self-hosting-architecture.md): do not implement consistency logic only in the Cloudflare entry point.
- [Original backup and disaster-recovery proposal](https://github.com/tianma-if/edgeever/blob/main/docs/backup-and-disaster-recovery-plan.zh-CN.md): retain the local-directory approach while specifying Issue #650's delivery boundaries and recovery requirements.
+
+## 12. Off-site WebDAV copy (P2, Issue #723)
+
+The optional off-site copy runs after a local backup is published. The local archive stays the source of truth; the archive format, server, database and synchronization are unchanged.
+
+- **Independent state.** `backup-offsite.mjs` keeps its own state file (`<scope>.offsite.json`) next to the backup state and never joins the local backup queue. An upload failure, a slow server or a cancelled upload never changes the local backup result, its success time or its retention.
+- **Settings.** Off by default. Address, username, remote folder (default `/EdgeEver/backups`) and password, saved explicitly with a **Test connection** action. `https://` is required; `http://` is accepted only for local-network hosts because Basic authentication sends the password with every request. Addresses with embedded credentials, query or fragment are rejected.
+- **Password.** Stored with Electron `safeStorage` in a separate `.secret` file bound to the instance and account scope, like the backup password. It never appears in the state file, renderer status, logs or the archive, and is never sent to the EdgeEver server. It is tied to the address and username it was entered for: changing either requires entering the password again, and testing another address never uses the saved one. When secure storage is unavailable, or Linux reports `basic_text`, uploads pause with a message; there is no plaintext fallback.
+- **Upload.** The published file is streamed as-is (encrypted archives stay encrypted) to `<folder>/<backupSetId>/<name>.<uuid>.part` with an explicit `Content-Length`, then moved to the final name and its remote size is checked. The local file is held open during the upload so local retention can proceed. A request that stops moving data for two minutes is aborted, and every other request (folder creation, `MOVE`, size check, cleanup, retention and the connection test) has the same two-minute bound, even if the server ignores cancellation, so one stuck request cannot block later copies. A leftover `.part` file is deleted on failure, and on the next start if the app quit mid-upload.
+- **Scheduling and retry.** Each completed local backup queues one upload; only the newest pending archive is kept. The hourly check retries the latest local archive when its copy failed or never ran (at most once an hour); **Upload now** retries immediately. Switching account or signing out cancels the upload, and so does turning the option off or changing the target. A connection test or upload reads the password of the account it started in and stops if the account changes while it waits.
+- **Remote retention.** Uses the local retention count. Only files this backup set recorded as uploaded to the same address, user and folder are deleted, and only after a newer copy succeeded. Files placed manually or by other devices or accounts are never touched. A failed delete is reported as a warning and retried later.
+- **Limits.** Plain WebDAV uploads a file in one request. A server request-size limit (HTTP 413) is reported as “file too large for this server”; provider-specific chunking is a possible follow-up.
+- **Rollback.** Turning the option off stops uploads and keeps both local and remote files. Older versions ignore the extra state and secret files.
+
diff --git a/docs/desktop-scheduled-backup-design.zh-CN.md b/docs/desktop-scheduled-backup-design.zh-CN.md
index d2dd5ecc..3275dd7b 100644
--- a/docs/desktop-scheduled-backup-design.zh-CN.md
+++ b/docs/desktop-scheduled-backup-design.zh-CN.md
@@ -20,7 +20,7 @@
设置页应在备份范围处说明“备份已同步的笔记和附件”。备份任务不主动提交本地待同步修改,也不在网络不可用时改用本地缓存凑出一份归档。网络不可用时保留上次成功记录,等待重试。
-现有 SQLite 本地快照继续承担本机恢复用途,不与本功能混用。WebDAV、S3 直传、应用完全退出后的系统级调度、Web 端密码导出与解密、移动端原生入口均留在后续范围。Web 原有普通 ZIP 导入导出保留。
+现有 SQLite 本地快照继续承担本机恢复用途,不与本功能混用。S3 直传(可选的 WebDAV 异地副本见第 12 节)、应用完全退出后的系统级调度、Web 端密码导出与解密、移动端原生入口均留在后续范围。Web 原有普通 ZIP 导入导出保留。
## 2. 默认配置和设置入口
@@ -232,3 +232,17 @@ GCM 的流式输出在最终认证前不能视为可信,因此禁止把解密
- [导入导出卡片](../apps/web/src/components/settings/DataExportCard.tsx)、[渲染器休眠](../apps/desktop/src/main/renderer-hibernate.mjs)与[账号隔离](../apps/desktop/src/main/account-scope.mjs):沿用现有入口,后台任务独立于渲染器。
- [跨运行时存储契约](../apps/api/src/storage-contract.ts)与[自托管架构](self-hosting-architecture.zh-CN.md):一致性逻辑不能只在 Cloudflare 入口实现。
- [原备份与容灾方案](https://github.com/tianma-if/edgeever/blob/main/docs/backup-and-disaster-recovery-plan.zh-CN.md):保留本地目录协同路线,本设计细化 Issue #650 的交付边界与恢复条件。
+
+## 12. WebDAV 异地副本(P2,Issue #723)
+
+可选的异地副本在本地备份发布完成后执行。本地归档仍是唯一可信来源;归档格式、服务端、数据库和同步均不变。
+
+- **独立状态。** `backup-offsite.mjs` 在备份状态旁保存自己的状态文件(`<scope>.offsite.json`),从不进入本地备份队列。上传失败、服务器缓慢或上传被取消,都不会改变本地备份结果、成功时间或保留策略。
+- **设置。** 默认关闭。地址、用户名、远程文件夹(默认 `/EdgeEver/backups`)和密码需要显式保存,并提供“测试连接”。必须使用 `https://`;由于 Basic 认证会在每次请求中发送密码,`http://` 只允许局域网地址。拒绝包含凭据、查询参数或片段的地址。
+- **密码。** 与备份密码一样,用 Electron `safeStorage` 保存在独立的 `.secret` 文件中,并绑定实例和账号范围。密码不会出现在状态文件、渲染进程状态、日志或归档中,也不会发送到 EdgeEver 服务端。密码绑定输入时的地址和用户名:修改其中任何一项都必须重新输入密码,测试其他地址时也不会使用已保存的密码。系统安全存储不可用或 Linux 报告 `basic_text` 时暂停上传并提示,不回退为明文。
+- **上传。** 已发布文件原样流式上传(加密归档保持加密)到 `<folder>/<backupSetId>/<name>.<uuid>.part`,请求带明确的 `Content-Length`,随后移动到最终文件名并核对远程大小。上传期间保持本地文件句柄,本地保留策略可照常执行。两分钟没有数据传输的请求会被中止;其他所有请求(创建文件夹、`MOVE`、核对大小、清理、保留策略和连接测试)也有同样的两分钟上限,即使服务器不响应取消也会结束,避免一个卡住的请求阻塞后续副本。失败时删除残留 `.part`;如果应用在上传中退出,下次启动时清理。
+- **调度与重试。** 每次本地备份完成后排队一次上传,只保留最新的待上传归档。每小时检查时,如果最新本地归档上传失败或尚未上传,则重试(每小时最多一次);“立即上传”会马上重试。切换账号、退出登录、关闭选项或修改目标都会取消上传。连接测试和上传只读取启动时所属账号的密码,等待期间账号发生变化即停止。
+- **远程保留。** 使用本地保留数量。只删除本备份集记录为已上传到同一地址、用户和文件夹的文件,并且只在更新的副本上传成功之后删除。手动放入或其他设备、其他账号产生的文件永远不会被删除。删除失败显示为警告,稍后重试。
+- **限制。** 标准 WebDAV 用单个请求上传文件。服务器请求大小限制(HTTP 413)会提示“文件超过该服务器限制”;各服务商的分块上传可作为后续改进。
+- **回滚。** 关闭选项即停止上传,本地与远程文件均保留。旧版本会忽略额外的状态和密钥文件。
+
diff --git a/package.json b/package.json
index 4c1a1557..ecbcd56b 100644
--- a/package.json
+++ b/package.json
@@ -68,6 +68,7 @@
"publish:stores": "bun scripts/store-delivery.mjs",
"publish:extension": "bun scripts/publish-web-clipper.mjs",
"test:plugin-sync": "bun tests/plugin-structured-sync.integration.mjs",
+ "test:webdav": "bun tests/desktop-webdav-backup.integration.mjs",
"test:desktop:backup-network": "bun apps/desktop/scripts/build-backup-worker.mjs && bun test ./apps/desktop/src/backup/tests/electron-network.integration.mjs",
"test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs && bun run test:plugin-sync",
"test:desktop": "bun test apps/desktop/src/main --path-ignore-patterns='apps/desktop/src/main/{acp-cleanup,acp-adapter-manager,acp-host,workbuddy-auth,antigravity-proxy,acp-mcp-bridge}.test.mjs' apps/web/src/lib/api.test.mjs apps/web/src/lib/app-page-path.test.mjs apps/web/src/lib/clipboard.test.mjs apps/web/src/lib/desktop-renderer-ready.test.mjs apps/web/src/lib/desktop-workspace-restore.test.mjs apps/web/src/lib/desktop-repository.test.mjs apps/web/src/lib/desktop-resources.test.mjs apps/web/src/lib/desktop-acp.test.mjs apps/web/src/lib/desktop-sync.test.mjs apps/web/src/lib/local-mirror.test.mjs apps/web/src/lib/repository.test.mjs apps/web/src/lib/runtime.test.mjs apps/web/src/lib/picgo.test.mjs apps/web/src/lib/screenshot-import.test.mjs apps/web/src/lib/wechat-chat-import.test.mjs apps/web/src/lib/shared-file-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun test --cwd apps/desktop src/main/acp-cleanup.test.mjs src/main/acp-adapter-manager.test.mjs src/main/acp-host.test.mjs src/main/workbuddy-auth.test.mjs src/main/antigravity-proxy.test.mjs src/main/acp-mcp-bridge.test.mjs && bun run test:desktop:sidecar",
diff --git a/packages/shared/src/backup.ts b/packages/shared/src/backup.ts
index a04b66ad..e4e2ca3e 100644
--- a/packages/shared/src/backup.ts
+++ b/packages/shared/src/backup.ts
@@ -212,6 +212,19 @@ export type DesktopBackupConfig = {
encrypted: boolean;
};
export type DesktopBackupError = { code: string; message?: string; status?: number };
+// Optional WebDAV copy of each completed local backup. The password stays in the main process.
+export type DesktopOffsiteConfig = { enabled: boolean; url: string; username: string; folder: string };
+export type DesktopOffsiteStatus = {
+ config: DesktopOffsiteConfig;
+ passwordSet: boolean;
+ secureStorageAvailable: boolean;
+ lastAttemptAt: string | null;
+ lastSuccessAt: string | null;
+ lastUploaded: { name: string; size: number; uploadedAt: string } | null;
+ error: DesktopBackupError | null;
+ warning: DesktopBackupError | null;
+ task: { name: string; sent: number; total: number } | null;
+};
export type DesktopBackupStatus = {
blocked: boolean;
config: DesktopBackupConfig;
@@ -232,6 +245,8 @@ export type DesktopBackupStatus = {
importWarning: DesktopBackupError | null;
history: Array<{ name: string; directory: string; completedAt: string; size: number; encrypted: boolean }>;
task: null | { kind: "export" | "import"; phase: "checking-source" | "exporting" | "decrypting" | "checking" | "ready" | "restoring"; completed: number; total: number; manifest?: JsonBackupManifest };
+ /** Older desktop builds omit it. */
+ offsite?: DesktopOffsiteStatus | null;
};
export type DesktopBackupSelection = { id: string; name: string; encrypted: boolean };
export type DesktopBackupActions = {
@@ -246,4 +261,7 @@ export type DesktopBackupActions = {
"delete-history": { input: { backupSetId: string; name: string }; output: DesktopBackupStatus };
"prepare-import": { input: { backupSetId: string; id: string; password?: string }; output: DesktopBackupStatus };
"confirm-import": { input: { backupSetId: string }; output: DesktopBackupStatus };
+ "offsite-save": { input: { backupSetId: string; config: DesktopOffsiteConfig; password?: string }; output: DesktopBackupStatus };
+ "offsite-test": { input: { backupSetId: string; config: DesktopOffsiteConfig; password?: string }; output: { ok: true } };
+ "offsite-upload": { input: { backupSetId: string }; output: DesktopBackupStatus };
};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 8c69bc0f..126e5b8f 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2206,6 +2206,28 @@ export const enUS = {
ready: "Ready to restore",
restoring: "Restoring data…"
},
+ offsite: {
+ title: "Off-site copy (WebDAV)",
+ description: "After each local backup, copy the file as it is (encrypted backups stay encrypted) to a WebDAV server such as Nextcloud, a NAS or Hetzner Storage Box. Local backups never wait for the upload.",
+ enable: "Copy backups to WebDAV",
+ url: "WebDAV address",
+ username: "Username",
+ folder: "Remote folder",
+ password: "WebDAV password",
+ passwordHint: "Use an app password if your provider offers one. It is stored in the system's secure storage on this device only.",
+ passwordSet: "WebDAV password saved",
+ secureUnavailable: "Secure storage is unavailable, so the WebDAV password cannot be saved and off-site copies are paused.",
+ httpLocalOnly: "http:// is accepted only for addresses on your local network. Use https:// for anything else.",
+ save: "Save WebDAV settings",
+ test: "Test connection",
+ testComplete: "Connection works and the remote folder is ready.",
+ saved: "WebDAV settings saved.",
+ lastSuccess: "Last off-site copy: {{time}}",
+ lastUploaded: "{{name}} · {{size}}",
+ uploading: "Uploading {{name}}: {{sent}} / {{total}}",
+ uploadNow: "Upload now",
+ failed: "Off-site copy failed: {{message}} The local backup is not affected.",
+ },
errors: {
backup_name_invalid: "Enter a valid filename without paths, reserved names or special characters.",
backup_name_exists: "A file with this name already exists. Try again in a moment; the existing file is unchanged.",
@@ -2233,7 +2255,24 @@ export const enUS = {
EPERM: "Folder access was denied. Check the folder permissions.",
ENOSPC: "There is not enough free disk space. Free space and try again.",
ENOENT: "The file or folder is no longer available. Choose it again.",
- backup_cancelled: "Cancelled."
+ backup_cancelled: "Cancelled.",
+ offsite_invalid_configuration: "Enter the WebDAV address, username and password.",
+ offsite_invalid_url: "Enter a valid WebDAV address without a username, password, query or fragment.",
+ offsite_insecure_url: "Use an https:// address. http:// is only allowed on a local network.",
+ offsite_invalid_folder: "Enter a remote folder without . or .. segments.",
+ offsite_password_required: "Enter the WebDAV password.",
+ offsite_secure_storage_unavailable: "Unlock secure storage or enter the WebDAV password again.",
+ offsite_auth_failed: "The WebDAV server rejected the username or password.",
+ offsite_file_too_large: "The backup file is too large for this WebDAV server.",
+ offsite_storage_full: "The WebDAV server has no space left.",
+ offsite_upload_failed: "The upload to WebDAV failed. It will be retried at the next check.",
+ offsite_unreachable: "The WebDAV server could not be reached.",
+ offsite_source_changed: "The local backup file changed during the upload. It was not copied.",
+ offsite_size_mismatch: "The uploaded copy has a different size. It will be uploaded again.",
+ offsite_stalled: "The WebDAV server stopped responding.",
+ offsite_no_backup: "Run a local backup first.",
+ offsite_already_uploaded: "The latest backup is already copied.",
+ offsite_cleanup_failed: "Off-site copy completed, but some older remote copies could not be removed."
}
},
dataExport: {
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 332634e4..7a010267 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2195,6 +2195,28 @@ export const ja = {
ready: "復元の準備完了",
restoring: "データを復元中…"
},
+ offsite: {
+ title: "オフサイトコピー(WebDAV)",
+ description: "ローカルバックアップが完了するたびに、ファイルをそのまま(暗号化されたバックアップは暗号化されたまま)Nextcloud、NAS、Hetzner Storage Box などの WebDAV サーバーへコピーします。ローカルバックアップはアップロードを待ちません。",
+ enable: "バックアップを WebDAV にコピー",
+ url: "WebDAV アドレス",
+ username: "ユーザー名",
+ folder: "リモートフォルダー",
+ password: "WebDAV パスワード",
+ passwordHint: "プロバイダーがアプリパスワードを提供している場合はそれを使用してください。パスワードはこのデバイスのシステムのセキュアストレージにのみ保存されます。",
+ passwordSet: "WebDAV パスワードは保存済みです",
+ secureUnavailable: "システムのセキュアストレージを利用できないため、WebDAV パスワードを保存できず、オフサイトコピーは一時停止しています。",
+ httpLocalOnly: "http:// はローカルネットワーク内のアドレスでのみ使用できます。それ以外は https:// を使用してください。",
+ save: "WebDAV 設定を保存",
+ test: "接続をテスト",
+ testComplete: "接続できました。リモートフォルダーの準備ができています。",
+ saved: "WebDAV 設定を保存しました。",
+ lastSuccess: "最後のオフサイトコピー:{{time}}",
+ lastUploaded: "{{name}} · {{size}}",
+ uploading: "{{name}} をアップロード中:{{sent}} / {{total}}",
+ uploadNow: "今すぐアップロード",
+ failed: "オフサイトコピーに失敗しました:{{message}} ローカルバックアップには影響ありません。",
+ },
errors: {
backup_name_invalid: "パス、予約名、特殊文字を含まない有効なファイル名を入力してください。",
backup_name_exists: "同名のファイルがあります。少し待ってから再度バックアップしてください。既存のファイルは変更されていません。",
@@ -2222,7 +2244,24 @@ export const ja = {
EPERM: "アクセスが拒否されました。権限を確認してください。",
ENOSPC: "空き容量が不足しています。空き容量を確保してください。",
ENOENT: "ファイルまたはフォルダーがありません。再選択してください。",
- backup_cancelled: "キャンセルしました。"
+ backup_cancelled: "キャンセルしました。",
+ offsite_invalid_configuration: "WebDAV アドレス、ユーザー名、パスワードを入力してください。",
+ offsite_invalid_url: "ユーザー名、パスワード、クエリ、フラグメントを含まない有効な WebDAV アドレスを入力してください。",
+ offsite_insecure_url: "https:// アドレスを使用してください。http:// はローカルネットワークでのみ使用できます。",
+ offsite_invalid_folder: ". や .. を含まないリモートフォルダーを入力してください。",
+ offsite_password_required: "WebDAV パスワードを入力してください。",
+ offsite_secure_storage_unavailable: "セキュアストレージのロックを解除するか、WebDAV パスワードを再入力してください。",
+ offsite_auth_failed: "WebDAV サーバーがユーザー名またはパスワードを拒否しました。",
+ offsite_file_too_large: "バックアップファイルがこの WebDAV サーバーの上限を超えています。",
+ offsite_storage_full: "WebDAV サーバーの空き容量がありません。",
+ offsite_upload_failed: "WebDAV へのアップロードに失敗しました。次回のチェックで再試行します。",
+ offsite_unreachable: "WebDAV サーバーに接続できません。",
+ offsite_source_changed: "アップロード中にローカルのバックアップファイルが変更されたため、コピーされませんでした。",
+ offsite_size_mismatch: "アップロードしたコピーのサイズが一致しません。再度アップロードします。",
+ offsite_stalled: "WebDAV サーバーが応答しなくなりました。",
+ offsite_no_backup: "先にローカルバックアップを実行してください。",
+ offsite_already_uploaded: "最新のバックアップはすでにコピー済みです。",
+ offsite_cleanup_failed: "オフサイトコピーは完了しましたが、一部の古いリモートコピーを削除できませんでした。"
}
},
dataExport: {
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 8fdebf9c..63f204fe 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2195,6 +2195,28 @@ export const pl = {
ready: "Gotowe do przywrócenia",
restoring: "Przywracanie danych…"
},
+ offsite: {
+ title: "Kopia poza urządzeniem (WebDAV)",
+ description: "Po każdym lokalnym backupie plik jest kopiowany bez zmian (zaszyfrowany zostaje zaszyfrowany) na serwer WebDAV, np. Nextcloud, NAS albo Hetzner Storage Box. Lokalny backup nigdy nie czeka na wysyłkę.",
+ enable: "Kopiuj backupy na WebDAV",
+ url: "Adres WebDAV",
+ username: "Nazwa użytkownika",
+ folder: "Folder zdalny",
+ password: "Hasło WebDAV",
+ passwordHint: "Użyj hasła aplikacji, jeśli dostawca je oferuje. Hasło jest przechowywane tylko w bezpiecznym magazynie systemu na tym urządzeniu.",
+ passwordSet: "Hasło WebDAV zapisane",
+ secureUnavailable: "Bezpieczny magazyn systemu jest niedostępny, więc nie można zapisać hasła WebDAV, a kopie poza urządzeniem są wstrzymane.",
+ httpLocalOnly: "http:// jest dozwolone tylko dla adresów w sieci lokalnej. W pozostałych przypadkach użyj https://.",
+ save: "Zapisz ustawienia WebDAV",
+ test: "Sprawdź połączenie",
+ testComplete: "Połączenie działa, a folder zdalny jest gotowy.",
+ saved: "Zapisano ustawienia WebDAV.",
+ lastSuccess: "Ostatnia kopia poza urządzeniem: {{time}}",
+ lastUploaded: "{{name}} · {{size}}",
+ uploading: "Wysyłanie {{name}}: {{sent}} / {{total}}",
+ uploadNow: "Wyślij teraz",
+ failed: "Kopia poza urządzeniem nie powiodła się: {{message}} Lokalny backup nie jest naruszony.",
+ },
errors: {
backup_name_invalid: "Wpisz prawidłową nazwę pliku bez ścieżek, nazw zastrzeżonych i znaków specjalnych.",
backup_name_exists: "Plik o tej nazwie już istnieje. Spróbuj ponownie za chwilę; istniejący plik nie został zmieniony.",
@@ -2222,7 +2244,24 @@ export const pl = {
EPERM: "Odmowa dostępu. Sprawdź uprawnienia folderu.",
ENOSPC: "Brak miejsca na dysku. Zwolnij miejsce i spróbuj ponownie.",
ENOENT: "Plik lub folder już nie istnieje. Wybierz ponownie.",
- backup_cancelled: "Anulowano."
+ backup_cancelled: "Anulowano.",
+ offsite_invalid_configuration: "Podaj adres WebDAV, nazwę użytkownika i hasło.",
+ offsite_invalid_url: "Podaj prawidłowy adres WebDAV bez nazwy użytkownika, hasła, parametrów i fragmentu.",
+ offsite_insecure_url: "Użyj adresu https://. http:// jest dozwolone tylko w sieci lokalnej.",
+ offsite_invalid_folder: "Podaj folder zdalny bez segmentów „.” i „..”.",
+ offsite_password_required: "Podaj hasło WebDAV.",
+ offsite_secure_storage_unavailable: "Odblokuj bezpieczny magazyn systemu albo podaj hasło WebDAV ponownie.",
+ offsite_auth_failed: "Serwer WebDAV odrzucił nazwę użytkownika lub hasło.",
+ offsite_file_too_large: "Plik backupu jest za duży dla tego serwera WebDAV.",
+ offsite_storage_full: "Na serwerze WebDAV brakuje miejsca.",
+ offsite_upload_failed: "Wysyłka na WebDAV nie powiodła się. Zostanie ponowiona przy następnym sprawdzeniu.",
+ offsite_unreachable: "Nie można połączyć się z serwerem WebDAV.",
+ offsite_source_changed: "Lokalny plik backupu zmienił się w trakcie wysyłki. Nie został skopiowany.",
+ offsite_size_mismatch: "Wysłana kopia ma inny rozmiar. Zostanie wysłana ponownie.",
+ offsite_stalled: "Serwer WebDAV przestał odpowiadać.",
+ offsite_no_backup: "Najpierw wykonaj lokalny backup.",
+ offsite_already_uploaded: "Najnowszy backup jest już skopiowany.",
+ offsite_cleanup_failed: "Kopia poza urządzeniem gotowa, ale nie udało się usunąć części starszych kopii zdalnych."
}
},
dataExport: {
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index 36ab3921..3978bd39 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -2206,6 +2206,28 @@ export const ru = {
ready: "Готово к восстановлению",
restoring: "Восстановление данных…"
},
+ offsite: {
+ title: "Внешняя копия (WebDAV)",
+ description: "После каждой локальной резервной копии файл без изменений (зашифрованные копии остаются зашифрованными) копируется на сервер WebDAV, например Nextcloud, NAS или Hetzner Storage Box. Локальное резервное копирование не ждёт загрузки.",
+ enable: "Копировать резервные копии на WebDAV",
+ url: "Адрес WebDAV",
+ username: "Имя пользователя",
+ folder: "Удалённая папка",
+ password: "Пароль WebDAV",
+ passwordHint: "Используйте пароль приложения, если провайдер его поддерживает. Пароль хранится только в защищённом хранилище системы на этом устройстве.",
+ passwordSet: "Пароль WebDAV сохранён",
+ secureUnavailable: "Защищённое хранилище системы недоступно, поэтому пароль WebDAV нельзя сохранить, и внешние копии приостановлены.",
+ httpLocalOnly: "http:// разрешён только для адресов в локальной сети. В остальных случаях используйте https://.",
+ save: "Сохранить настройки WebDAV",
+ test: "Проверить подключение",
+ testComplete: "Подключение работает, удалённая папка готова.",
+ saved: "Настройки WebDAV сохранены.",
+ lastSuccess: "Последняя внешняя копия: {{time}}",
+ lastUploaded: "{{name}} · {{size}}",
+ uploading: "Загрузка {{name}}: {{sent}} / {{total}}",
+ uploadNow: "Загрузить сейчас",
+ failed: "Не удалось создать внешнюю копию: {{message}} Локальная резервная копия не затронута.",
+ },
errors: {
backup_name_invalid: "Введите допустимое имя файла без пути, зарезервированных имён и специальных символов.",
backup_name_exists: "Файл с таким именем уже существует. Повторите резервное копирование чуть позже; существующий файл не изменён.",
@@ -2233,7 +2255,24 @@ export const ru = {
EPERM: "Доступ к папке запрещён. Проверьте права доступа.",
ENOSPC: "Недостаточно свободного места. Освободите место и повторите попытку.",
ENOENT: "Файл или папка больше недоступны. Выберите их заново.",
- backup_cancelled: "Отменено."
+ backup_cancelled: "Отменено.",
+ offsite_invalid_configuration: "Укажите адрес WebDAV, имя пользователя и пароль.",
+ offsite_invalid_url: "Введите корректный адрес WebDAV без имени пользователя, пароля, параметров запроса и фрагмента.",
+ offsite_insecure_url: "Используйте адрес https://. http:// разрешён только в локальной сети.",
+ offsite_invalid_folder: "Укажите удалённую папку без сегментов . и ..",
+ offsite_password_required: "Введите пароль WebDAV.",
+ offsite_secure_storage_unavailable: "Разблокируйте защищённое хранилище или введите пароль WebDAV заново.",
+ offsite_auth_failed: "Сервер WebDAV отклонил имя пользователя или пароль.",
+ offsite_file_too_large: "Файл резервной копии слишком велик для этого сервера WebDAV.",
+ offsite_storage_full: "На сервере WebDAV закончилось место.",
+ offsite_upload_failed: "Не удалось загрузить на WebDAV. Попытка будет повторена при следующей проверке.",
+ offsite_unreachable: "Не удаётся подключиться к серверу WebDAV.",
+ offsite_source_changed: "Локальный файл резервной копии изменился во время загрузки. Он не был скопирован.",
+ offsite_size_mismatch: "Размер загруженной копии отличается. Она будет загружена заново.",
+ offsite_stalled: "Сервер WebDAV перестал отвечать.",
+ offsite_no_backup: "Сначала создайте локальную резервную копию.",
+ offsite_already_uploaded: "Последняя резервная копия уже скопирована.",
+ offsite_cleanup_failed: "Внешняя копия создана, но некоторые старые удалённые копии удалить не удалось."
}
},
dataExport: {
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index d35dcabf..5685b3c8 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2206,6 +2206,28 @@ export const zhCN = {
ready: "可以恢复",
restoring: "正在恢复数据…"
},
+ offsite: {
+ title: "异地副本(WebDAV)",
+ description: "每次本地备份完成后,把备份文件原样(加密备份保持加密)复制到 WebDAV 服务器,例如 Nextcloud、NAS 或 Hetzner Storage Box。本地备份不会等待上传。",
+ enable: "将备份复制到 WebDAV",
+ url: "WebDAV 地址",
+ username: "用户名",
+ folder: "远程文件夹",
+ password: "WebDAV 密码",
+ passwordHint: "如果服务商提供应用密码,请使用应用密码。密码只保存在本设备的系统安全存储中。",
+ passwordSet: "已保存 WebDAV 密码",
+ secureUnavailable: "系统安全存储不可用,无法保存 WebDAV 密码,异地副本已暂停。",
+ httpLocalOnly: "只有局域网地址可以使用 http://,其他地址请使用 https://。",
+ save: "保存 WebDAV 设置",
+ test: "测试连接",
+ testComplete: "连接正常,远程文件夹已就绪。",
+ saved: "已保存 WebDAV 设置。",
+ lastSuccess: "最近一次异地副本:{{time}}",
+ lastUploaded: "{{name}} · {{size}}",
+ uploading: "正在上传 {{name}}:{{sent}} / {{total}}",
+ uploadNow: "立即上传",
+ failed: "异地副本失败:{{message}} 本地备份不受影响。",
+ },
errors: {
backup_name_invalid: "请输入有效文件名,不要包含路径、保留名称或特殊字符。",
backup_name_exists: "已存在同名文件,请稍后重新备份。原文件未改动。",
@@ -2233,7 +2255,24 @@ export const zhCN = {
EPERM: "目录访问被拒绝,请检查目录权限。",
ENOSPC: "磁盘空间不足,请释放空间后重试。",
ENOENT: "文件或目录已不存在,请重新选择。",
- backup_cancelled: "已取消。"
+ backup_cancelled: "已取消。",
+ offsite_invalid_configuration: "请填写 WebDAV 地址、用户名和密码。",
+ offsite_invalid_url: "请输入有效的 WebDAV 地址,不要包含用户名、密码、查询参数或片段。",
+ offsite_insecure_url: "请使用 https:// 地址。只有局域网地址可以使用 http://。",
+ offsite_invalid_folder: "远程文件夹不能包含 . 或 .. 路径段。",
+ offsite_password_required: "请输入 WebDAV 密码。",
+ offsite_secure_storage_unavailable: "请解锁系统安全存储,或重新输入 WebDAV 密码。",
+ offsite_auth_failed: "WebDAV 服务器拒绝了用户名或密码。",
+ offsite_file_too_large: "备份文件超过了该 WebDAV 服务器允许的大小。",
+ offsite_storage_full: "WebDAV 服务器空间不足。",
+ offsite_upload_failed: "上传到 WebDAV 失败,将在下次检查时重试。",
+ offsite_unreachable: "无法连接 WebDAV 服务器。",
+ offsite_source_changed: "上传过程中本地备份文件发生了变化,未复制。",
+ offsite_size_mismatch: "上传后的副本大小不一致,将重新上传。",
+ offsite_stalled: "WebDAV 服务器停止响应。",
+ offsite_no_backup: "请先完成一次本地备份。",
+ offsite_already_uploaded: "最新备份已复制。",
+ offsite_cleanup_failed: "异地副本已完成,但部分旧的远程副本未能删除。"
}
},
dataExport: {
diff --git a/tests/desktop-webdav-backup.integration.mjs b/tests/desktop-webdav-backup.integration.mjs
new file mode 100644
index 00000000..f79f7fd6
--- /dev/null
+++ b/tests/desktop-webdav-backup.integration.mjs
@@ -0,0 +1,102 @@
+// Off-site backup copies against real WebDAV servers.
+// Start them with: docker compose -f tests/webdav/compose.yml up -d
+// Then run: bun run test:webdav
+import assert from "node:assert/strict";
+import { createHash, randomBytes } from "node:crypto";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createClient } from "webdav";
+import { OffsiteBackup } from "../apps/desktop/src/main/backup-offsite.mjs";
+
+const URL = process.env.EDGEEVER_WEBDAV_URL ?? "http://127.0.0.1:18080";
+const LIMITED_URL = process.env.EDGEEVER_WEBDAV_LIMITED_URL ?? "http://127.0.0.1:18081";
+const USER = process.env.EDGEEVER_WEBDAV_USER ?? "tester";
+const PASSWORD = process.env.EDGEEVER_WEBDAV_PASSWORD ?? "test-pass-123";
+const SET = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
+const secureStorage = {
+ isEncryptionAvailable: () => true, isAsyncEncryptionAvailable: async () => true,
+ encryptStringAsync: async (s) => Buffer.from(`sealed:${s}`), decryptStringAsync: async (b) => ({ result: b.toString().slice(7), shouldReEncrypt: false }),
+};
+const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
+
+const root = await mkdtemp(join(tmpdir(), "edgeever-webdav-it-"));
+const backups = join(root, "backups");
+await mkdir(join(root, "private", "scheduled-backups"), { recursive: true });
+await mkdir(join(backups, SET), { recursive: true });
+const folder = `/it-${Date.now()}`;
+const remote = createClient(URL, { username: USER, password: PASSWORD });
+const results = [];
+const step = async (name, run) => {
+ try { await run(); results.push(`PASS ${name}`); } catch (error) { results.push(`FAIL ${name}: ${error.message}`); }
+ console.log(results.at(-1));
+};
+const archive = async (name, size) => {
+ const bytes = randomBytes(size);
+ await writeFile(join(backups, SET, name), bytes);
+ return { entry: { name, directory: backups, size, completedAt: new Date().toISOString() }, bytes };
+};
+const offsite = new OffsiteBackup({ userData: join(root, "private"), secureStorage });
+const settle = async () => { while (offsite.upload || offsite.queued) await new Promise((r) => setTimeout(r, 20)); };
+await offsite.setScope("it-scope", SET);
+
+try {
+ await step("test connection: right password passes, wrong password is reported", async () => {
+ assert.deepEqual(await offsite.test({ url: URL, username: USER, folder }, PASSWORD), { ok: true });
+ await assert.rejects(offsite.test({ url: URL, username: USER, folder }, "wrong"), { code: "offsite_auth_failed" });
+ });
+
+ await offsite.save({ enabled: true, url: URL, username: USER, folder }, PASSWORD);
+
+ await step("plain and encrypted archives upload byte-for-byte without leftover .part files", async () => {
+ for (const [name, size] of [["edgeever-backup-1.zip", 3 * 1024 * 1024], ["edgeever-backup-2.edgeever.enc", 512 * 1024]]) {
+ const { entry, bytes } = await archive(name, size);
+ offsite.enqueue(entry, 5); await settle();
+ assert.equal(offsite.status().error, null, JSON.stringify(offsite.status().error));
+ const downloaded = await remote.getFileContents(`${folder}/${SET}/${name}`);
+ assert.equal(sha(Buffer.from(downloaded)), sha(bytes));
+ }
+ const listing = await remote.getDirectoryContents(`${folder}/${SET}`);
+ assert.deepEqual(listing.filter((item) => item.basename.endsWith(".part")), []);
+ });
+
+ await step("remote retention keeps the newest copies and never deletes foreign files", async () => {
+ await remote.putFileContents(`${folder}/${SET}/manual.zip`, "keep");
+ for (const name of ["r1.zip", "r2.zip", "r3.zip"]) {
+ const { entry } = await archive(name, 1024);
+ offsite.enqueue(entry, 2); await settle();
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ const names = (await remote.getDirectoryContents(`${folder}/${SET}`)).map((item) => item.basename).sort();
+ assert.deepEqual(names, ["manual.zip", "r2.zip", "r3.zip"]);
+ });
+
+ await step("a wrong saved password fails the copy without uploading anything", async () => {
+ await offsite.save({ enabled: true, url: URL, username: USER, folder }, "wrong-password");
+ const { entry } = await archive("denied.zip", 1024);
+ offsite.enqueue(entry, 5); await settle();
+ assert.equal(offsite.status().error?.code, "offsite_auth_failed");
+ assert.equal(await remote.exists(`${folder}/${SET}/denied.zip`), false);
+ });
+
+ await step("a server request-size limit is reported as file too large and leaves no .part", async () => {
+ await offsite.save({ enabled: true, url: LIMITED_URL, username: USER, folder }, PASSWORD);
+ const { entry } = await archive("too-large.zip", 512 * 1024);
+ offsite.enqueue(entry, 5); await settle();
+ assert.equal(offsite.status().error?.code, "offsite_file_too_large", JSON.stringify(offsite.status().error));
+ const listing = await remote.getDirectoryContents(`${folder}/${SET}`);
+ assert.deepEqual(listing.filter((item) => item.basename.startsWith("too-large")), []);
+ });
+
+ await step("an unreachable server is reported", async () => {
+ await offsite.save({ enabled: true, url: "http://127.0.0.1:9", username: USER, folder }, PASSWORD);
+ const { entry } = await archive("offline.zip", 1024);
+ offsite.enqueue(entry, 5); await settle();
+ assert.equal(offsite.status().error?.code, "offsite_unreachable", JSON.stringify(offsite.status().error));
+ });
+} finally {
+ await remote.deleteFile(folder).catch(() => {});
+ await rm(root, { recursive: true, force: true });
+ console.log(`\n${results.join("\n")}`);
+ if (results.some((line) => line.startsWith("FAIL"))) process.exitCode = 1;
+}
diff --git a/tests/webdav/compose.yml b/tests/webdav/compose.yml
new file mode 100644
index 00000000..62f200a0
--- /dev/null
+++ b/tests/webdav/compose.yml
@@ -0,0 +1,12 @@
+name: edgeever-webdav-test
+services:
+ webdav:
+ image: rclone/rclone:1.69
+ command: ["serve", "webdav", "/data", "--addr", ":8080", "--user", "tester", "--pass", "test-pass-123"]
+ tmpfs: ["/data"]
+ ports: ["127.0.0.1:18080:8080"]
+ limited:
+ image: nginx:1.27-alpine
+ volumes: ["./nginx-size-limit.conf:/etc/nginx/conf.d/default.conf:ro"]
+ ports: ["127.0.0.1:18081:80"]
+ depends_on: [webdav]
diff --git a/tests/webdav/nginx-size-limit.conf b/tests/webdav/nginx-size-limit.conf
new file mode 100644
index 00000000..fa1c85b2
--- /dev/null
+++ b/tests/webdav/nginx-size-limit.conf
@@ -0,0 +1,10 @@
+server {
+ listen 80;
+ client_max_body_size 64k;
+ location / {
+ proxy_pass http://webdav:8080;
+ proxy_request_buffering off;
+ proxy_set_header Host $host;
+ proxy_set_header Destination $http_destination;
+ }
+}