Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat: allow encrypting a workspace backup with a password (#639)

Tássio Noronha4c69808e8c63
diff --git a/backend/app/api/export.py b/backend/app/api/export.py
index d3f7cd9d..4ffee63c 100644
--- a/backend/app/api/export.py
+++ b/backend/app/api/export.py
@@ -1,6 +1,3 @@
-import io
-import json
-import zipfile
from datetime import date, datetime, timezone
from decimal import Decimal
from uuid import UUID
@@ -22,6 +19,8 @@ from app.models.import_log import ImportLog
from app.models.recurring_transaction import RecurringTransaction
from app.models.rule import Rule
from app.models.transaction import Transaction
+from app.schemas.export import BackupRequest
+from app.services.backup_service import build_backup_archive
router = APIRouter(prefix="/api/export", tags=["export"])
@@ -41,17 +40,8 @@ def _serialize(obj) -> dict:
return d
-async def backup(
- ctx: WorkspaceContext = Depends(current_workspace),
- session: AsyncSession = Depends(get_async_session),
-):
- """Export every entity in the current workspace as a JSON zip.
-
- Backup is scoped to one workspace at a time — users with multiple
- workspaces back each one up separately. AssetValue inherits its
- workspace from its Asset and is filtered transitively.
- """
+async def _collect(ctx: WorkspaceContext, session: AsyncSession) -> dict[str, object]:
+ """Every entity in the workspace, keyed by the file it becomes."""
ws_id = ctx.workspace.id
accounts = (await session.execute(select(Account).where(Account.workspace_id == ws_id))).scalars().all()
@@ -83,27 +73,57 @@ async def backup(
"import_logs": import_logs,
}
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
- entity_counts = {}
- for name, rows in entities.items():
- serialized = [_serialize(r) for r in rows]
- entity_counts[name] = len(serialized)
- zf.writestr(f"{name}.json", json.dumps(serialized, indent=2, ensure_ascii=False))
-
- metadata = {
- "export_date": datetime.now(timezone.utc).isoformat(),
- "format_version": "1.0",
- "workspace_id": str(ws_id),
- "workspace_name": ctx.workspace.name,
- "entity_counts": entity_counts,
- }
- zf.writestr("metadata.json", json.dumps(metadata, indent=2, ensure_ascii=False))
-
- buf.seek(0)
+ files: dict[str, object] = {}
+ entity_counts = {}
+ for name, rows in entities.items():
+ serialized = [_serialize(r) for r in rows]
+ entity_counts[name] = len(serialized)
+ files[f"{name}.json"] = serialized
+
+ files["metadata.json"] = {
+ "export_date": datetime.now(timezone.utc).isoformat(),
+ "format_version": "1.0",
+ "workspace_id": str(ws_id),
+ "workspace_name": ctx.workspace.name,
+ "entity_counts": entity_counts,
+ }
+ return files
+
+
+def _as_download(archive: bytes) -> StreamingResponse:
today = date.today().isoformat()
return StreamingResponse(
- iter([buf.getvalue()]),
+ iter([archive]),
media_type="application/zip",
headers={"Content-Disposition": f'attachment; filename="securo-backup-{today}.zip"'},
)
+
+
+async def backup(
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Export every entity in the current workspace as a JSON zip.
+
+ Backup is scoped to one workspace at a time — users with multiple
+ workspaces back each one up separately. AssetValue inherits its
+ workspace from its Asset and is filtered transitively.
+ """
+ return _as_download(build_backup_archive(await _collect(ctx, session)))
+
+
+async def backup_protected(
+ body: BackupRequest,
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """The same archive, encrypted with AES-256 when a password is given.
+
+ A POST because the password belongs in a body: a query string is written
+ to browser history, proxy logs and server access logs. Securo never stores
+ the password and cannot recover the archive without it.
+ """
+ password = body.password.get_secret_value() if body.password else None
+ return _as_download(build_backup_archive(await _collect(ctx, session), password))
diff --git a/backend/app/schemas/export.py b/backend/app/schemas/export.py
new file mode 100644
index 00000000..cc28ddcd
--- /dev/null
+++ b/backend/app/schemas/export.py
@@ -0,0 +1,13 @@
+from pydantic import BaseModel, Field, SecretStr
+
+
+class BackupRequest(BaseModel):
+ """Options for a workspace backup.
+
+ `password` is optional: omitted (or null) produces the plain zip. A
+ SecretStr so the value never reaches a log line or a validation error
+ through a repr. The floor is a length, not a character-class rule, since
+ those push people towards shorter passwords they can satisfy.
+ """
+
+ password: SecretStr | None = Field(default=None, min_length=8, max_length=256)
diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py
new file mode 100644
index 00000000..e555361d
--- /dev/null
+++ b/backend/app/services/backup_service.py
@@ -0,0 +1,46 @@
+"""Packing a workspace backup into a zip, optionally encrypted.
+
+The archive is the user's own copy of their data, so it stays a plain zip of
+plain JSON by default: anything that can open a zip can read it, today and in
+ten years. A password swaps the container for an AES-256 one (WinZip AES, the
+scheme 7-Zip, Keka and WinRAR all speak) so the file stays openable by ordinary
+tools while the contents travel safely through whatever cloud or drive the user
+keeps it on.
+
+AES rather than the legacy ZipCrypto that "password-protected zip" often means:
+ZipCrypto's key is recoverable from a few known plaintext bytes, and a backup
+full of JSON is nothing but known plaintext.
+"""
+import io
+import json
+import zipfile
+
+import pyzipper
+
+#: The zip encrypts entry *contents*, never the central directory, so the file
+#: names and their sizes stay readable without the password. Nothing sensitive
+#: goes in a name — they are the fixed entity names below plus `metadata.json`.
+_COMPRESSION = zipfile.ZIP_DEFLATED
+
+
+def build_backup_archive(files: dict[str, object], password: str | None = None) -> bytes:
+ """Serialize `files` (name → JSON-serializable payload) into a zip.
+
+ Returns the archive bytes. With a password the entries are encrypted with
+ AES-256; without one the result is byte-for-byte the plain zip Securo has
+ always produced.
+ """
+ buf = io.BytesIO()
+ if password:
+ archive = pyzipper.AESZipFile(
+ buf, "w", compression=_COMPRESSION, encryption=pyzipper.WZ_AES
+ )
+ archive.setpassword(password.encode("utf-8"))
+ else:
+ archive = zipfile.ZipFile(buf, "w", _COMPRESSION)
+
+ with archive as zf:
+ for name, payload in files.items():
+ zf.writestr(name, json.dumps(payload, indent=2, ensure_ascii=False))
+
+ return buf.getvalue()
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index b7380d5f..b76c5ac2 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -30,6 +30,10 @@ dependencies = [
"yfinance>=1.3.0",
"pgvector>=0.3.0",
"pypdf>=5.0.0",
+ # Password-protected backups. The stdlib zipfile can only *read* the
+ # legacy ZipCrypto scheme and cannot write an encrypted archive at all,
+ # so AES-256 zips need this fork of it.
+ "pyzipper>=0.4.0",
# Bundled multilingual embedder — only imported on demand by the
# agents knowledge-base path. ONNX runtime, ~120 MB model downloaded
# on first use to /app/data/embedding_models. Users not on the
diff --git a/backend/tests/test_export_api.py b/backend/tests/test_export_api.py
index e6d02630..89cd28fd 100644
--- a/backend/tests/test_export_api.py
+++ b/backend/tests/test_export_api.py
@@ -6,6 +6,7 @@ from datetime import date
from decimal import Decimal
import pytest
+import pyzipper
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
@@ -142,3 +143,63 @@ async def test_backup_metadata_structure(client: AsyncClient, auth_headers):
assert "export_date" in meta
assert meta["format_version"] == "1.0"
assert "entity_counts" in meta
+
+
+async def test_backup_post_without_password_is_a_plain_zip(client: AsyncClient, auth_headers):
+ """The password is optional: omitting it must not change the archive."""
+ resp = await client.post("/api/export/backup", json={}, headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.headers["content-type"] == "application/zip"
+
+ with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
+ assert "metadata.json" in zf.namelist()
+ assert json.loads(zf.read("metadata.json"))["format_version"] == "1.0"
+
+
+async def test_backup_post_with_password_encrypts_the_entries(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ resp = await client.post(
+ "/api/export/backup", json={"password": "correct horse battery"}, headers=auth_headers
+ )
+ assert resp.status_code == 200
+ assert resp.headers["content-type"] == "application/zip"
+
+ # Readable with the password, and the data really is in there.
+ with pyzipper.AESZipFile(io.BytesIO(resp.content)) as zf:
+ zf.setpassword(b"correct horse battery")
+ accounts = json.loads(zf.read("accounts.json"))
+ assert any(a["name"] == test_account.name for a in accounts)
+
+ # ...and unreadable without it, which is the whole point.
+ with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
+ assert "accounts.json" in zf.namelist()
+ with pytest.raises(RuntimeError):
+ zf.read("accounts.json")
+
+
+async def test_backup_post_rejects_the_wrong_password(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/export/backup", json={"password": "correct horse battery"}, headers=auth_headers
+ )
+
+ with pyzipper.AESZipFile(io.BytesIO(resp.content)) as zf:
+ zf.setpassword(b"wrong horse battery")
+ with pytest.raises(RuntimeError):
+ zf.read("metadata.json")
+
+
+async def test_backup_post_rejects_a_short_password(client: AsyncClient, auth_headers):
+ """Refused up front rather than written into an archive that looks safe."""
+ resp = await client.post("/api/export/backup", json={"password": "short"}, headers=auth_headers)
+ assert resp.status_code == 422
+
+
+async def test_backup_post_unauthenticated(client: AsyncClient):
+ resp = await client.post("/api/export/backup", json={"password": "correct horse battery"})
+ assert resp.status_code == 401
diff --git a/backend/tests/test_write_permission_coverage.py b/backend/tests/test_write_permission_coverage.py
index b5d73d9b..7268747e 100644
--- a/backend/tests/test_write_permission_coverage.py
+++ b/backend/tests/test_write_permission_coverage.py
@@ -71,6 +71,9 @@ ALLOWLIST: dict[tuple[str, str], str] = {
("DELETE", "/api/workspaces/{workspace_id}/members/{member_user_id}"): "owner floor inside the handler",
# Deliberate: a POST that persists nothing. See the comment on the route.
("POST", "/api/transactions/import/preview"): "parses an upload and returns a preview; writes nothing",
+ # A read that has to be a POST: the backup password belongs in a body,
+ # not in a query string. Same read permission as GET /api/export/backup.
+ ("POST", "/api/export/backup"): "exports the workspace it can already read; writes nothing",
# The agents surface, mounted only when AGENTS_ENABLED is on (the test
# suite turns it on so these are always covered). An LLM connection is
# the requester's own credential — scoped by `user.id`, never by
diff --git a/backend/uv.lock b/backend/uv.lock
index cbe6239c..ed9c5835 100644
--- a/backend/uv.lock
+++ b/backend/uv.lock
@@ -2060,6 +2060,36 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },
]
+[[package]]
+name = "pycryptodomex"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/85/e24bf90972a30b0fcd16c73009add1d7d7cd9140c2498a68252028899e41/pycryptodomex-3.23.0.tar.gz", hash = "sha256:71909758f010c82bc99b0abf4ea12012c98962fbf0583c2164f8b84533c2e4da", size = 4922157, upload-time = "2025-05-17T17:23:41.434Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/00/10edb04777069a42490a38c137099d4b17ba6e36a4e6e28bdc7470e9e853/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:7b37e08e3871efe2187bc1fd9320cc81d87caf19816c648f24443483005ff886", size = 2498764, upload-time = "2025-05-17T17:22:21.453Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/3f/2872a9c2d3a27eac094f9ceaa5a8a483b774ae69018040ea3240d5b11154/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:91979028227543010d7b2ba2471cf1d1e398b3f183cb105ac584df0c36dac28d", size = 1643012, upload-time = "2025-05-17T17:22:23.702Z" },
+ { url = "https://files.pythonhosted.org/packages/70/af/774c2e2b4f6570fbf6a4972161adbb183aeeaa1863bde31e8706f123bf92/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b8962204c47464d5c1c4038abeadd4514a133b28748bcd9fa5b6d62e3cec6fa", size = 2187643, upload-time = "2025-05-17T17:22:26.37Z" },
+ { url = "https://files.pythonhosted.org/packages/de/a3/71065b24cb889d537954cedc3ae5466af00a2cabcff8e29b73be047e9a19/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a33986a0066860f7fcf7c7bd2bc804fa90e434183645595ae7b33d01f3c91ed8", size = 2273762, upload-time = "2025-05-17T17:22:28.313Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/0b/ff6f43b7fbef4d302c8b981fe58467b8871902cdc3eb28896b52421422cc/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7947ab8d589e3178da3d7cdeabe14f841b391e17046954f2fbcd941705762b5", size = 2313012, upload-time = "2025-05-17T17:22:30.57Z" },
+ { url = "https://files.pythonhosted.org/packages/02/de/9d4772c0506ab6da10b41159493657105d3f8bb5c53615d19452afc6b315/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c25e30a20e1b426e1f0fa00131c516f16e474204eee1139d1603e132acffc314", size = 2186856, upload-time = "2025-05-17T17:22:32.819Z" },
+ { url = "https://files.pythonhosted.org/packages/28/ad/8b30efcd6341707a234e5eba5493700a17852ca1ac7a75daa7945fcf6427/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:da4fa650cef02db88c2b98acc5434461e027dce0ae8c22dd5a69013eaf510006", size = 2347523, upload-time = "2025-05-17T17:22:35.386Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/02/16868e9f655b7670dbb0ac4f2844145cbc42251f916fc35c414ad2359849/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:58b851b9effd0d072d4ca2e4542bf2a4abcf13c82a29fd2c93ce27ee2a2e9462", size = 2272825, upload-time = "2025-05-17T17:22:37.632Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/18/4ca89ac737230b52ac8ffaca42f9c6f1fd07c81a6cd821e91af79db60632/pycryptodomex-3.23.0-cp313-cp313t-win32.whl", hash = "sha256:a9d446e844f08299236780f2efa9898c818fe7e02f17263866b8550c7d5fb328", size = 1772078, upload-time = "2025-05-17T17:22:40Z" },
+ { url = "https://files.pythonhosted.org/packages/73/34/13e01c322db027682e00986873eca803f11c56ade9ba5bbf3225841ea2d4/pycryptodomex-3.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:bc65bdd9fc8de7a35a74cab1c898cab391a4add33a8fe740bda00f5976ca4708", size = 1803656, upload-time = "2025-05-17T17:22:42.139Z" },
+ { url = "https://files.pythonhosted.org/packages/54/68/9504c8796b1805d58f4425002bcca20f12880e6fa4dc2fc9a668705c7a08/pycryptodomex-3.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:c885da45e70139464f082018ac527fdaad26f1657a99ee13eecdce0f0ca24ab4", size = 1707172, upload-time = "2025-05-17T17:22:44.704Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/9c/1a8f35daa39784ed8adf93a694e7e5dc15c23c741bbda06e1d45f8979e9e/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:06698f957fe1ab229a99ba2defeeae1c09af185baa909a31a5d1f9d42b1aaed6", size = 2499240, upload-time = "2025-05-17T17:22:46.953Z" },
+ { url = "https://files.pythonhosted.org/packages/7a/62/f5221a191a97157d240cf6643747558759126c76ee92f29a3f4aee3197a5/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b2c2537863eccef2d41061e82a881dcabb04944c5c06c5aa7110b577cc487545", size = 1644042, upload-time = "2025-05-17T17:22:49.098Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/fd/5a054543c8988d4ed7b612721d7e78a4b9bf36bc3c5ad45ef45c22d0060e/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:43c446e2ba8df8889e0e16f02211c25b4934898384c1ec1ec04d7889c0333587", size = 2186227, upload-time = "2025-05-17T17:22:51.139Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/a9/8862616a85cf450d2822dbd4fff1fcaba90877907a6ff5bc2672cafe42f8/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f489c4765093fb60e2edafdf223397bc716491b2b69fe74367b70d6999257a5c", size = 2272578, upload-time = "2025-05-17T17:22:53.676Z" },
+ { url = "https://files.pythonhosted.org/packages/46/9f/bda9c49a7c1842820de674ab36c79f4fbeeee03f8ff0e4f3546c3889076b/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bdc69d0d3d989a1029df0eed67cc5e8e5d968f3724f4519bd03e0ec68df7543c", size = 2312166, upload-time = "2025-05-17T17:22:56.585Z" },
+ { url = "https://files.pythonhosted.org/packages/03/cc/870b9bf8ca92866ca0186534801cf8d20554ad2a76ca959538041b7a7cf4/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6bbcb1dd0f646484939e142462d9e532482bc74475cecf9c4903d4e1cd21f003", size = 2185467, upload-time = "2025-05-17T17:22:59.237Z" },
+ { url = "https://files.pythonhosted.org/packages/96/e3/ce9348236d8e669fea5dd82a90e86be48b9c341210f44e25443162aba187/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:8a4fcd42ccb04c31268d1efeecfccfd1249612b4de6374205376b8f280321744", size = 2346104, upload-time = "2025-05-17T17:23:02.112Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/e9/e869bcee87beb89040263c416a8a50204f7f7a83ac11897646c9e71e0daf/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:55ccbe27f049743a4caf4f4221b166560d3438d0b1e5ab929e07ae1702a4d6fd", size = 2271038, upload-time = "2025-05-17T17:23:04.872Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/67/09ee8500dd22614af5fbaa51a4aee6e342b5fa8aecf0a6cb9cbf52fa6d45/pycryptodomex-3.23.0-cp37-abi3-win32.whl", hash = "sha256:189afbc87f0b9f158386bf051f720e20fa6145975f1e76369303d0f31d1a8d7c", size = 1771969, upload-time = "2025-05-17T17:23:07.115Z" },
+ { url = "https://files.pythonhosted.org/packages/69/96/11f36f71a865dd6df03716d33bd07a67e9d20f6b8d39820470b766af323c/pycryptodomex-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:52e5ca58c3a0b0bd5e100a9fbc8015059b05cffc6c66ce9d98b4b45e023443b9", size = 1803124, upload-time = "2025-05-17T17:23:09.267Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/93/45c1cdcbeb182ccd2e144c693eaa097763b08b38cded279f0053ed53c553/pycryptodomex-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:02d87b80778c171445d67e23d1caef279bf4b25c3597050ccd2e13970b57fd51", size = 1707161, upload-time = "2025-05-17T17:23:11.414Z" },
+]
+
[[package]]
name = "pydantic"
version = "2.13.4"
@@ -2414,6 +2444,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
]
+[[package]]
+name = "pyzipper"
+version = "0.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pycryptodomex" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/8b/5a/548039b202f85fcdfbadaddde2f4182c6dbf7730bbe005b24f903ae886ee/pyzipper-0.4.0.tar.gz", hash = "sha256:a4b96afcac04c5589d5abdc6158dd362166374e3cc6810aa441e65f8a17cb9e3", size = 36780, upload-time = "2026-05-14T04:06:28.903Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/9a/db7b20df854ea3a7f25ee9d7bc31ff3ecce085843bcf4c06bd9c1dcc34e0/pyzipper-0.4.0-py3-none-any.whl", hash = "sha256:aa7b8a0fe741d67aac36ead85f6e735af107b72f84e0775f2ed565fc0d3a2f02", size = 36643, upload-time = "2026-05-14T04:06:27.332Z" },
+]
+
[[package]]
name = "redis"
version = "6.4.0"
@@ -2506,6 +2548,7 @@ dependencies = [
{ name = "pypdf" },
{ name = "python-jose", extra = ["cryptography"] },
{ name = "python-multipart" },
+ { name = "pyzipper" },
{ name = "redis", extra = ["hiredis"] },
{ name = "sqlalchemy" },
{ name = "uvicorn", extra = ["standard"] },
@@ -2551,6 +2594,7 @@ requires-dist = [
{ name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6.1" },
{ name = "python-jose", extras = ["cryptography"], specifier = ">=3.3.0" },
{ name = "python-multipart", specifier = ">=0.0.6" },
+ { name = "pyzipper", specifier = ">=0.4.0" },
{ name = "redis", extras = ["hiredis"], specifier = ">=5.0.0" },
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0,<0.16" },
{ name = "sqlalchemy", specifier = ">=2.0.0" },
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index a306877d..6f16dc09 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -8,9 +8,8 @@ import { useAuth } from '@/contexts/auth-context'
import { useCollectionFilter } from '@/contexts/collection-filter-context'
import { useWorkspace } from '@/contexts/workspace-context'
import { CollectionSelector } from '@/components/collection-selector'
-import { auth as authApi, backup as backupApi, admin as adminApi } from '@/lib/api'
+import { auth as authApi, admin as adminApi } from '@/lib/api'
import { resolveSupportedLang } from '@/lib/i18n'
-import { toast } from 'sonner'
import { OnboardingTour } from '@/components/onboarding-tour'
import { useTheme } from 'next-themes'
import { accounts as accountsApi } from '@/lib/api'
@@ -52,6 +51,7 @@ import {
} from 'lucide-react'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { ChangePasswordDialog } from '@/components/change-password-dialog'
+import { BackupDialog } from '@/components/backup-dialog'
import { TwoFactorSetup } from '@/components/two-factor-setup'
import { PasskeyManagementDialog } from '@/components/passkey-management-dialog'
import { CommandPalette } from '@/components/command-palette'
@@ -98,7 +98,7 @@ export function AppLayout() {
const [changePasswordOpen, setChangePasswordOpen] = useState(false)
const [twoFactorOpen, setTwoFactorOpen] = useState(false)
const [passkeysOpen, setPasskeysOpen] = useState(false)
- const [backingUp, setBackingUp] = useState(false)
+ const [backupOpen, setBackupOpen] = useState(false)
const [paletteOpen, setPaletteOpen] = useState(false)
const [chatOpen, setChatOpen] = useState(false)
const [updateDialogOpen, setUpdateDialogOpen] = useState(false)
@@ -260,18 +260,7 @@ export function AppLayout() {
onTwoFactor={() => setTwoFactorOpen(true)}
onPasskeys={() => setPasskeysOpen(true)}
agentsEnabled={agentsEnabled}
- backingUp={backingUp}
- onBackup={async () => {
- setBackingUp(true)
- try {
- await backupApi.download()
- toast.success(t('backup.success'))
- } catch {
- toast.error(t('backup.error'))
- } finally {
- setBackingUp(false)
- }
- }}
+ onBackup={() => setBackupOpen(true)}
dark
isAdmin={user?.is_superuser}
/>
@@ -501,21 +490,10 @@ export function AppLayout() {
account actions that used to live in a separate dropdown. */}
<div className="px-3 pt-1">
<WorkspaceSwitcher
- backingUp={backingUp}
onChangePassword={() => setChangePasswordOpen(true)}
onTwoFactor={() => setTwoFactorOpen(true)}
onPasskeys={() => setPasskeysOpen(true)}
- onBackup={async () => {
- setBackingUp(true)
- try {
- await backupApi.download()
- toast.success(t('backup.success'))
- } catch {
- toast.error(t('backup.error'))
- } finally {
- setBackingUp(false)
- }
- }}
+ onBackup={() => setBackupOpen(true)}
onUpdateAvailable={() => setUpdateDialogOpen(true)}
agentsEnabled={agentsEnabled}
/>
@@ -550,6 +528,7 @@ export function AppLayout() {
open={changePasswordOpen}
onClose={() => setChangePasswordOpen(false)}
/>
+ <BackupDialog open={backupOpen} onClose={() => setBackupOpen(false)} />
<TwoFactorSetup
open={twoFactorOpen}
onClose={() => setTwoFactorOpen(false)}
@@ -578,7 +557,6 @@ function UserMenu({
onTwoFactor,
onPasskeys,
onBackup,
- backingUp,
dark,
isAdmin,
agentsEnabled,
@@ -589,7 +567,6 @@ function UserMenu({
onTwoFactor: () => void
onPasskeys: () => void
onBackup: () => void
- backingUp: boolean
dark?: boolean
isAdmin?: boolean
agentsEnabled?: boolean
@@ -649,12 +626,11 @@ function UserMenu({
{t('auth.passkeysTitle')}
</DropdownMenuItem>
<DropdownMenuItem
- disabled={backingUp}
onClick={onBackup}
className="flex items-center gap-2"
>
<HardDriveDownload size={14} />
- {backingUp ? t('backup.downloading') : t('backup.button')}
+ {t('backup.button')}
</DropdownMenuItem>
{agentsEnabled && (
<DropdownMenuItem
diff --git a/frontend/src/components/backup-dialog.tsx b/frontend/src/components/backup-dialog.tsx
new file mode 100644
index 00000000..ef1826a9
--- /dev/null
+++ b/frontend/src/components/backup-dialog.tsx
@@ -0,0 +1,122 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { ShieldCheck } from 'lucide-react'
+import { backup as backupApi } from '@/lib/api'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+
+const MIN_PASSWORD_LENGTH = 8
+
+interface BackupDialogProps {
+ open: boolean
+ onClose: () => void
+}
+
+/**
+ * Asks for an optional password before downloading the workspace archive.
+ *
+ * Empty means the plain zip Securo has always produced. A password produces an
+ * AES-256 zip, which any standard archiver can open, so the backup stays usable
+ * even without Securo. Nothing about the password is sent anywhere else or
+ * stored: lose it and the archive is gone, which the dialog says out loud.
+ */
+export function BackupDialog({ open, onClose }: BackupDialogProps) {
+ const { t } = useTranslation()
+ const [password, setPassword] = useState('')
+ const [confirmPassword, setConfirmPassword] = useState('')
+ const [downloading, setDownloading] = useState(false)
+ const [error, setError] = useState('')
+
+ const handleClose = () => {
+ setPassword('')
+ setConfirmPassword('')
+ setError('')
+ onClose()
+ }
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError('')
+
+ if (password && password.length < MIN_PASSWORD_LENGTH) {
+ setError(t('backup.passwordTooShort', { min: MIN_PASSWORD_LENGTH }))
+ return
+ }
+ if (password !== confirmPassword) {
+ setError(t('setup.passwordMismatch'))
+ return
+ }
+
+ setDownloading(true)
+ try {
+ await backupApi.download(password || undefined)
+ toast.success(password ? t('backup.successEncrypted') : t('backup.success'))
+ handleClose()
+ } catch {
+ toast.error(t('backup.error'))
+ } finally {
+ setDownloading(false)
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('backup.dialogTitle')}</DialogTitle>
+ <DialogDescription>{t('backup.dialogDescription')}</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="backup-password">{t('backup.passwordLabel')}</Label>
+ <Input
+ id="backup-password"
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ autoComplete="new-password"
+ placeholder={t('backup.passwordPlaceholder')}
+ />
+ </div>
+ {password && (
+ <div className="space-y-2">
+ <Label htmlFor="backup-password-confirm">{t('setup.confirmPassword')}</Label>
+ <Input
+ id="backup-password-confirm"
+ type="password"
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ autoComplete="new-password"
+ />
+ </div>
+ )}
+ {password && (
+ <p className="flex items-start gap-2 rounded-md bg-muted p-3 text-xs text-muted-foreground">
+ <ShieldCheck size={14} className="mt-0.5 shrink-0" />
+ {t('backup.encryptionNote')}
+ </p>
+ )}
+ {error && <p className="text-sm text-destructive">{error}</p>}
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={downloading}>
+ {downloading ? t('backup.downloading') : t('backup.button')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/workspace-switcher.tsx b/frontend/src/components/workspace-switcher.tsx
index 10dc21c2..4405a0e9 100644
--- a/frontend/src/components/workspace-switcher.tsx
+++ b/frontend/src/components/workspace-switcher.tsx
@@ -71,8 +71,6 @@ function workspaceColor(w: Workspace): string {
}
interface AccountMenuProps {
- /** Backup download in progress — disables the menu item. */
- backingUp: boolean
/** Open the change-password dialog. */
onChangePassword: () => void
/** Open the 2FA setup dialog. */
@@ -97,7 +95,6 @@ interface AccountMenuProps {
* only needs to trigger them.
*/
export function WorkspaceSwitcher({
- backingUp,
onChangePassword,
onTwoFactor,
onPasskeys,
@@ -255,12 +252,11 @@ export function WorkspaceSwitcher({
{t('auth.passkeysTitle')}
</DropdownMenuItem>
<DropdownMenuItem
- disabled={backingUp}
onClick={onBackup}
className="flex items-center gap-2"
>
<HardDriveDownload size={14} />
- {backingUp ? t('backup.downloading') : t('backup.button')}
+ {t('backup.button')}
</DropdownMenuItem>
{agentsEnabled && (
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 2e63526b..b350fe4c 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1247,8 +1247,17 @@ export const settings = {
// Backup
export const backup = {
- download: async (): Promise<void> => {
- const { data } = await api.get('/export/backup', { responseType: 'blob' })
+ /**
+ * Download the workspace archive, encrypted with AES-256 when a password is
+ * given. POST rather than GET so the password stays out of browser history
+ * and proxy logs.
+ */
+ download: async (password?: string): Promise<void> => {
+ const { data } = await api.post(
+ '/export/backup',
+ password ? { password } : {},
+ { responseType: 'blob' },
+ )
const blob = new Blob([data], { type: 'application/zip' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 013b2ed2..d950b5e3 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -1509,7 +1509,14 @@
"button": "Backup",
"downloading": "Wird heruntergeladen...",
"success": "Backup erfolgreich heruntergeladen",
- "error": "Fehler beim Herunterladen des Backups"
+ "error": "Fehler beim Herunterladen des Backups",
+ "dialogTitle": "Backup herunterladen",
+ "dialogDescription": "Ein Zip mit allen Konten, Transaktionen und Regeln dieses Workspace, als reines JSON.",
+ "passwordLabel": "Passwort (optional)",
+ "passwordPlaceholder": "Leer lassen für ein unverschlüsseltes Backup",
+ "passwordTooShort": "Mindestens {{min}} Zeichen verwenden",
+ "encryptionNote": "Das Archiv wird mit AES-256 verschlüsselt und lässt sich mit jedem Packprogramm öffnen. Securo speichert dieses Passwort nicht und kann die Datei ohne es nicht wiederherstellen.",
+ "successEncrypted": "Verschlüsseltes Backup erfolgreich heruntergeladen"
},
"update": {
"title": "Server-Update",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 9eaebc36..da99eb85 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -1509,7 +1509,14 @@
"button": "Backup",
"downloading": "Downloading...",
"success": "Backup downloaded successfully",
- "error": "Failed to download backup"
+ "error": "Failed to download backup",
+ "dialogTitle": "Download backup",
+ "dialogDescription": "A zip with every account, transaction and rule in this workspace, as plain JSON.",
+ "passwordLabel": "Password (optional)",
+ "passwordPlaceholder": "Leave empty for an unencrypted backup",
+ "passwordTooShort": "Use at least {{min}} characters",
+ "encryptionNote": "The archive is encrypted with AES-256 and opens in any standard archiver. Securo does not store this password and cannot recover the file without it.",
+ "successEncrypted": "Encrypted backup downloaded successfully"
},
"update": {
"title": "Server update",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 4a645547..d902daea 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -1509,7 +1509,14 @@
"button": "Copia de seguridad",
"downloading": "Descargando...",
"success": "Copia de seguridad descargada correctamente",
- "error": "No se pudo descargar la copia de seguridad"
+ "error": "No se pudo descargar la copia de seguridad",
+ "dialogTitle": "Descargar copia de seguridad",
+ "dialogDescription": "Un zip con todas las cuentas, transacciones y reglas de este workspace, en JSON plano.",
+ "passwordLabel": "Contraseña (opcional)",
+ "passwordPlaceholder": "Déjalo vacío para una copia sin cifrar",
+ "passwordTooShort": "Usa al menos {{min}} caracteres",
+ "encryptionNote": "El archivo se cifra con AES-256 y se abre con cualquier compresor. Securo no guarda esta contraseña y no puede recuperar el archivo sin ella.",
+ "successEncrypted": "Copia de seguridad cifrada descargada correctamente"
},
"update": {
"title": "Actualización del servidor",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 03d33d50..65bd3164 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -1509,7 +1509,14 @@
"button": "Sauvegarde",
"downloading": "Téléchargement...",
"success": "Sauvegarde téléchargée avec succès",
- "error": "Échec du téléchargement de la sauvegarde"
+ "error": "Échec du téléchargement de la sauvegarde",
+ "dialogTitle": "Télécharger la sauvegarde",
+ "dialogDescription": "Un zip contenant tous les comptes, transactions et règles de cet espace, en JSON brut.",
+ "passwordLabel": "Mot de passe (facultatif)",
+ "passwordPlaceholder": "Laissez vide pour une sauvegarde non chiffrée",
+ "passwordTooShort": "Utilisez au moins {{min}} caractères",
+ "encryptionNote": "L'archive est chiffrée en AES-256 et s'ouvre avec n'importe quel logiciel d'archivage. Securo ne conserve pas ce mot de passe et ne peut pas récupérer le fichier sans lui.",
+ "successEncrypted": "Sauvegarde chiffrée téléchargée avec succès"
},
"update": {
"title": "Mise à jour du serveur",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index f6da448b..5adcb1b1 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -1509,7 +1509,14 @@
"button": "Backup",
"downloading": "Download...",
"success": "Backup scaricato con successo",
- "error": "Impossibile scaricare il backup"
+ "error": "Impossibile scaricare il backup",
+ "dialogTitle": "Scarica il backup",
+ "dialogDescription": "Uno zip con tutti i conti, le transazioni e le regole di questo workspace, in JSON semplice.",
+ "passwordLabel": "Password (facoltativa)",
+ "passwordPlaceholder": "Lascia vuoto per un backup non cifrato",
+ "passwordTooShort": "Usa almeno {{min}} caratteri",
+ "encryptionNote": "L'archivio è cifrato con AES-256 e si apre con qualsiasi programma di compressione. Securo non conserva questa password e non può recuperare il file senza di essa.",
+ "successEncrypted": "Backup cifrato scaricato con successo"
},
"update": {
"title": "Aggiornamento del server",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 0a19b71b..cc713ad9 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -1599,7 +1599,14 @@
"button": "Kopia zapasowa",
"downloading": "Pobieranie...",
"success": "Pomyślnie pobrano kopię zapasową",
- "error": "Nie udało się pobrać kopii zapasowej"
+ "error": "Nie udało się pobrać kopii zapasowej",
+ "dialogTitle": "Pobierz kopię zapasową",
+ "dialogDescription": "Zip ze wszystkimi kontami, transakcjami i regułami tego workspace, w czystym JSON.",
+ "passwordLabel": "Hasło (opcjonalne)",
+ "passwordPlaceholder": "Zostaw puste, aby pobrać kopię bez szyfrowania",
+ "passwordTooShort": "Użyj co najmniej {{min}} znaków",
+ "encryptionNote": "Archiwum jest szyfrowane AES-256 i otwiera się w dowolnym programie do archiwów. Securo nie przechowuje tego hasła i bez niego nie odzyska pliku.",
+ "successEncrypted": "Pomyślnie pobrano zaszyfrowaną kopię zapasową"
},
"update": {
"title": "Aktualizacja serwera",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 522775a0..a5f0eb52 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -1509,7 +1509,14 @@
"button": "Backup",
"downloading": "Baixando...",
"success": "Backup baixado com sucesso",
- "error": "Erro ao baixar backup"
+ "error": "Erro ao baixar backup",
+ "dialogTitle": "Baixar backup",
+ "dialogDescription": "Um zip com todas as contas, transações e regras deste workspace, em JSON puro.",
+ "passwordLabel": "Senha (opcional)",
+ "passwordPlaceholder": "Deixe em branco para um backup sem criptografia",
+ "passwordTooShort": "Use pelo menos {{min}} caracteres",
+ "encryptionNote": "O arquivo é criptografado com AES-256 e abre em qualquer compactador. O Securo não guarda essa senha e não consegue recuperar o arquivo sem ela.",
+ "successEncrypted": "Backup criptografado baixado com sucesso"
},
"update": {
"title": "Atualização do servidor",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 4a78b789..78f30211 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -1509,7 +1509,14 @@
"button": "Backup",
"downloading": "A transferir...",
"success": "Backup baixado com sucesso",
- "error": "Erro ao transferir backup"
+ "error": "Erro ao transferir backup",
+ "dialogTitle": "Transferir backup",
+ "dialogDescription": "Um zip com todas as contas, transações e regras deste workspace, em JSON simples.",
+ "passwordLabel": "Palavra-passe (opcional)",
+ "passwordPlaceholder": "Deixe vazio para um backup sem encriptação",
+ "passwordTooShort": "Use pelo menos {{min}} caracteres",
+ "encryptionNote": "O ficheiro é encriptado com AES-256 e abre em qualquer compactador. O Securo não guarda esta palavra-passe e não consegue recuperar o ficheiro sem ela.",
+ "successEncrypted": "Backup encriptado transferido com sucesso"
},
"update": {
"title": "Atualização do servidor",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 303c9d10..0d2ac708 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -1515,7 +1515,14 @@
"button": "Резервное копирование",
"downloading": "Загрузка...",
"success": "Резервная копия успешно загружена",
- "error": "Не удалось загрузить резервную копию"
+ "error": "Не удалось загрузить резервную копию",
+ "dialogTitle": "Скачать резервную копию",
+ "dialogDescription": "Zip со всеми счетами, транзакциями и правилами этого рабочего пространства в виде обычного JSON.",
+ "passwordLabel": "Пароль (необязательно)",
+ "passwordPlaceholder": "Оставьте пустым для копии без шифрования",
+ "passwordTooShort": "Используйте не менее {{min}} символов",
+ "encryptionNote": "Архив шифруется алгоритмом AES-256 и открывается любым архиватором. Securo не хранит этот пароль и не сможет восстановить файл без него.",
+ "successEncrypted": "Зашифрованная резервная копия успешно загружена"
},
"update": {
"title": "Обновление сервера",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 72f6b0e5..4764f84e 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -1515,7 +1515,14 @@
"button": "Резервне копіювання",
"downloading": "Завантаження...",
"success": "Резервну копію успішно завантажено",
- "error": "Не вдалося завантажити резервну копію"
+ "error": "Не вдалося завантажити резервну копію",
+ "dialogTitle": "Завантажити резервну копію",
+ "dialogDescription": "Zip з усіма рахунками, транзакціями та правилами цього робочого простору у вигляді звичайного JSON.",
+ "passwordLabel": "Пароль (необов'язково)",
+ "passwordPlaceholder": "Залиште порожнім для копії без шифрування",
+ "passwordTooShort": "Використайте щонайменше {{min}} символів",
+ "encryptionNote": "Архів шифрується алгоритмом AES-256 і відкривається будь-яким архіватором. Securo не зберігає цей пароль і не зможе відновити файл без нього.",
+ "successEncrypted": "Зашифровану резервну копію успішно завантажено"
},
"update": {
"title": "Оновлення сервера",