Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(security): encrypt local credentials and guide data migration

二丫讲梵250e0c0a10a7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1ecabc2819..dcff8fe449 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1194,6 +1194,11 @@ jobs:
working-directory: agents
steps:
- uses: actions/checkout@v7
+ - name: Install system dependencies
+ if: matrix.driver == 'duckdb'
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libdbus-1-dev pkg-config
- name: Setup Rust
uses: dtolnay/[email protected]
# Pin mold because runner image updates can change bundled DuckDB C++ links.
diff --git a/Cargo.lock b/Cargo.lock
index 42b27fffb8..3d3ad96b84 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2017,6 +2017,24 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "dbus-secret-service"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"
+dependencies = [
+ "aes 0.8.4",
+ "block-padding 0.3.3",
+ "cbc 0.1.2",
+ "dbus",
+ "fastrand",
+ "hkdf 0.12.4",
+ "num",
+ "once_cell",
+ "sha2 0.10.9",
+ "zeroize",
+]
+
[[package]]
name = "dbx"
version = "0.6.20"
@@ -2141,11 +2159,12 @@ dependencies = [
"font-kit",
"futures",
"jsonwebtoken",
+ "keyring",
"log",
"minijinja",
"mongodb",
"mysql_async",
- "nix",
+ "nix 0.31.3",
"notify",
"percent-encoding",
"portpicker",
@@ -2202,7 +2221,7 @@ dependencies = [
"mongodb",
"mysql_async",
"mysql_common",
- "nix",
+ "nix 0.31.3",
"openssl",
"pageant",
"percent-encoding",
@@ -2283,7 +2302,7 @@ name = "dbx-platform"
version = "0.1.0"
dependencies = [
"futures",
- "nix",
+ "nix 0.31.3",
"reqwest 0.12.28",
"serde",
"tokio",
@@ -2831,7 +2850,7 @@ dependencies = [
"crypto-bigint",
"crypto-common 0.2.2",
"digest 0.11.3",
- "hkdf",
+ "hkdf 0.13.0",
"hybrid-array",
"once_cell",
"pem-rfc7468 1.0.0",
@@ -4001,6 +4020,15 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac 0.12.1",
+]
+
[[package]]
name = "hkdf"
version = "0.13.0"
@@ -4814,6 +4842,23 @@ dependencies = [
"indexmap 2.14.0",
]
+[[package]]
+name = "keyring"
+version = "3.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
+dependencies = [
+ "byteorder",
+ "dbus-secret-service",
+ "linux-keyutils",
+ "log",
+ "secret-service",
+ "security-framework 2.11.1",
+ "security-framework 3.7.0",
+ "windows-sys 0.60.2",
+ "zeroize",
+]
+
[[package]]
name = "kqueue"
version = "1.2.0"
@@ -4963,6 +5008,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "linux-keyutils"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83270a18e9f90d0707c41e9f35efada77b64c0e6f3f1810e71c8368a864d5590"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -5512,6 +5567,19 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+[[package]]
+name = "nix"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+ "memoffset",
+]
+
[[package]]
name = "nix"
version = "0.31.3"
@@ -5578,6 +5646,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -5604,6 +5686,15 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -5629,6 +5720,17 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -7462,7 +7564,7 @@ dependencies = [
"getrandom 0.2.17",
"ghash 0.6.0",
"hex-literal",
- "hkdf",
+ "hkdf 0.13.0",
"hmac 0.12.1",
"hmac 0.13.0",
"inout 0.1.4",
@@ -7515,7 +7617,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37cb4d0360bdd8935392a306d8b5edb539cc455b30e8bf13dd213a0cf7879b40"
dependencies = [
"log",
- "nix",
+ "nix 0.31.3",
"ssh-encoding",
"windows-sys 0.61.2",
]
@@ -7945,6 +8047,25 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "secret-service"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"
+dependencies = [
+ "aes 0.8.4",
+ "cbc 0.1.2",
+ "futures-util",
+ "generic-array 0.14.7",
+ "hkdf 0.12.4",
+ "num",
+ "once_cell",
+ "rand 0.8.7",
+ "serde",
+ "sha2 0.10.9",
+ "zbus 4.4.0",
+]
+
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -8633,6 +8754,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "string_cache"
version = "0.9.0"
@@ -9135,7 +9262,7 @@ dependencies = [
"thiserror 2.0.19",
"url",
"windows 0.61.3",
- "zbus",
+ "zbus 5.18.0",
]
[[package]]
@@ -9182,7 +9309,7 @@ dependencies = [
"tokio",
"tracing",
"windows-sys 0.60.2",
- "zbus",
+ "zbus 5.18.0",
]
[[package]]
@@ -11453,6 +11580,16 @@ dependencies = [
"rustix",
]
+[[package]]
+name = "xdg-home"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "yeslogic-fontconfig-sys"
version = "6.0.1"
@@ -11487,6 +11624,38 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zbus"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"
+dependencies = [
+ "async-broadcast",
+ "async-process",
+ "async-recursion",
+ "async-trait",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "hex",
+ "nix 0.29.0",
+ "ordered-stream",
+ "rand 0.8.7",
+ "serde",
+ "serde_repr",
+ "sha1 0.10.7",
+ "static_assertions",
+ "tracing",
+ "uds_windows",
+ "windows-sys 0.52.0",
+ "xdg-home",
+ "zbus_macros 4.4.0",
+ "zbus_names 3.0.0",
+ "zvariant 4.2.0",
+]
+
[[package]]
name = "zbus"
version = "5.18.0"
@@ -11517,9 +11686,22 @@ dependencies = [
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
- "zbus_macros",
- "zbus_names",
- "zvariant",
+ "zbus_macros 5.18.0",
+ "zbus_names 4.3.4",
+ "zvariant 5.13.1",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zvariant_utils 2.1.0",
]
[[package]]
@@ -11532,9 +11714,20 @@ dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
- "zbus_names",
- "zvariant",
- "zvariant_utils",
+ "zbus_names 4.3.4",
+ "zvariant 5.13.1",
+ "zvariant_utils 3.5.0",
+]
+
+[[package]]
+name = "zbus_names"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"
+dependencies = [
+ "serde",
+ "static_assertions",
+ "zvariant 4.2.0",
]
[[package]]
@@ -11545,7 +11738,7 @@ checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
dependencies = [
"serde",
"winnow 1.0.4",
- "zvariant",
+ "zvariant 5.13.1",
]
[[package]]
@@ -11736,6 +11929,19 @@ dependencies = [
"zune-core",
]
+[[package]]
+name = "zvariant"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "static_assertions",
+ "zvariant_derive 4.2.0",
+]
+
[[package]]
name = "zvariant"
version = "5.13.1"
@@ -11746,8 +11952,21 @@ dependencies = [
"enumflags2",
"serde",
"winnow 1.0.4",
- "zvariant_derive",
- "zvariant_utils",
+ "zvariant_derive 5.13.1",
+ "zvariant_utils 3.5.0",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zvariant_utils 2.1.0",
]
[[package]]
@@ -11760,7 +11979,18 @@ dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
- "zvariant_utils",
+ "zvariant_utils 3.5.0",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
diff --git a/README.md b/README.md
index 5a2c4faf02..058b24d65e 100644
--- a/README.md
+++ b/README.md
@@ -346,7 +346,10 @@ DBX provides a web version that can be deployed via Docker. The examples use
the `latest` tag to pull the current release.
```bash
-docker run -d --pull=always --name dbx -p 4224:4224 -v dbx-data:/app/data t8y2/dbx:latest
+# The default keeps the key in the persistent /app/data volume.
+docker run -d --pull=always --name dbx -p 4224:4224 \
+ -v dbx-data:/app/data \
+ t8y2/dbx:latest
```
This uses the cross-platform `dbx-data` named volume. Users in China can use
@@ -375,10 +378,58 @@ services:
volumes:
dbx-data:
+
```
Open `http://localhost:4224` in your browser. Multi-arch images (amd64 / arm64) are available.
+Connection, plugin, AI, and tunnel credentials are encrypted before they are
+written to `dbx.db`. Desktop builds use the local platform credential store
+(macOS Keychain, Windows Credential Manager, or Linux Secret Service).
+Web/Docker and directly running `dbx-web` use the same managed data-directory
+key by default: `${DBX_DATA_DIR}/.dbx/secret.key`. The key is created only when
+migration starts or the first sensitive value is written, and must be backed up
+together with `dbx.db`. Persisting `/app/data` is therefore sufficient for a
+normal Docker deployment. This key protects the database contents, but cannot
+protect the whole data volume if the volume itself is copied or exposed.
+
+For production deployments, replace the managed key with a Docker/Kubernetes
+Secret by setting `DBX_SECRET_KEY_FILE`, or provide `DBX_SECRET_KEY` through a
+secret manager. Explicit keys take precedence and must never be rotated while
+encrypted data is in use. Without a usable key, business APIs remain blocked
+and the browser displays the data security upgrade screen.
+
+When running the binary directly, set `DBX_DATA_DIR=/var/lib/dbx` to use
+`/var/lib/dbx/.dbx/secret.key` with the same lifecycle and backup rules.
+
+When upgrading from a release that stored credentials in plain text, Desktop
+and Web display a **Data Security Upgrade** wizard before opening the main
+application. Choose **Start upgrade** to create a restricted backup, migrate
+legacy database/JSON credentials, and verify that encrypted values can be
+read. Failures retain the original data and backup; fix the issue shown in
+the wizard and choose **Retry**. The backup path is shown after success.
+Once you have verified your connections, **Delete migration backups** asks
+for confirmation and removes the migration backup directory and the legacy
+JSON `.bak` files created by that migration. Unrelated backup files are kept.
+Users with no legacy data proceed directly after the initial check.
+
+Local CLI and standalone MCP can reuse the existing platform credential
+store on the same device, or read an explicitly configured
+`DBX_SECRET_KEY_FILE`/`DBX_SECRET_KEY`. They do not create keys during the
+startup check or automatically migrate legacy data. A
+`DATA_MIGRATION_REQUIRED` error means that you must first open the same data
+directory in Desktop or Web and complete its upgrade wizard. For headless
+hosts without a platform credential store, configure the persistent key.
+
+Cross-device exports use a separate sync passphrase and never contain the
+local storage key. A direct `dbx.db` copy is not a cross-platform sync method:
+platform keys do not move with the database. Use encrypted export/import so
+the target device stores credentials using its own local key.
+
+For the complete design, migration state machine, implementation map,
+troubleshooting, and test plan, see
+[DBX Data Security Upgrade and Migration](docs/data-security-migration.md).
+
To publish DBX under a reverse-proxy context path such as `/dbx`, set the
runtime base path and proxy the same prefix to the container:
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 96c828d539..cac1e50cd9 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -353,7 +353,10 @@ flatpak install flatpark com.dbxio.dbx
DBX 提供 Web 版本,可通过 Docker 部署。示例使用 `latest` 标签以拉取当前发布版本。
```bash
-docker run -d --pull=always --name dbx -p 4224:4224 -v dbx-data:/app/data t8y2/dbx:latest
+# 默认将密钥保存在持久化的 /app/data 数据卷中。
+docker run -d --pull=always --name dbx -p 4224:4224 \
+ -v dbx-data:/app/data \
+ t8y2/dbx:latest
```
这里使用跨平台的 `dbx-data` 命名卷。中国大陆用户可选用 CNB 镜像
@@ -381,8 +384,21 @@ services:
volumes:
dbx-data:
+
```
+连接、插件、AI 和 Tunnel 凭据写入 `dbx.db` 前会加密。桌面端使用本机凭据存储(macOS Keychain、Windows Credential Manager 或 Linux Secret Service)。Web/Docker 与直接运行 `dbx-web` 默认使用同一套数据目录托管密钥:`${DBX_DATA_DIR}/.dbx/secret.key`。只有在开始迁移或第一次写入敏感字段时才创建密钥;普通 Docker 部署只需持久化 `/app/data`,并且必须将 `.dbx/secret.key` 与 `dbx.db` 一起备份。该密钥不能防护整个数据卷被复制或泄露。
+
+生产环境可以使用 Docker/Kubernetes Secret 覆盖托管策略:设置 `DBX_SECRET_KEY_FILE`,或由密钥管理系统提供 `DBX_SECRET_KEY`。显式密钥优先,已有密文使用期间不能轮换。密钥不可用时,业务 API 保持阻塞,浏览器显示数据安全升级页面。直接运行二进制时设置 `DBX_DATA_DIR=/var/lib/dbx`,即可使用 `/var/lib/dbx/.dbx/secret.key`。
+
+升级包含历史明文凭据的版本时,桌面端和 Web 会在进入主界面前显示 **数据安全升级向导**。点击 **开始迁移** 后,软件会创建权限受限的备份,迁移旧数据库和 JSON 凭据,并验证密文可读取。失败时保留原始数据和备份,根据向导提示修复后点击 **重试**。成功页面会显示备份路径。确认连接可用后,可点击 **删除迁移备份**,二次确认后删除迁移备份目录和本次迁移生成的旧 JSON `.bak` 文件;其他备份不会删除。没有历史数据的新用户检查后直接进入主界面。
+
+本机 CLI 和独立 MCP 可以复用同一设备已有的平台凭据存储,也可以读取显式配置的 `DBX_SECRET_KEY_FILE` 或 `DBX_SECRET_KEY`。它们不会在启动检查时创建密钥,也不会自动迁移历史数据。遇到 `DATA_MIGRATION_REQUIRED` 时,请先使用桌面端或 Web 打开同一数据目录,完成升级向导。没有平台凭据存储的无界面主机应配置持久化密钥。
+
+跨设备导出使用独立的同步口令,导出包不包含本地存储密钥。直接复制 `dbx.db` 不能作为跨平台同步方式,因为本机平台密钥不会随数据库移动。请使用加密导出/导入,让目标设备使用自己的本地密钥保存凭据。
+
+完整的设计、迁移状态、实现模块、排障和测试说明请参阅:[DBX 数据安全升级与迁移](docs/data-security-migration.zh-CN.md)。
+
如需通过 nginx 等反向代理发布到 `/dbx` 这类子路径下,设置运行时上下文路径,并将同一前缀代理到容器:
```yaml
diff --git a/agents/drivers/duckdb/Cargo.lock b/agents/drivers/duckdb/Cargo.lock
index f0da685a78..4870c15b38 100644
--- a/agents/drivers/duckdb/Cargo.lock
+++ b/agents/drivers/duckdb/Cargo.lock
@@ -341,6 +341,112 @@ dependencies = [
"regex-syntax",
]
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix 1.1.4",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix 1.1.4",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix 1.1.4",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
[[package]]
name = "async-trait"
version = "0.1.91"
@@ -529,6 +635,19 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "blocking"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
[[package]]
name = "blowfish"
version = "0.9.1"
@@ -807,6 +926,15 @@ dependencies = [
"unicode-width",
]
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "connection-string"
version = "0.2.0"
@@ -1222,6 +1350,35 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
+[[package]]
+name = "dbus"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "dbus-secret-service"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"
+dependencies = [
+ "aes 0.8.4",
+ "block-padding 0.3.3",
+ "cbc 0.1.2",
+ "dbus",
+ "fastrand",
+ "hkdf 0.12.4",
+ "num",
+ "once_cell",
+ "sha2 0.10.9",
+ "zeroize",
+]
+
[[package]]
name = "dbx-ai-provider"
version = "0.1.0"
@@ -1268,11 +1425,12 @@ dependencies = [
"flate2",
"futures",
"jsonwebtoken",
+ "keyring",
"log",
"minijinja",
"mongodb",
"mysql_async",
- "nix",
+ "nix 0.31.3",
"notify",
"percent-encoding",
"portpicker",
@@ -1388,7 +1546,7 @@ name = "dbx-platform"
version = "0.1.0"
dependencies = [
"futures",
- "nix",
+ "nix 0.31.3",
"reqwest",
"serde",
"tokio",
@@ -1755,7 +1913,7 @@ dependencies = [
"crypto-bigint",
"crypto-common 0.2.2",
"digest 0.11.3",
- "hkdf",
+ "hkdf 0.13.0",
"hybrid-array",
"once_cell",
"pem-rfc7468 1.0.0",
@@ -1777,6 +1935,12 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
[[package]]
name = "enum_dispatch"
version = "0.3.13"
@@ -1796,6 +1960,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
+ "serde",
]
[[package]]
@@ -1825,6 +1990,26 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
[[package]]
name = "fallible-iterator"
version = "0.2.0"
@@ -2020,6 +2205,19 @@ version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
[[package]]
name = "futures-macro"
version = "0.3.33"
@@ -2314,6 +2512,15 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac 0.12.1",
+]
+
[[package]]
name = "hkdf"
version = "0.13.0"
@@ -2852,6 +3059,23 @@ dependencies = [
"indexmap",
]
+[[package]]
+name = "keyring"
+version = "3.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
+dependencies = [
+ "byteorder",
+ "dbus-secret-service",
+ "linux-keyutils",
+ "log",
+ "secret-service",
+ "security-framework 2.11.1",
+ "security-framework 3.7.0",
+ "windows-sys 0.60.2",
+ "zeroize",
+]
+
[[package]]
name = "kqueue"
version = "1.2.0"
@@ -2944,6 +3168,15 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+[[package]]
+name = "libdbus-sys"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
+dependencies = [
+ "pkg-config",
+]
+
[[package]]
name = "libduckdb-sys"
version = "1.10505.0"
@@ -2986,6 +3219,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "linux-keyutils"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83270a18e9f90d0707c41e9f35efada77b64c0e6f3f1810e71c8368a864d5590"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -3148,6 +3391,15 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "minijinja"
version = "2.21.0"
@@ -3380,6 +3632,19 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+[[package]]
+name = "nix"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+ "memoffset",
+]
+
[[package]]
name = "nix"
version = "0.31.3"
@@ -3437,6 +3702,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -3497,6 +3776,17 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -3619,6 +3909,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
[[package]]
name = "p256"
version = "0.14.0-rc.7"
@@ -3680,6 +3980,12 @@ dependencies = [
"windows-strings",
]
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -3835,6 +4141,17 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
[[package]]
name = "pkcs1"
version = "0.8.0-rc.4"
@@ -3890,6 +4207,20 @@ version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix 1.1.4",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "poly1305"
version = "0.8.0"
@@ -4600,7 +4931,7 @@ dependencies = [
"getrandom 0.2.17",
"ghash 0.6.0",
"hex-literal",
- "hkdf",
+ "hkdf 0.13.0",
"hmac 0.12.1",
"hmac 0.13.0",
"inout 0.1.4",
@@ -4653,7 +4984,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37cb4d0360bdd8935392a306d8b5edb539cc455b30e8bf13dd213a0cf7879b40"
dependencies = [
"log",
- "nix",
+ "nix 0.31.3",
"ssh-encoding",
"windows-sys 0.61.2",
]
@@ -4955,6 +5286,25 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "secret-service"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"
+dependencies = [
+ "aes 0.8.4",
+ "cbc 0.1.2",
+ "futures-util",
+ "generic-array 0.14.7",
+ "hkdf 0.12.4",
+ "num",
+ "once_cell",
+ "rand 0.8.7",
+ "serde",
+ "sha2 0.10.9",
+ "zbus",
+]
+
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -5051,6 +5401,17 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -5393,6 +5754,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "stringprep"
version = "0.1.5"
@@ -6043,6 +6410,17 @@ version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "unicode-bidi"
version = "0.3.18"
@@ -6424,7 +6802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
dependencies = [
"windows-core 0.57.0",
- "windows-targets",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6457,7 +6835,7 @@ dependencies = [
"windows-implement 0.57.0",
"windows-interface 0.57.0",
"windows-result 0.1.2",
- "windows-targets",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6561,7 +6939,7 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
dependencies = [
- "windows-targets",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6588,7 +6966,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
- "windows-targets",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6597,7 +6975,16 @@ version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
- "windows-targets",
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
]
[[package]]
@@ -6615,14 +7002,31 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_gnullvm",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
]
[[package]]
@@ -6640,48 +7044,96 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
[[package]]
name = "winnow"
version = "1.0.4"
@@ -6734,6 +7186,16 @@ dependencies = [
"rustix 1.1.4",
]
+[[package]]
+name = "xdg-home"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -6757,6 +7219,62 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zbus"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"
+dependencies = [
+ "async-broadcast",
+ "async-process",
+ "async-recursion",
+ "async-trait",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "hex",
+ "nix 0.29.0",
+ "ordered-stream",
+ "rand 0.8.7",
+ "serde",
+ "serde_repr",
+ "sha1 0.10.7",
+ "static_assertions",
+ "tracing",
+ "uds_windows",
+ "windows-sys 0.52.0",
+ "xdg-home",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"
+dependencies = [
+ "serde",
+ "static_assertions",
+ "zvariant",
+]
+
[[package]]
name = "zerocopy"
version = "0.8.55"
@@ -6930,3 +7448,40 @@ dependencies = [
"cc",
"pkg-config",
]
+
+[[package]]
+name = "zvariant"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "static_assertions",
+ "zvariant_derive",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index fdb2f53a6f..296de3a0fe 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -95,6 +95,7 @@ import { parseConnectionDeepLink, parseConnectionDeepLinkUpdate, type Connection
import { resolveConnectionDeepLinkUpdate } from "@/lib/connection/connectionDeepLinkUpdate";
import { parseAiConfigDeepLink, type AiConfigDeepLinkDraft } from "@/lib/ai/aiConfigDeepLink";
import { activeDesktopAiRuns, blockingDesktopAiRunsForQuit } from "@/lib/ai/desktopAiRunRegistry";
+
import {
isBrowserReloadShortcut,
isCloseOtherTabsShortcut,
diff --git a/apps/desktop/src/StartupGate.vue b/apps/desktop/src/StartupGate.vue
new file mode 100644
index 0000000000..16812ff950
--- /dev/null
+++ b/apps/desktop/src/StartupGate.vue
@@ -0,0 +1,124 @@
+<script setup lang="ts">
+import { defineAsyncComponent, onMounted, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import LoginPage from "@/components/auth/LoginPage.vue";
+import SecurityMigrationWizard from "@/components/migration/SecurityMigrationWizard.vue";
+import { useMigrationStore } from "@/stores/migrationStore";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { apiUrl, webPath } from "@/lib/common/webPath";
+
+// App setup installs listeners and instantiates business stores, so even its import
+// is deferred until authentication and the security migration have completed.
+const App = defineAsyncComponent(() => import("./App.vue"));
+const { t } = useI18n();
+const migration = useMigrationStore();
+const { blocking } = migration;
+const checkingAuth = ref(true);
+const loginRequired = ref(false);
+const setupRequired = ref(false);
+const authFailed = ref(false);
+const enteringApp = ref(false);
+let launchTransitionTimer: number | undefined;
+
+watch(
+ () => migration.state.entered,
+ (entered) => {
+ if (entered) {
+ enteringApp.value = true;
+ }
+ },
+);
+
+function appReady() {
+ window.clearTimeout(launchTransitionTimer);
+ launchTransitionTimer = window.setTimeout(() => {
+ enteringApp.value = false;
+ }, 650);
+}
+async function initialize() {
+ checkingAuth.value = true;
+ authFailed.value = false;
+ try {
+ if (!isTauriRuntime()) {
+ const response = await fetch(apiUrl("/api/auth/check"), { credentials: "same-origin" });
+ if (!response.ok) throw new Error("AUTH_CHECK_FAILED");
+ const result = await response.json();
+ if (typeof result.required !== "boolean" || typeof result.authenticated !== "boolean") throw new Error("AUTH_CHECK_FAILED");
+ setupRequired.value = result.setup_required === true;
+ loginRequired.value = setupRequired.value || (result.required && !result.authenticated);
+ if (loginRequired.value) {
+ history.replaceState(null, "", webPath("/login"));
+ return;
+ }
+ }
+ await migration.initialize();
+ } catch {
+ authFailed.value = true;
+ } finally {
+ checkingAuth.value = false;
+ }
+}
+async function authenticated() {
+ history.replaceState(null, "", webPath("/"));
+ await initialize();
+}
+onMounted(initialize);
+</script>
+<template>
+ <div v-if="checkingAuth || authFailed" class="fixed inset-0 flex flex-col items-center justify-center gap-4 bg-background text-foreground" role="status">
+ <p>{{ t(authFailed ? "migration.authFailed" : "migration.checking") }}</p>
+ <button v-if="authFailed" class="rounded border px-4 py-2" @click="initialize">{{ t("migration.retry") }}</button>
+ </div>
+ <LoginPage v-else-if="loginRequired" :setup-mode="setupRequired" @authenticated="authenticated" />
+ <SecurityMigrationWizard v-else-if="blocking" :store="migration" />
+ <div v-else class="relative min-h-screen">
+ <Suspense @resolve="appReady">
+ <App />
+ </Suspense>
+ <Transition name="startup-fade">
+ <div v-if="enteringApp" class="fixed inset-0 z-[1100] flex items-center justify-center bg-background text-foreground" role="status" aria-live="polite">
+ <div class="flex flex-col items-center gap-5 text-center">
+ <span class="flex h-14 w-14 items-center justify-center rounded-full bg-primary/10 text-2xl text-primary" aria-hidden="true">✓</span>
+ <div>
+ <p class="text-lg font-semibold">{{ t("migration.successTitle") }}</p>
+ <p class="mt-2 text-sm text-muted-foreground">{{ t("migration.launching") }}</p>
+ </div>
+ <span class="h-1.5 w-24 overflow-hidden rounded-full bg-primary/15" aria-hidden="true"><span class="startup-progress block h-full w-1/2 rounded-full bg-primary" /></span>
+ </div>
+ </div>
+ </Transition>
+ </div>
+</template>
+
+<style scoped>
+.startup-fade-enter-active,
+.startup-fade-leave-active {
+ transition: opacity 280ms ease;
+}
+
+.startup-fade-enter-from,
+.startup-fade-leave-to {
+ opacity: 0;
+}
+
+.startup-progress {
+ animation: startup-progress 1.2s ease-in-out infinite;
+}
+
+@keyframes startup-progress {
+ from {
+ transform: translateX(-100%);
+ }
+
+ to {
+ transform: translateX(200%);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .startup-progress {
+ animation: none;
+ transform: translateX(50%);
+ }
+}
+</style>
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 44e71cd4b2..b8a197735b 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -4293,7 +4293,7 @@ async function testWebDav() {
async function uploadWebDavSnapshot() {
await runWebDavAction("upload", async () => {
- const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined);
+ const summary = await webdavSyncUpload(currentWebDavConfig(), settingsStore.editorSettings, webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
return t("settings.syncUploadSuccess", {
bytes: summary.bytes,
path: summary.remotePath,
@@ -4304,7 +4304,7 @@ async function uploadWebDavSnapshot() {
async function downloadWebDavSnapshot() {
if (!window.confirm(t("settings.syncDownloadConfirm"))) return;
await runWebDavAction("download", async () => {
- const result = await webdavSyncDownload(currentWebDavConfig(), webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined);
+ const result = await webdavSyncDownload(currentWebDavConfig(), webdavSyncSecrets.value ? webdavSecretsPassphrase.value : undefined, webdavSyncSecrets.value);
if (result.editorSettings && typeof result.editorSettings === "object") {
settingsStore.updateEditorSettings(result.editorSettings as any);
}
diff --git a/apps/desktop/src/components/migration/SecurityMigrationWizard.spec.ts b/apps/desktop/src/components/migration/SecurityMigrationWizard.spec.ts
new file mode 100644
index 0000000000..a90ba487ad
--- /dev/null
+++ b/apps/desktop/src/components/migration/SecurityMigrationWizard.spec.ts
@@ -0,0 +1,70 @@
+// @vitest-environment happy-dom
+import { createApp, nextTick } from "vue";
+import { describe, it, expect, vi } from "vitest";
+import { useMigrationStore } from "@/stores/migrationStore";
+import Wizard from "./SecurityMigrationWizard.vue";
+const mocks = vi.hoisted(() => ({ save: vi.fn().mockRejectedValue(new Error("unavailable")) }));
+vi.mock("@/lib/backend/api", () => ({}));
+vi.mock("@/i18n", () => ({ setLocale: vi.fn() }));
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key, locale: "en" }) }));
+vi.mock("@/lib/export/saveTextFile", () => ({ saveTextFile: mocks.save }));
+describe("migration failure actions", () => {
+ it("shows a redacted diagnostic even when file saving fails and routes status retries correctly", async () => {
+ const backend = { migrationStatus: vi.fn().mockRejectedValue(new Error("private transport detail")), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() };
+ const store = useMigrationStore(backend);
+ await store.initialize();
+ store.state.step = 2;
+ const root = document.createElement("div");
+ const app = createApp(Wizard, { store });
+ app.mount(root);
+ try {
+ const button = (label: string) => Array.from(root.querySelectorAll("button")).find((b) => b.textContent === label)!;
+ expect(root.querySelector("textarea")?.value).toContain("statusFailed");
+ button("migration.exportDiagnostic").click();
+ await nextTick();
+ await nextTick();
+ expect(mocks.save).toHaveBeenCalledWith(expect.any(String), "dbx-migration-diagnostic.json", "JSON", "json");
+ expect(root.querySelector("textarea")?.value).toContain("statusFailed");
+ expect(root.querySelector("textarea")?.value).not.toContain("private transport detail");
+ button("migration.retryStatus").click();
+ await nextTick();
+ expect(backend.migrationStatus).toHaveBeenCalledTimes(2);
+ expect(backend.migrationRetry).not.toHaveBeenCalled();
+ } finally {
+ app.unmount();
+ }
+ });
+
+ it("updates the visible diagnostic after a failed action refreshes migration status", async () => {
+ const pendingStatus = {
+ migrationId: "secret-store-v1",
+ state: "pending" as const,
+ needsMigration: true,
+ keyProviderAvailable: true,
+ databasePlaintextCount: 1,
+ connectionCount: 1,
+ pluginSecretCount: 0,
+ aiSecretCount: 0,
+ tunnelSecretCount: 0,
+ syncCredentialCount: 0,
+ legacyJsonFiles: [],
+ backupRequired: false,
+ };
+ const failedStatus = { ...pendingStatus, state: "failed" as const, errorCode: "LEGACY_JSON_INVALID", errorMessage: "Repair connections.json" };
+ const status = vi.fn().mockResolvedValueOnce(pendingStatus).mockResolvedValueOnce(failedStatus);
+ const backend = { migrationStatus: status, migrationStart: vi.fn().mockRejectedValue(new Error("request failed")), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() };
+ const store = useMigrationStore(backend);
+ await store.initialize();
+ const root = document.createElement("div");
+ const app = createApp(Wizard, { store });
+ app.mount(root);
+ try {
+ const start = Array.from(root.querySelectorAll("button")).find((button) => button.textContent === "migration.start")!;
+ start.click();
+ await vi.waitFor(() => expect(root.querySelector("textarea")?.value).toContain("LEGACY_JSON_INVALID"));
+ expect(root.querySelector("textarea")?.value).toContain('"state": "failed"');
+ } finally {
+ app.unmount();
+ }
+ });
+});
diff --git a/apps/desktop/src/components/migration/SecurityMigrationWizard.vue b/apps/desktop/src/components/migration/SecurityMigrationWizard.vue
new file mode 100644
index 0000000000..46f2a1eca0
--- /dev/null
+++ b/apps/desktop/src/components/migration/SecurityMigrationWizard.vue
@@ -0,0 +1,228 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import * as api from "@/lib/backend/api";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { setLocale, type Locale } from "@/i18n";
+import { LOCALE_OPTIONS } from "@/lib/app/localeOptions";
+import { saveTextFile } from "@/lib/export/saveTextFile";
+import type { useMigrationStore } from "@/stores/migrationStore";
+
+const props = defineProps<{ store: ReturnType<typeof useMigrationStore> }>();
+const { t, locale } = useI18n({ useScope: "global" });
+const status = computed(() => props.store.state.status);
+const confirmingCleanup = ref(false);
+const diagnosticText = computed(() => (props.store.state.error ? JSON.stringify(props.store.diagnostic(), null, 2) : ""));
+const exportingDiagnostic = ref(false);
+const canRevealPaths = computed(() => isTauriRuntime());
+const errorCode = computed(() => props.store.state.errorCode);
+const errorMessage = computed(() => props.store.state.errorMessage);
+const errorAdviceKey = computed(() => {
+ if (props.store.state.error === "cleanupFailed") return "migration.errors.cleanupAdvice";
+ switch (errorCode.value) {
+ case "MISSING_MANAGED_KEY":
+ case "MISSING_EXTERNAL_KEY":
+ case "MISSING_PERSISTENT_KEY":
+ return "migration.errors.persistentKeyAdvice";
+ case "ENCRYPTED_DATA_KEY_MISSING":
+ case "SECRET_KEY_INVALID":
+ case "SECRET_KEY_MISMATCH":
+ case "KEY_FILE_UNAVAILABLE":
+ case "KEY_PROVIDER_UNAVAILABLE":
+ return "migration.errors.keyProviderAdvice";
+ case "BACKUP_FAILED":
+ return "migration.errors.backupAdvice";
+ case "LEGACY_JSON_INVALID":
+ return "migration.errors.jsonAdvice";
+ case "VERIFICATION_FAILED":
+ return "migration.errors.verifyAdvice";
+ default:
+ return "migration.errors.genericAdvice";
+ }
+});
+function changeLocale(event: Event) {
+ const value = (event.target as HTMLSelectElement).value as Locale;
+ void setLocale(value);
+}
+async function exitApp() {
+ if (isTauriRuntime()) {
+ try {
+ await api.completeAppClose("quit");
+ return;
+ } catch {
+ /* browser fallback */
+ }
+ }
+ window.close();
+}
+async function revealPath(path: string | null | undefined) {
+ if (!path || !isTauriRuntime()) return;
+ try {
+ await api.revealPathInFileManager(path);
+ } catch {
+ /* the path stays visible so it can still be copied manually */
+ }
+}
+async function diagnostic() {
+ if (exportingDiagnostic.value) return;
+ exportingDiagnostic.value = true;
+ try {
+ await saveTextFile(diagnosticText.value, "dbx-migration-diagnostic.json", "JSON", "json");
+ } catch {
+ // Keep a selectable, redacted report visible even if native saving fails.
+ } finally {
+ exportingDiagnostic.value = false;
+ }
+}
+</script>
+<template>
+ <main class="fixed inset-0 z-[1000] flex items-center justify-center bg-background/95 p-6" role="dialog" aria-modal="true">
+ <section class="w-full max-w-2xl rounded-xl border bg-card p-8 shadow-2xl">
+ <div class="mb-8 flex items-start justify-between gap-4">
+ <div>
+ <p class="text-xs font-medium uppercase tracking-wider text-muted-foreground">{{ t("migration.eyebrow") }}</p>
+ <h1 class="mt-2 text-2xl font-semibold">{{ t("migration.title") }}</h1>
+ </div>
+ <label class="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
+ <span class="sr-only">{{ t("migration.language") }}</span>
+ <select class="h-8 rounded-md border bg-card px-2 text-xs text-foreground outline-none focus:ring-2 focus:ring-primary" :value="locale" :aria-label="t('migration.language')" @change="changeLocale">
+ <option v-for="option in LOCALE_OPTIONS" :key="option.value" :value="option.value">{{ option.flag }} {{ option.label }}</option>
+ </select>
+ </label>
+ </div>
+ <ol class="mb-8 grid grid-cols-3 gap-3" :aria-label="t('migration.stepsLabel')">
+ <li v-for="item in [1, 2, 3]" :key="item" class="flex min-w-0 items-center justify-center gap-2 text-center text-sm">
+ <span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-xs font-semibold" :class="item <= props.store.state.step ? 'border-primary bg-primary text-primary-foreground' : 'text-muted-foreground'">{{ item }}</span
+ ><span :class="item <= props.store.state.step ? 'font-medium' : 'text-muted-foreground'">{{ t(`migration.step${item}`) }}</span>
+ </li>
+ </ol>
+ <div v-if="props.store.state.loading" class="py-10 text-center text-sm text-muted-foreground">{{ t("migration.checking") }}</div>
+ <template v-else>
+ <div v-if="props.store.state.step === 1" class="space-y-5">
+ <p class="text-sm text-muted-foreground">{{ t("migration.intro") }}</p>
+ <div class="rounded-lg border border-primary/20 bg-primary/5 p-4 text-sm">
+ <h2 class="font-medium">{{ t("migration.whyTitle") }}</h2>
+ <p class="mt-2 text-muted-foreground">{{ t("migration.whyBody") }}</p>
+ <ul class="mt-3 list-disc space-y-1 pl-5 text-muted-foreground">
+ <li>{{ t("migration.whyItem1") }}</li>
+ <li>{{ t("migration.whyItem2") }}</li>
+ </ul>
+ </div>
+ <div v-if="status" class="grid gap-3 rounded-lg border p-4 text-sm sm:grid-cols-2">
+ <div>
+ <span class="text-muted-foreground">{{ t("migration.connectionCountLabel") }}</span> {{ status.connectionCount }}
+ </div>
+ <div>
+ <span class="text-muted-foreground">{{ t("migration.secretCountLabel") }}</span> {{ status.databasePlaintextCount }}
+ </div>
+ <div>
+ <span class="text-muted-foreground">{{ t("migration.backupRequiredLabel") }}</span> {{ status.backupRequired ? t("migration.yes") : t("migration.no") }}
+ </div>
+ <div>
+ <span class="text-muted-foreground">{{ t("migration.keyProviderLabel") }}</span> {{ status.persistentKeyConfigured ? t("migration.ready") : t("migration.pending") }}
+ </div>
+ </div>
+ <p v-if="status?.dataDir" class="break-all text-xs text-muted-foreground">
+ {{ t("migration.dataDir")
+ }}<!--
+ --><button
+ type="button"
+ class="break-all text-left underline decoration-dotted underline-offset-2 hover:text-foreground disabled:cursor-default disabled:no-underline"
+ :disabled="!canRevealPaths"
+ :title="canRevealPaths ? t('migration.openDataDir') : status.dataDir"
+ @click="revealPath(status.dataDir)"
+ >
+ {{ status.dataDir }}
+ </button>
+ </p>
+ <p v-if="status?.keyProviderAvailable === false && !status.keyCreationAllowed" class="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{{ t("migration.keyUnavailable") }}</p>
+ <p v-if="status?.keyFileConfigured === false && status?.persistentKeyConfigured === false && status?.keyCreationAllowed === false" class="text-xs text-muted-foreground">{{ t("migration.keyRecoveryHint") }}</p>
+ <div v-if="props.store.state.error" class="space-y-1 rounded-lg bg-destructive/10 p-4 text-sm text-destructive">
+ <p>{{ t(`migration.${props.store.state.error === "statusFailed" ? "statusFailed" : props.store.state.error === "cleanupFailed" ? "cleanupFailed" : "failed"}`) }}</p>
+ <p v-if="errorCode">{{ t("migration.errorCode", { code: errorCode }) }}</p>
+ <p v-if="errorMessage">{{ errorMessage }}</p>
+ <p>{{ t(errorAdviceKey) }}</p>
+ </div>
+ <div class="flex flex-wrap gap-3">
+ <button v-if="props.store.state.error === 'statusFailed' || (status?.keyProviderAvailable === false && !status?.keyCreationAllowed)" class="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50" :disabled="props.store.state.busy" @click="props.store.initialize">
+ {{ t("migration.retryStatus") }}</button
+ ><button
+ v-else
+ class="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
+ :disabled="props.store.state.busy || (status?.keyProviderAvailable === false && !status?.keyCreationAllowed)"
+ @click="status?.state === 'failed' ? props.store.retry() : props.store.start()"
+ >
+ {{ status?.state === "failed" ? t("migration.retryMigration") : t("migration.start") }}</button
+ ><button v-if="props.store.state.error" class="rounded-md border px-4 py-2" @click="diagnostic">{{ t("migration.exportDiagnostic") }}</button
+ ><button v-if="props.store.state.error && status?.dataDir && canRevealPaths" class="rounded-md border px-4 py-2" @click="revealPath(status.dataDir)">{{ t("migration.openDataDir") }}</button
+ ><button v-if="props.store.state.error" class="rounded-md border px-4 py-2" @click="exitApp">{{ t("migration.exit") }}</button>
+ </div>
+ </div>
+ <div v-else-if="props.store.state.step === 2" class="space-y-5">
+ <div class="rounded-lg border p-5" :class="props.store.state.error ? 'border-destructive/40' : 'border-primary/30'">
+ <div class="flex items-center gap-3">
+ <span class="h-3 w-3 rounded-full" :class="props.store.state.busy ? 'animate-pulse bg-primary' : 'bg-destructive'" />
+ <h2 class="font-medium">{{ props.store.state.error === "statusFailed" ? t("migration.statusFailed") : props.store.state.error ? t("migration.failed") : t("migration.running") }}</h2>
+ </div>
+ <p v-if="errorCode" class="mt-3 text-sm">{{ t("migration.errorCode", { code: errorCode }) }}</p>
+ <p v-if="errorMessage" class="mt-2 text-sm">{{ errorMessage }}</p>
+ <p class="mt-3 text-sm text-muted-foreground">{{ props.store.state.error ? t(errorAdviceKey) : t("migration.progress") }}</p>
+ </div>
+ <div v-if="props.store.state.error" class="flex flex-wrap gap-3">
+ <button class="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50" :disabled="props.store.state.busy" @click="props.store.state.error === 'statusFailed' ? props.store.initialize() : props.store.retry()">
+ {{ props.store.state.busy ? t("migration.running") : props.store.state.error === "statusFailed" ? t("migration.retryStatus") : t("migration.retryMigration") }}</button
+ ><button class="rounded-md border px-4 py-2 disabled:opacity-50" :disabled="props.store.state.busy" @click="diagnostic">{{ t("migration.exportDiagnostic") }}</button
+ ><button class="rounded-md border px-4 py-2 disabled:opacity-50" :disabled="props.store.state.busy" @click="exitApp">{{ t("migration.exit") }}</button>
+ </div>
+ </div>
+ <div v-else class="space-y-5">
+ <div class="rounded-lg border border-primary/30 bg-primary/5 p-5">
+ <h2 class="font-medium">{{ t("migration.successTitle") }}</h2>
+ <p class="mt-2 text-sm text-muted-foreground">{{ t("migration.successIntro") }}</p>
+ <p v-if="status?.backupPath" class="mt-3 break-all text-xs text-muted-foreground">
+ {{ t("migration.backupPath")
+ }}<!--
+ --><button
+ type="button"
+ class="break-all text-left underline decoration-dotted underline-offset-2 hover:text-foreground disabled:cursor-default disabled:no-underline"
+ :disabled="!canRevealPaths"
+ :title="canRevealPaths ? t('migration.openBackupDir') : status.backupPath"
+ @click="revealPath(status.backupPath)"
+ >
+ {{ status.backupPath }}
+ </button>
+ </p>
+ </div>
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <button class="rounded-md bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50" :disabled="props.store.state.busy" @click="props.store.enter">{{ t("migration.enter") }}</button
+ ><button v-if="status?.backupPath && props.store.state.error !== 'cleanupFailed'" class="text-xs text-muted-foreground underline underline-offset-2 hover:text-destructive disabled:opacity-50" :disabled="props.store.state.busy" @click="confirmingCleanup = true">
+ {{ t("migration.deleteBackup") }}
+ </button>
+ </div>
+ <div v-if="confirmingCleanup" class="rounded border p-4 text-sm">
+ <p>{{ t("migration.confirmDelete") }}</p>
+ <div class="mt-3 flex gap-2">
+ <button
+ class="rounded border border-destructive bg-card px-3 py-1 text-destructive hover:bg-destructive/10"
+ @click="
+ confirmingCleanup = false;
+ props.store.cleanup();
+ "
+ >
+ {{ t("migration.confirm") }}</button
+ ><button class="rounded border px-3 py-1" @click="confirmingCleanup = false">{{ t("migration.cancel") }}</button>
+ </div>
+ </div>
+ <div v-if="props.store.state.error === 'cleanupFailed'" class="space-y-3" role="alert">
+ <p class="text-sm text-destructive">{{ t("migration.cleanupFailed") }} {{ t("migration.errors.cleanupAdvice") }}</p>
+ <button class="rounded-md border px-4 py-2 disabled:opacity-50" :disabled="props.store.state.busy" @click="props.store.cleanup">{{ t("migration.retryCleanup") }}</button>
+ </div>
+ </div>
+ <div v-if="diagnosticText" class="mt-4 space-y-2">
+ <p class="text-sm font-medium">{{ t("migration.exportDiagnostic") }}</p>
+ <textarea readonly :value="diagnosticText" :aria-label="t('migration.exportDiagnostic')" class="h-40 w-full rounded border bg-background p-3 font-mono text-xs" />
+ </div>
+ </template>
+ </section>
+ </main>
+</template>
diff --git a/apps/desktop/src/composables/useWebDavAutoUpload.ts b/apps/desktop/src/composables/useWebDavAutoUpload.ts
index b318938581..6f50b57e28 100644
--- a/apps/desktop/src/composables/useWebDavAutoUpload.ts
+++ b/apps/desktop/src/composables/useWebDavAutoUpload.ts
@@ -1,7 +1,7 @@
import { onMounted, onUnmounted } from "vue";
import { useSettingsStore } from "@/stores/settingsStore";
import { appendDebugLog } from "@/lib/backend/debugLog";
-import { webdavSyncUpload } from "@/lib/backend/api";
+import { webdavSyncSecretsStatus, webdavSyncUpload } from "@/lib/backend/api";
import { readWebDavAutoUploadConfig, WEB_DAV_AUTO_UPLOAD_STORAGE_KEYS } from "@/lib/webdav/webdavAutoUploadConfig";
export function useWebDavAutoUpload() {
@@ -32,7 +32,8 @@ export function useWebDavAutoUpload() {
uploading = true;
try {
- const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings);
+ const secretsStatus = await webdavSyncSecretsStatus();
+ const summary = await webdavSyncUpload(config.webDavConfig, settingsStore.editorSettings, undefined, secretsStatus.enabled && secretsStatus.hasSavedPassphrase);
appendDebugLog("info", "[DBX][webdav:auto-upload:success]", {
bytes: summary.bytes,
remotePath: summary.remotePath,
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index f679bad640..2d568ce287 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -10259,4 +10259,67 @@ export default withEnglishFallback({
titleLabel: "Başlıq (istəyə bağlı)",
titlePlaceholder: "Məsələn, sorğu nəticəsi",
},
+ migration: {
+ eyebrow: "Yeniləmədən sonra ilk açılış",
+ title: "Məlumat təhlükəsizliyi yeniləməsi",
+ stepsLabel: "Köçürmə addımları",
+ language: "Dil",
+ step1: "Yoxla və təsdiqlə",
+ step2: "Məlumatları köçür",
+ step3: "Tamamla və ehtiyat nüsxə",
+ successTitle: "Köçürmə tamamlandı",
+ connectionCountLabel: "Bağlantılar:",
+ secretCountLabel: "Qorunan elementlər:",
+ backupRequiredLabel: "Ehtiyat nüsxə:",
+ keyProviderLabel: "Açar vəziyyəti:",
+ ready: "hazır",
+ pending: "qurulmalıdır",
+ intro: "DBX-i yeniləyib yenidən başlatdınız. Bu yeniləmə yerli məlumatların təhlükəsizliyini artırır. Bir dəfəlik prosesi tamamladıqdan sonra bağlantılardan istifadə edə bilərsiniz.",
+ whyTitle: "Bu yeniləmə nə edir?",
+ whyBody: "Yeni versiya bağlantıları, plaginləri və digər həssas ayarları daha güclü şifrələmə ilə qoruyur. Bu proses yalnız bir dəfə işləyəcək.",
+ whyItem1: "Başlamazdan əvvəl ehtiyat nüsxə yaradılır.",
+ whyItem2: "Tamamlanmadan əvvəl nəticə yoxlanılır.",
+ connectionCount: "Bağlantılar: {count}",
+ secretCount: "Qorunan elementlər: {count}",
+ backupPath: "Ehtiyat nüsxə:",
+ dataDir: "Məlumat qovluğu:",
+ backupDir: "Ehtiyat qovluğu:",
+ yes: "bəli",
+ no: "xeyr",
+ keyFileStatus: "Açar faylı: {configured}; oxunaqlıdır: {readable}",
+ persistentKeyStatus: "Davamlı açar təminatçısı: {available}",
+ keyUnavailable: "Cihaz açarı əlçatan deyil. Açar zəncirinə girişə icazə verin və ya davamlı açar qurun.",
+ keyRecoveryHint: "Bu məlumat qovluğu üçün istifadə olunan orijinal açarı bərpa edin və ya mövcud məlumatları şifrələyən eyni xarici açarı konfiqurasiya edin. Onu yeni açarla əvəz etməyin.",
+ progress: "Ehtiyat nüsxə yaradılır, köçürülür və yoxlanılır…",
+ failed: "Köçürmə tamamlanmadı. İlkin məlumatlar saxlanıldı.",
+ cleanupFailed: "Köçürmə tamamlandı, lakin ehtiyat nüsxə silinmədi.",
+ retryCleanup: "Silməni yenidən yoxla",
+ statusFailed: "Köçürmə vəziyyəti yoxlanıla bilmədi.",
+ errorCode: "Xəta kodu: {code}",
+ retryStatus: "Vəziyyəti yenidən yoxla",
+ start: "Köçürməni başlat",
+ running: "Köçürülür…",
+ retryMigration: "Köçürməni yenidən yoxla",
+ enter: "DBX-ə daxil ol",
+ deleteBackup: "Ehtiyat nüsxəni sil",
+ exportDiagnostic: "Diaqnostikanı ixrac et",
+ openDataDir: "Məlumat qovluğunu aç",
+ exit: "DBX-dən çıx",
+ confirmDelete: "Köçürmə ehtiyat nüsxəsi silinsin?",
+ confirm: "Sil",
+ cancel: "Ləğv et",
+ checking: "Yerli məlumat təhlükəsizliyi yoxlanılır…",
+ authFailed: "DBX autentifikasiyası yoxlanıla bilmədi.",
+ retry: "Yenidən yoxla",
+ successIntro: "Köçürmə və yoxlama tamamlandı. Ehtiyat nüsxəni silməzdən əvvəl bağlantıları yoxlayın.",
+ errors: {
+ persistentKeyAdvice: "Davamlı açar qurun və vəziyyəti yenidən yoxlayın.",
+ cleanupAdvice: "Ehtiyat qovluğunun icazələrini yoxlayın və yenidən cəhd edin.",
+ genericAdvice: "Problemi həll edib yenidən cəhd edin.",
+ keyProviderAdvice: "Açar zəncirinə girişə icazə verin və ya davamlı açar faylı qurun.",
+ backupAdvice: "Məlumat qovluğunun yazıla bildiyini və boş yer olduğunu yoxlayın.",
+ jsonAdvice: "Göstərilən faylı düzəldib yenidən cəhd edin.",
+ verifyAdvice: "Yoxlama uğurlu olana qədər ehtiyat nüsxəni saxlayın.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 77fbf2a581..0b5b52b092 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -10874,4 +10874,69 @@ export default {
titleLabel: "Title (optional)",
titlePlaceholder: "e.g. Query result",
},
+ migration: {
+ eyebrow: "First launch after upgrade",
+ title: "Data security upgrade",
+ stepsLabel: "Migration steps",
+ language: "Language",
+ step1: "Review and confirm",
+ step2: "Migrate data",
+ step3: "Complete and backup",
+ successTitle: "Migration completed",
+ connectionCountLabel: "Connections: ",
+ secretCountLabel: "Sensitive items: ",
+ backupRequiredLabel: "Backup required: ",
+ keyProviderLabel: "Key status: ",
+ ready: "ready",
+ pending: "needs setup",
+ intro: "You have just upgraded and restarted DBX. This upgrade improves local data security; complete this one-time step to continue using your connections.",
+ whyTitle: "What does this upgrade do?",
+ whyBody: "The new version uses stronger encryption to protect connections, plugins, and other sensitive settings. This step runs once after the upgrade and will not appear again.",
+ whyItem1: "A backup is created before the upgrade so your data can be recovered if needed.",
+ whyItem2: "The result is verified before completion to confirm the security upgrade succeeded.",
+ successIntro: "Migration completed and ciphertext verification passed. Check your connections before deleting the backup.",
+ connectionCount: "Connections: {count}",
+ secretCount: "Sensitive items to migrate: {count}",
+ backupPath: "Backup: ",
+ dataDir: "Data directory: ",
+ backupDir: "Backup directory: ",
+ keyFileStatus: "Configured key file: {configured}; readable: {readable}",
+ persistentKeyStatus: "Persistent key provider available: {available}",
+ yes: "yes",
+ no: "no",
+ keyUnavailable: "The device key is unavailable. Allow keychain access or configure a persistent key.",
+ keyRecoveryHint: "Restore the original key used for this data directory, or configure the same external key that encrypted the existing data. Do not replace it with a new key.",
+ progress: "Creating backup, migrating, and verifying. Do not close DBX…",
+ failed: "Migration did not complete. Original data has been retained.",
+ cleanupFailed: "Migration completed, but the backup could not be deleted.",
+ retryCleanup: "Retry deleting backup",
+ statusFailed: "Unable to check migration status.",
+ errorCode: "Error code: {code}",
+ retryStatus: "Retry status check",
+ start: "Start migration",
+ running: "Migrating…",
+ retryMigration: "Retry migration",
+ enter: "Enter DBX",
+ launching: "Starting DBX…",
+ deleteBackup: "Delete backup",
+ exportDiagnostic: "Export redacted diagnostics",
+ openDataDir: "Open data directory",
+ openBackupDir: "Open backup location",
+ exit: "Exit DBX",
+ confirmDelete: "Delete this upgrade backup? Your connections and passwords are already stored on this device, so removing the backup does not delete your connection list or passwords, but you can no longer use it to roll back this upgrade.",
+ confirm: "Delete",
+ cancel: "Cancel",
+ errors: {
+ persistentKeyAdvice: "Configure DBX_SECRET_KEY_FILE or DBX_SECRET_KEY with a persistent key, then retry the status check.",
+ cleanupAdvice: "Check backup directory permissions and retry deleting the backup. Your migrated data is ready to use.",
+ genericAdvice: "Fix the issue above and retry. Your original data is still available.",
+ keyProviderAdvice: "Allow DBX to access the keychain or provide a persistent DBX_SECRET_KEY_FILE.",
+ backupAdvice: "Check that the data directory is writable and has enough free space.",
+ jsonAdvice: "Repair the reported legacy JSON file, then retry the migration.",
+ verifyAdvice: "Keep the backup and retry. Do not delete migration backups until verification succeeds.",
+ },
+ checking: "Checking local data security status…",
+ authFailed: "Unable to check DBX authentication.",
+ retry: "Retry",
+ },
};
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index b2a53f0b15..1aa1383a15 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -10352,6 +10352,71 @@ export default withEnglishFallback({
titleLabel: "Título (opcional)",
titlePlaceholder: "p. ej. Resultado de consulta",
},
+ migration: {
+ eyebrow: "Primer inicio tras la actualización",
+ title: "Actualización de seguridad de datos",
+ stepsLabel: "Pasos de migración",
+ language: "Idioma",
+ step1: "Revisar y confirmar",
+ step2: "Migrar datos",
+ step3: "Finalizar y guardar copia",
+ successTitle: "Migración completada",
+ connectionCountLabel: "Conexiones:",
+ secretCountLabel: "Elementos protegidos:",
+ backupRequiredLabel: "Copia de seguridad:",
+ keyProviderLabel: "Estado de la clave:",
+ ready: "lista",
+ pending: "pendiente",
+ intro: "Acabas de actualizar y reiniciar DBX. Esta actualización mejora la seguridad de los datos locales. Completa este proceso único para seguir usando tus conexiones.",
+ whyTitle: "¿Qué hace esta actualización?",
+ whyBody: "La nueva versión usa un cifrado más sólido para proteger conexiones, plugins y otros ajustes sensibles. Este proceso se ejecuta una sola vez.",
+ whyItem1: "Se crea una copia de seguridad antes de empezar.",
+ whyItem2: "El resultado se verifica antes de finalizar.",
+ connectionCount: "Conexiones: {count}",
+ secretCount: "Elementos protegidos: {count}",
+ backupPath: "Copia de seguridad:",
+ dataDir: "Directorio de datos:",
+ backupDir: "Directorio de copias:",
+ yes: "sí",
+ no: "no",
+ keyFileStatus: "Archivo de clave configurado: {configured}; legible: {readable}",
+ persistentKeyStatus: "Proveedor de clave persistente: {available}",
+ keyUnavailable: "La clave del dispositivo no está disponible. Permite el acceso al llavero o configura una clave persistente.",
+ keyRecoveryHint: "Restaura la clave original usada por este directorio de datos o configura la misma clave externa que cifró los datos existentes. No la reemplaces por una clave nueva.",
+ progress: "Creando copia, migrando y verificando…",
+ failed: "La migración no se completó. Los datos originales se conservaron.",
+ cleanupFailed: "La migración terminó, pero no se pudo eliminar la copia.",
+ retryCleanup: "Reintentar eliminación",
+ statusFailed: "No se pudo comprobar el estado de la migración.",
+ errorCode: "Código de error: {code}",
+ retryStatus: "Reintentar comprobación",
+ start: "Iniciar migración",
+ running: "Migrando…",
+ retryMigration: "Reintentar migración",
+ enter: "Entrar en DBX",
+ deleteBackup: "Eliminar copia",
+ exportDiagnostic: "Exportar diagnóstico",
+ openDataDir: "Abrir directorio de datos",
+ exit: "Salir de DBX",
+ confirmDelete: "¿Eliminar la copia de migración?",
+ confirm: "Eliminar",
+ cancel: "Cancelar",
+ checking: "Comprobando la seguridad de los datos locales…",
+ authFailed: "No se pudo comprobar la autenticación de DBX.",
+ retry: "Reintentar",
+ successIntro: "La migración y la verificación terminaron. Comprueba las conexiones antes de eliminar la copia.",
+ errors: {
+ persistentKeyAdvice: "Configura una clave persistente y vuelve a comprobar el estado.",
+ cleanupAdvice: "Comprueba los permisos del directorio y vuelve a intentarlo.",
+ genericAdvice: "Soluciona el problema y vuelve a intentarlo.",
+ keyProviderAdvice: "Permite el acceso al llavero o configura un archivo de clave persistente.",
+ backupAdvice: "Comprueba que el directorio permite escribir y tiene espacio suficiente.",
+ jsonAdvice: "Repara el archivo indicado y vuelve a intentarlo.",
+ verifyAdvice: "Conserva la copia hasta que la verificación sea correcta.",
+ },
+ launching: "Iniciando DBX…",
+ openBackupDir: "Abrir ubicación de copia de seguridad",
+ },
solrAdmin: {
title: "Administración de Solr",
refresh: "Actualizar",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index c6e39b5461..22c7138408 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -10352,6 +10352,71 @@ export default withEnglishFallback({
titleLabel: "Titolo (facoltativo)",
titlePlaceholder: "es. Risultato della query",
},
+ migration: {
+ eyebrow: "Primo avvio dopo l'aggiornamento",
+ title: "Aggiornamento della sicurezza dei dati",
+ stepsLabel: "Passaggi della migrazione",
+ language: "Lingua",
+ step1: "Controlla e conferma",
+ step2: "Migra dati",
+ step3: "Completa e crea backup",
+ successTitle: "Migrazione completata",
+ connectionCountLabel: "Connessioni:",
+ secretCountLabel: "Elementi protetti:",
+ backupRequiredLabel: "Backup:",
+ keyProviderLabel: "Stato della chiave:",
+ ready: "pronta",
+ pending: "da configurare",
+ intro: "Hai appena aggiornato e riavviato DBX. Questo aggiornamento migliora la sicurezza dei dati locali. Completa questa operazione una sola volta per continuare a usare le connessioni.",
+ whyTitle: "Cosa comporta questo aggiornamento?",
+ whyBody: "La nuova versione usa una crittografia più forte per proteggere connessioni, plugin e altre impostazioni sensibili. L'operazione viene eseguita una sola volta.",
+ whyItem1: "Prima dell'avvio viene creato un backup.",
+ whyItem2: "Il risultato viene verificato prima del completamento.",
+ connectionCount: "Connessioni: {count}",
+ secretCount: "Elementi protetti: {count}",
+ backupPath: "Backup:",
+ dataDir: "Directory dati:",
+ backupDir: "Directory backup:",
+ yes: "sì",
+ no: "no",
+ keyFileStatus: "File chiave configurato: {configured}; leggibile: {readable}",
+ persistentKeyStatus: "Provider di chiavi persistenti: {available}",
+ keyUnavailable: "La chiave del dispositivo non è disponibile. Consenti l'accesso al portachiavi o configura una chiave persistente.",
+ keyRecoveryHint: "Ripristina la chiave originale usata da questa directory dati oppure configura la stessa chiave esterna che ha cifrato i dati esistenti. Non sostituirla con una nuova chiave.",
+ progress: "Creazione del backup, migrazione e verifica in corso…",
+ failed: "Migrazione non completata. I dati originali sono stati conservati.",
+ cleanupFailed: "Migrazione completata, ma il backup non è stato eliminato.",
+ retryCleanup: "Riprova eliminazione",
+ statusFailed: "Impossibile controllare lo stato della migrazione.",
+ errorCode: "Codice errore: {code}",
+ retryStatus: "Riprova controllo",
+ start: "Avvia migrazione",
+ running: "Migrazione in corso…",
+ retryMigration: "Riprova migrazione",
+ enter: "Entra in DBX",
+ deleteBackup: "Elimina backup",
+ exportDiagnostic: "Esporta diagnostica",
+ openDataDir: "Apri directory dati",
+ exit: "Esci da DBX",
+ confirmDelete: "Eliminare il backup della migrazione?",
+ confirm: "Elimina",
+ cancel: "Annulla",
+ checking: "Controllo della sicurezza dei dati locali…",
+ authFailed: "Impossibile controllare l'autenticazione DBX.",
+ retry: "Riprova",
+ successIntro: "Migrazione e verifica completate. Controlla le connessioni prima di eliminare il backup.",
+ errors: {
+ persistentKeyAdvice: "Configura una chiave persistente e ricontrolla lo stato.",
+ cleanupAdvice: "Controlla i permessi della directory e riprova.",
+ genericAdvice: "Risolvi il problema e riprova.",
+ keyProviderAdvice: "Consenti l'accesso al portachiavi o configura un file chiave persistente.",
+ backupAdvice: "Controlla i permessi di scrittura e lo spazio disponibile.",
+ jsonAdvice: "Ripara il file indicato e riprova.",
+ verifyAdvice: "Conserva il backup finché la verifica non riesce.",
+ },
+ launching: "Avvio di DBX in corso…",
+ openBackupDir: "Apri posizione backup",
+ },
solrAdmin: {
title: "Amministrazione Solr",
refresh: "Aggiorna",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 368c653fad..459419be5c 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -10402,6 +10402,71 @@ export default withEnglishFallback({
titleLabel: "タイトル(任意)",
titlePlaceholder: "例:クエリ結果",
},
+ migration: {
+ eyebrow: "アップグレード後の初回起動",
+ title: "データセキュリティのアップグレード",
+ stepsLabel: "移行ステップ",
+ language: "表示言語",
+ step1: "確認",
+ step2: "データを移行",
+ step3: "完了とバックアップ",
+ successTitle: "移行が完了しました",
+ connectionCountLabel: "接続数:",
+ secretCountLabel: "保護対象:",
+ backupRequiredLabel: "バックアップ:",
+ keyProviderLabel: "鍵の状態:",
+ ready: "準備完了",
+ pending: "要設定",
+ intro: "DBXをアップグレードして再起動しました。このアップグレードでローカルデータの安全性が向上します。1回の処理を完了すると接続を引き続き利用できます。",
+ whyTitle: "このアップグレードで何が変わりますか?",
+ whyBody: "新しいバージョンでは、接続、プラグイン、その他の機密設定をより強力な暗号化で保護します。この処理はアップグレード後に1回だけ実行され、以後は表示されません。",
+ whyItem1: "開始前にバックアップを作成するため、必要に応じてデータを復元できます。",
+ whyItem2: "完了前にデータを検証し、安全なアップグレードが成功したことを確認します。",
+ successIntro: "移行と検証が完了しました。バックアップを削除する前に接続を確認してください。",
+ connectionCount: "接続:{count}",
+ secretCount: "保護対象:{count}",
+ backupPath: "バックアップ:",
+ dataDir: "データディレクトリ:",
+ backupDir: "バックアップディレクトリ:",
+ keyFileStatus: "鍵ファイル設定済み:{configured};読み取り可能:{readable}",
+ persistentKeyStatus: "永続鍵プロバイダー:{available}",
+ yes: "はい",
+ no: "いいえ",
+ keyUnavailable: "デバイスの鍵を利用できません。キーチェーンへのアクセスを許可するか、永続鍵を設定してください。",
+ keyRecoveryHint: "このデータディレクトリで使用していた元のキーを復元するか、既存データの暗号化に使用した同じ外部キーを設定してください。新しいキーで置き換えないでください。",
+ progress: "バックアップを作成し、移行と検証を実行しています。DBXを終了しないでください…",
+ failed: "移行を完了できませんでした。元のデータは保持されています。",
+ cleanupFailed: "移行は完了しましたが、バックアップを削除できませんでした。",
+ retryCleanup: "バックアップ削除を再試行",
+ statusFailed: "移行状態を確認できません。",
+ errorCode: "エラーコード:{code}",
+ retryStatus: "状態確認を再試行",
+ start: "移行を開始",
+ running: "移行中…",
+ retryMigration: "移行を再試行",
+ enter: "DBXを開始",
+ deleteBackup: "バックアップを削除",
+ exportDiagnostic: "診断情報をエクスポート",
+ openDataDir: "データディレクトリを開く",
+ exit: "DBXを終了",
+ confirmDelete: "移行バックアップを削除しますか?削除後はロールバックに使用できません。",
+ confirm: "削除",
+ cancel: "キャンセル",
+ errors: {
+ persistentKeyAdvice: "永続鍵を設定してから状態確認を再試行してください。",
+ cleanupAdvice: "バックアップディレクトリの権限を確認して削除を再試行してください。移行済みデータは使用できます。",
+ genericAdvice: "問題を解決してから再試行してください。元のデータは保持されています。",
+ keyProviderAdvice: "キーチェーンへのアクセスを許可するか、永続鍵ファイルを設定してください。",
+ backupAdvice: "データディレクトリの書き込み権限と空き容量を確認してください。",
+ jsonAdvice: "表示されたファイルを修復してから移行を再試行してください。",
+ verifyAdvice: "バックアップを保持したまま再試行してください。検証が成功するまで削除しないでください。",
+ },
+ checking: "ローカルデータのセキュリティ状態を確認しています…",
+ authFailed: "DBXの認証状態を確認できません。",
+ retry: "再試行",
+ launching: "DBX を起動しています…",
+ openBackupDir: "バックアップの場所を開く",
+ },
solrAdmin: {
title: "Solr 管理",
refresh: "更新",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 861ec42be5..60a024e564 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -9809,6 +9809,71 @@ export default withEnglishFallback({
titleLabel: "제목 (선택)",
titlePlaceholder: "예: 쿼리 결과",
},
+ migration: {
+ eyebrow: "업그레이드 후 첫 실행",
+ title: "데이터 보안 업그레이드",
+ stepsLabel: "마이그레이션 단계",
+ language: "언어",
+ step1: "검토 및 확인",
+ step2: "데이터 마이그레이션",
+ step3: "완료 및 백업",
+ successTitle: "마이그레이션 완료",
+ connectionCountLabel: "연결:",
+ secretCountLabel: "보호 항목:",
+ backupRequiredLabel: "백업:",
+ keyProviderLabel: "키 상태:",
+ ready: "준비됨",
+ pending: "설정 필요",
+ intro: "DBX를 업그레이드하고 다시 시작했습니다. 이번 업그레이드는 로컬 데이터 보안을 강화합니다. 한 번의 처리를 완료하면 연결을 계속 사용할 수 있습니다.",
+ whyTitle: "이번 업그레이드는 무엇을 하나요?",
+ whyBody: "새 버전은 연결, 플러그인 및 기타 민감한 설정을 더 강력한 암호화로 보호합니다. 이 처리는 업그레이드 후 한 번만 실행됩니다.",
+ whyItem1: "시작 전에 백업을 만들어 필요할 때 복구할 수 있습니다.",
+ whyItem2: "완료 전에 결과를 확인하여 업그레이드 성공을 검증합니다.",
+ connectionCount: "연결: {count}",
+ secretCount: "보호 항목: {count}",
+ backupPath: "백업:",
+ dataDir: "데이터 디렉터리:",
+ backupDir: "백업 디렉터리:",
+ yes: "예",
+ no: "아니요",
+ keyFileStatus: "키 파일 설정: {configured}; 읽기 가능: {readable}",
+ persistentKeyStatus: "영구 키 제공자: {available}",
+ keyUnavailable: "장치 키를 사용할 수 없습니다. 키체인 접근을 허용하거나 영구 키를 설정하세요.",
+ keyRecoveryHint: "이 데이터 디렉터리에서 사용한 원래 키를 복원하거나 기존 데이터를 암호화한 동일한 외부 키를 구성하세요. 새 키로 교체하지 마세요.",
+ progress: "백업을 만들고 마이그레이션 및 확인을 진행 중입니다…",
+ failed: "마이그레이션을 완료하지 못했습니다. 원본 데이터는 보존되었습니다.",
+ cleanupFailed: "마이그레이션은 완료되었지만 백업을 삭제하지 못했습니다.",
+ retryCleanup: "백업 삭제 재시도",
+ statusFailed: "마이그레이션 상태를 확인할 수 없습니다.",
+ errorCode: "오류 코드: {code}",
+ retryStatus: "상태 확인 재시도",
+ start: "마이그레이션 시작",
+ running: "마이그레이션 중…",
+ retryMigration: "마이그레이션 재시도",
+ enter: "DBX 시작",
+ deleteBackup: "백업 삭제",
+ exportDiagnostic: "진단 정보 내보내기",
+ openDataDir: "데이터 디렉터리 열기",
+ exit: "DBX 종료",
+ confirmDelete: "마이그레이션 백업을 삭제할까요?",
+ confirm: "삭제",
+ cancel: "취소",
+ checking: "로컬 데이터 보안 상태 확인 중…",
+ authFailed: "DBX 인증 상태를 확인할 수 없습니다.",
+ retry: "재시도",
+ successIntro: "마이그레이션과 확인이 완료되었습니다. 백업을 삭제하기 전에 연결을 확인하세요.",
+ errors: {
+ persistentKeyAdvice: "영구 키를 설정한 후 상태 확인을 다시 시도하세요.",
+ cleanupAdvice: "백업 디렉터리 권한을 확인한 후 다시 시도하세요.",
+ genericAdvice: "문제를 해결한 후 다시 시도하세요.",
+ keyProviderAdvice: "키체인 접근을 허용하거나 영구 키 파일을 설정하세요.",
+ backupAdvice: "데이터 디렉터리의 쓰기 권한과 여유 공간을 확인하세요.",
+ jsonAdvice: "표시된 파일을 수정한 후 다시 시도하세요.",
+ verifyAdvice: "확인이 성공할 때까지 백업을 보관하세요.",
+ },
+ launching: "DBX를 시작하는 중…",
+ openBackupDir: "백업 위치 열기",
+ },
solrAdmin: {
title: "Solr 관리",
refresh: "새로 고침",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index a48f50ecd2..18b87178f0 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -10353,6 +10353,71 @@ export default withEnglishFallback({
titleLabel: "Título (opcional)",
titlePlaceholder: "ex.: Resultado da consulta",
},
+ migration: {
+ eyebrow: "Primeiro início após a atualização",
+ title: "Atualização da segurança dos dados",
+ stepsLabel: "Etapas da migração",
+ language: "Idioma",
+ step1: "Revisar e confirmar",
+ step2: "Migrar dados",
+ step3: "Concluir e fazer backup",
+ successTitle: "Migração concluída",
+ connectionCountLabel: "Conexões:",
+ secretCountLabel: "Itens protegidos:",
+ backupRequiredLabel: "Backup:",
+ keyProviderLabel: "Estado da chave:",
+ ready: "pronta",
+ pending: "pendente",
+ intro: "Você acabou de atualizar e reiniciar o DBX. Esta atualização melhora a segurança dos dados locais. Conclua esta etapa única para continuar usando suas conexões.",
+ whyTitle: "O que esta atualização faz?",
+ whyBody: "A nova versão usa criptografia mais forte para proteger conexões, plugins e outras configurações sensíveis. Esta etapa é executada apenas uma vez.",
+ whyItem1: "Um backup é criado antes do início para permitir a recuperação dos dados.",
+ whyItem2: "O resultado é verificado antes da conclusão.",
+ connectionCount: "Conexões: {count}",
+ secretCount: "Itens protegidos: {count}",
+ backupPath: "Backup:",
+ dataDir: "Diretório de dados:",
+ backupDir: "Diretório de backup:",
+ yes: "sim",
+ no: "não",
+ keyFileStatus: "Arquivo de chave configurado: {configured}; legível: {readable}",
+ persistentKeyStatus: "Provedor de chave persistente: {available}",
+ keyUnavailable: "A chave do dispositivo não está disponível. Permita o acesso ao chaveiro ou configure uma chave persistente.",
+ keyRecoveryHint: "Restaure a chave original usada por este diretório de dados ou configure a mesma chave externa que criptografou os dados existentes. Não a substitua por uma chave nova.",
+ progress: "Criando backup, migrando e verificando…",
+ failed: "A migração não foi concluída. Os dados originais foram preservados.",
+ cleanupFailed: "A migração terminou, mas o backup não pôde ser excluído.",
+ retryCleanup: "Tentar excluir novamente",
+ statusFailed: "Não foi possível verificar o estado da migração.",
+ errorCode: "Código de erro: {code}",
+ retryStatus: "Tentar verificar novamente",
+ start: "Iniciar migração",
+ running: "Migrando…",
+ retryMigration: "Tentar migração novamente",
+ enter: "Entrar no DBX",
+ deleteBackup: "Excluir backup",
+ exportDiagnostic: "Exportar diagnóstico",
+ openDataDir: "Abrir diretório de dados",
+ exit: "Sair do DBX",
+ confirmDelete: "Excluir o backup da migração?",
+ confirm: "Excluir",
+ cancel: "Cancelar",
+ checking: "Verificando a segurança dos dados locais…",
+ authFailed: "Não foi possível verificar a autenticação do DBX.",
+ retry: "Tentar novamente",
+ successIntro: "A migração e a verificação foram concluídas. Confira as conexões antes de excluir o backup.",
+ errors: {
+ persistentKeyAdvice: "Configure uma chave persistente e verifique o estado novamente.",
+ cleanupAdvice: "Verifique as permissões do diretório e tente novamente.",
+ genericAdvice: "Resolva o problema e tente novamente.",
+ keyProviderAdvice: "Permita o acesso ao chaveiro ou configure um arquivo de chave persistente.",
+ backupAdvice: "Verifique as permissões de gravação e o espaço disponível.",
+ jsonAdvice: "Corrija o arquivo indicado e tente novamente.",
+ verifyAdvice: "Mantenha o backup até a verificação ser concluída.",
+ },
+ launching: "Iniciando o DBX…",
+ openBackupDir: "Abrir local do backup",
+ },
solrAdmin: {
title: "Administração do Solr",
refresh: "Atualizar",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 97e2cead1a..c787ef4e27 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -10140,4 +10140,67 @@ export default withEnglishFallback({
titleLabel: "Başlık (isteğe bağlı)",
titlePlaceholder: "örn. Sorgu sonucu",
},
+ migration: {
+ eyebrow: "Güncelleme sonrası ilk açılış",
+ title: "Veri güvenliği güncellemesi",
+ stepsLabel: "Taşıma adımları",
+ language: "Dil",
+ step1: "İncele ve onayla",
+ step2: "Verileri taşı",
+ step3: "Tamamla ve yedekle",
+ successTitle: "Taşıma tamamlandı",
+ connectionCountLabel: "Bağlantılar:",
+ secretCountLabel: "Korunan öğeler:",
+ backupRequiredLabel: "Yedek:",
+ keyProviderLabel: "Anahtar durumu:",
+ ready: "hazır",
+ pending: "ayarlanmalı",
+ intro: "DBX'i güncellediniz ve yeniden başlattınız. Bu güncelleme yerel veri güvenliğini artırır. Bağlantıları kullanmaya devam etmek için bu tek seferlik işlemi tamamlayın.",
+ whyTitle: "Bu güncelleme ne yapar?",
+ whyBody: "Yeni sürüm bağlantıları, eklentileri ve diğer hassas ayarları daha güçlü şifrelemeyle korur. Bu işlem yalnızca bir kez çalışır.",
+ whyItem1: "Başlamadan önce verilerin kurtarılabilmesi için yedek oluşturulur.",
+ whyItem2: "Tamamlanmadan önce sonuç doğrulanır.",
+ connectionCount: "Bağlantılar: {count}",
+ secretCount: "Korunan öğeler: {count}",
+ backupPath: "Yedek:",
+ dataDir: "Veri dizini:",
+ backupDir: "Yedek dizini:",
+ yes: "evet",
+ no: "hayır",
+ keyFileStatus: "Anahtar dosyası yapılandırıldı: {configured}; okunabilir: {readable}",
+ persistentKeyStatus: "Kalıcı anahtar sağlayıcısı: {available}",
+ keyUnavailable: "Cihaz anahtarı kullanılamıyor. Anahtarlık erişimine izin verin veya kalıcı bir anahtar yapılandırın.",
+ keyRecoveryHint: "Bu veri dizini için kullanılan özgün anahtarı geri yükleyin veya mevcut verileri şifreleyen aynı harici anahtarı yapılandırın. Yeni bir anahtarla değiştirmeyin.",
+ progress: "Yedek oluşturuluyor, taşınıyor ve doğrulanıyor…",
+ failed: "Taşıma tamamlanamadı. Orijinal veriler korundu.",
+ cleanupFailed: "Taşıma tamamlandı ancak yedek silinemedi.",
+ retryCleanup: "Silmeyi yeniden dene",
+ statusFailed: "Taşıma durumu denetlenemedi.",
+ errorCode: "Hata kodu: {code}",
+ retryStatus: "Durumu yeniden dene",
+ start: "Taşımayı başlat",
+ running: "Taşınıyor…",
+ retryMigration: "Taşımayı yeniden dene",
+ enter: "DBX'e gir",
+ deleteBackup: "Yedeği sil",
+ exportDiagnostic: "Tanılamayı dışa aktar",
+ openDataDir: "Veri dizinini aç",
+ exit: "DBX'ten çık",
+ confirmDelete: "Taşıma yedeği silinsin mi?",
+ confirm: "Sil",
+ cancel: "İptal",
+ checking: "Yerel veri güvenliği denetleniyor…",
+ authFailed: "DBX kimlik doğrulaması denetlenemedi.",
+ retry: "Yeniden dene",
+ successIntro: "Taşıma ve doğrulama tamamlandı. Yedeği silmeden önce bağlantıları kontrol edin.",
+ errors: {
+ persistentKeyAdvice: "Kalıcı anahtar yapılandırın ve durumu yeniden denetleyin.",
+ cleanupAdvice: "Yedek dizini izinlerini kontrol edip yeniden deneyin.",
+ genericAdvice: "Sorunu düzeltip yeniden deneyin.",
+ keyProviderAdvice: "Anahtarlık erişimine izin verin veya kalıcı anahtar dosyası yapılandırın.",
+ backupAdvice: "Veri dizininin yazılabilir olduğunu ve yeterli alan bulunduğunu kontrol edin.",
+ jsonAdvice: "Belirtilen dosyayı düzeltip yeniden deneyin.",
+ verifyAdvice: "Doğrulama başarılı olana kadar yedeği saklayın.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 6432872fc5..d0c5f7eb0e 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -10841,4 +10841,69 @@ export default withEnglishFallback({
titleLabel: "标题(可选)",
titlePlaceholder: "例如:查询结果",
},
+ migration: {
+ eyebrow: "升级后的首次启动",
+ title: "数据安全升级",
+ stepsLabel: "迁移步骤",
+ language: "界面语言",
+ step1: "检查与确认",
+ step2: "执行迁移",
+ step3: "完成与备份",
+ successTitle: "迁移完成",
+ connectionCountLabel: "连接:",
+ secretCountLabel: "敏感项:",
+ backupRequiredLabel: "需要备份:",
+ keyProviderLabel: "密钥状态:",
+ ready: "已就绪",
+ pending: "待配置",
+ intro: "你刚刚完成了 DBX 升级并重新启动应用。本次升级会进一步提升本地数据安全,完成一次处理后即可继续使用连接。",
+ whyTitle: "本次升级会带来什么?",
+ whyBody: "新版本将使用更安全的加密方式保护连接、插件和其他敏感配置。首次启动需要完成一次数据处理,之后不会重复显示此页面。",
+ whyItem1: "开始前会自动创建备份,确保数据可恢复。",
+ whyItem2: "完成后会验证数据可以正常读取,确认安全升级成功。",
+ successIntro: "迁移已完成且密文验证通过。确认连接正常后再删除备份。",
+ connectionCount: "连接:{count} 个",
+ secretCount: "待迁移敏感项:{count} 个",
+ backupPath: "备份位置:",
+ dataDir: "数据目录:",
+ backupDir: "备份目录:",
+ keyFileStatus: "密钥文件已配置:{configured};可读取:{readable}",
+ persistentKeyStatus: "持久化密钥提供者可用:{available}",
+ yes: "是",
+ no: "否",
+ keyUnavailable: "当前设备密钥不可用,请允许钥匙串访问或配置持久化密钥。",
+ keyRecoveryHint: "请恢复该数据目录原有的密钥,或配置用于加密现有数据的同一外部密钥。不要使用新密钥替换原密钥。",
+ progress: "正在创建备份、迁移并验证,请勿关闭 DBX…",
+ failed: "迁移没有完成,原始数据已保留。",
+ cleanupFailed: "迁移已完成,但备份删除失败。",
+ retryCleanup: "重试删除备份",
+ statusFailed: "无法检查迁移状态。",
+ errorCode: "错误代码:{code}",
+ retryStatus: "重试状态检查",
+ start: "开始迁移",
+ running: "迁移中…",
+ retryMigration: "重试迁移",
+ enter: "进入 DBX",
+ launching: "正在启动 DBX…",
+ deleteBackup: "删除备份",
+ exportDiagnostic: "导出脱敏诊断",
+ openDataDir: "打开数据目录",
+ openBackupDir: "打开备份位置",
+ exit: "退出 DBX",
+ confirmDelete: "确认删除这份升级备份?连接和密码已经保存在本机,删除备份不会删除你的连接列表或密码,但之后无法再用它回滚本次升级。",
+ confirm: "确认删除",
+ cancel: "取消",
+ errors: {
+ persistentKeyAdvice: "请配置持久化的 DBX_SECRET_KEY_FILE 或 DBX_SECRET_KEY,然后重新检查状态。",
+ cleanupAdvice: "请检查备份目录权限后重试删除备份,迁移后的数据可正常使用。",
+ genericAdvice: "请修复上述问题后重试,原始数据仍然保留。",
+ keyProviderAdvice: "请允许 DBX 访问钥匙串,或配置持久化的 DBX_SECRET_KEY_FILE。",
+ backupAdvice: "请确认数据目录可写且有足够的剩余空间。",
+ jsonAdvice: "请修复提示的历史 JSON 文件后重试迁移。",
+ verifyAdvice: "请保留备份并重试,验证成功前不要删除迁移备份。",
+ },
+ checking: "正在检查本地数据安全状态…",
+ authFailed: "无法检查 DBX 登录状态。",
+ retry: "重试",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 696ef9da79..a987847aaf 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -10348,6 +10348,71 @@ export default withEnglishFallback({
titleLabel: "標題(可選)",
titlePlaceholder: "例如:查詢結果",
},
+ migration: {
+ eyebrow: "升級後首次啟動",
+ title: "資料安全升級",
+ stepsLabel: "遷移步驟",
+ language: "介面語言",
+ step1: "檢查與確認",
+ step2: "執行遷移",
+ step3: "完成與備份",
+ successTitle: "遷移完成",
+ connectionCountLabel: "連線:",
+ secretCountLabel: "受保護項目:",
+ backupRequiredLabel: "需要備份:",
+ keyProviderLabel: "金鑰狀態:",
+ ready: "已就緒",
+ pending: "待設定",
+ intro: "你剛完成 DBX 升級並重新啟動應用程式。本次升級會提升本機資料安全,完成一次處理後即可繼續使用連線。",
+ whyTitle: "本次升級會帶來什麼?",
+ whyBody: "新版本會使用更安全的加密方式保護連線、外掛程式及其他敏感設定。這項處理只會執行一次。",
+ whyItem1: "開始前會自動建立備份,確保資料可以復原。",
+ whyItem2: "完成前會驗證資料可以正常讀取。",
+ connectionCount: "連線:{count} 個",
+ secretCount: "受保護項目:{count} 個",
+ backupPath: "備份位置:",
+ dataDir: "資料目錄:",
+ backupDir: "備份目錄:",
+ yes: "是",
+ no: "否",
+ keyFileStatus: "金鑰檔案已設定:{configured};可讀取:{readable}",
+ persistentKeyStatus: "持久化金鑰提供者:{available}",
+ keyUnavailable: "目前無法使用裝置金鑰,請允許存取鑰匙圈或設定持久化金鑰。",
+ keyRecoveryHint: "請還原此資料目錄原本使用的金鑰,或設定用於加密現有資料的相同外部金鑰。請勿使用新金鑰取代原金鑰。",
+ progress: "正在建立備份、執行遷移並驗證…",
+ failed: "遷移未完成,原始資料已保留。",
+ cleanupFailed: "遷移已完成,但無法刪除備份。",
+ retryCleanup: "重試刪除備份",
+ statusFailed: "無法檢查遷移狀態。",
+ errorCode: "錯誤代碼:{code}",
+ retryStatus: "重試狀態檢查",
+ start: "開始遷移",
+ running: "遷移中…",
+ retryMigration: "重試遷移",
+ enter: "進入 DBX",
+ deleteBackup: "刪除備份",
+ exportDiagnostic: "匯出診斷資訊",
+ openDataDir: "開啟資料目錄",
+ openBackupDir: "開啟備份位置",
+ exit: "退出 DBX",
+ confirmDelete: "確定要刪除這份升級備份嗎?連線與密碼已保存在本機,刪除備份不會刪除你的連線清單或密碼,但之後將無法再用它回復本次升級。",
+ confirm: "刪除",
+ cancel: "取消",
+ checking: "正在檢查本機資料安全狀態…",
+ authFailed: "無法檢查 DBX 驗證狀態。",
+ retry: "重試",
+ successIntro: "遷移與驗證已完成。刪除備份前請先確認連線正常。",
+ errors: {
+ persistentKeyAdvice: "請設定持久化金鑰後重新檢查狀態。",
+ cleanupAdvice: "請檢查備份目錄權限後重試。",
+ genericAdvice: "請修正問題後重試。",
+ keyProviderAdvice: "請允許存取鑰匙圈或設定持久化金鑰檔案。",
+ backupAdvice: "請確認資料目錄可寫入且有足夠空間。",
+ jsonAdvice: "請修復提示的檔案後重試。",
+ verifyAdvice: "驗證成功前請保留備份。",
+ },
+ launching: "正在啟動 DBX…",
+ },
solrAdmin: {
title: "Solr 管理",
refresh: "重新整理",
diff --git a/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts b/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
index 32cbfb7457..54ddaeb34c 100644
--- a/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
+++ b/apps/desktop/src/lib/backend/__tests__/cloudSyncWebApi.spec.ts
@@ -61,18 +61,27 @@ describe("WebDAV sync HTTP API", () => {
expect(lastCall(fetchMock)).toEqual({ url: "/api/cloud-sync/webdav/forget-sync-secrets-passphrase", body: {} });
const editorSettings = { theme: "dark" };
- await webdavSyncUpload(config, editorSettings, "sync-passphrase");
+ await webdavSyncUpload(config, editorSettings, "sync-passphrase", true);
expect(lastCall(fetchMock)).toEqual({
url: "/api/cloud-sync/webdav/upload",
- body: { config, editorSettings, secretsPassphrase: "sync-passphrase" },
+ body: { config, editorSettings, secretsPassphrase: "sync-passphrase", includeSecrets: true },
});
- await webdavSyncDownload(config, "sync-passphrase");
+ await webdavSyncDownload(config, "sync-passphrase", true);
expect(lastCall(fetchMock)).toEqual({
url: "/api/cloud-sync/webdav/download",
- body: { config, secretsPassphrase: "sync-passphrase" },
+ body: { config, secretsPassphrase: "sync-passphrase", restoreSecrets: true },
});
});
+
+ it("accepts the migration cleanup endpoint's empty 204 response", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const { migrationCleanupBackups } = await import("@/lib/backend/http");
+
+ await expect(migrationCleanupBackups()).resolves.toBeUndefined();
+ expect(lastCall(fetchMock)).toEqual({ url: "/api/migration/cleanup-backups", body: {} });
+ });
});
describe("GitLab snippet sync HTTP API", () => {
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 8559bc5eb0..fe0e24bfbd 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -385,6 +385,10 @@ export const saveSavedSqlEditorPositions = forward("saveSavedSqlEditorPositions"
export const loadTransferTaskLibrary = forward("loadTransferTaskLibrary");
export const saveTransferTaskLibrary = forward("saveTransferTaskLibrary");
export const webdavSyncTest = forward("webdavSyncTest");
+export const migrationStatus = forward("migrationStatus");
+export const migrationStart = forward("migrationStart");
+export const migrationRetry = forward("migrationRetry");
+export const migrationCleanupBackups = forward("migrationCleanupBackups");
export const webdavPasswordStatus = forward("webdavPasswordStatus");
export const saveWebdavSavedPassword = forward("saveWebdavSavedPassword");
export const forgetWebdavSavedPassword = forward("forgetWebdavSavedPassword");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index ed4d2b1094..7d2e95f95f 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -175,6 +175,12 @@ import type {
} from "@/lib/backend/tauri";
import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import type { CsvQuoteMode } from "@/lib/export/csvQuoteMode";
+import type { MigrationPreflight, MigrationReport } from "./migration";
+export type { MigrationPreflight, MigrationReport } from "./migration";
+export const migrationStatus = (): Promise<MigrationPreflight> => get("/api/migration/status");
+export const migrationStart = (): Promise<MigrationReport> => post("/api/migration/start", {});
+export const migrationRetry = (): Promise<MigrationReport> => post("/api/migration/retry", {});
+export const migrationCleanupBackups = (): Promise<void> => post("/api/migration/cleanup-backups", {});
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
import type {
DataGridColumnDistinctValuesSqlOptions,
@@ -316,6 +322,7 @@ async function post<T>(url: string, body: unknown): Promise<T> {
body: JSON.stringify(body),
});
if (!res.ok) throw await backendResponseError(res);
+ if (res.status === 204) return undefined as T;
return res.json();
}
@@ -2380,16 +2387,17 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
return post("/api/cloud-sync/webdav/forget-sync-secrets-passphrase", {});
}
-export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string): Promise<WebDavSyncSummary> {
+export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
return post("/api/cloud-sync/webdav/upload", {
config,
editorSettings,
secretsPassphrase,
+ includeSecrets,
});
}
-export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string): Promise<WebDavDownloadResult> {
- return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase });
+export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
+ return post("/api/cloud-sync/webdav/download", { config, secretsPassphrase, restoreSecrets });
}
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
diff --git a/apps/desktop/src/lib/backend/migration.ts b/apps/desktop/src/lib/backend/migration.ts
new file mode 100644
index 0000000000..aa13185944
--- /dev/null
+++ b/apps/desktop/src/lib/backend/migration.ts
@@ -0,0 +1,35 @@
+export type MigrationState = "pending" | "running" | "succeeded" | "failed" | "not_required";
+export interface MigrationPreflight {
+ migrationId: string;
+ state: MigrationState;
+ needsMigration: boolean;
+ keyProviderAvailable: boolean;
+ keyCreationAllowed?: boolean;
+ databasePlaintextCount: number;
+ connectionCount: number;
+ pluginSecretCount: number;
+ aiSecretCount: number;
+ tunnelSecretCount: number;
+ syncCredentialCount: number;
+ legacyJsonFiles: { name: string; exists: boolean; bytes: number }[];
+ backupRequired: boolean;
+ backupPath?: string | null;
+ errorMessage?: string | null;
+ errorCode?: string | null;
+ dataDir?: string;
+ backupDir?: string;
+ keyFileConfigured?: boolean;
+ keyFileReadable?: boolean;
+ persistentKeyConfigured?: boolean;
+ keySource?: "explicit_file" | "explicit_env" | "managed_data_dir" | "platform_store" | "unavailable" | string;
+}
+export interface MigrationReport {
+ migrationId: string;
+ state: MigrationState;
+ backupPath?: string | null;
+ databasePlaintextCount: number;
+ legacyJsonFiles: string[];
+ verifiedSecretCount: number;
+ errorCode?: string | null;
+ errorMessage?: string | null;
+}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index ce146586b1..dd0b4dcad3 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -12,6 +12,13 @@ function invoke<T>(command: string, args?: Record<string, unknown>): Promise<T>
assertUpdateAllowsCommand(command);
return tauriInvoke<T>(command, args);
}
+
+import type { MigrationPreflight, MigrationReport } from "./migration";
+export type { MigrationPreflight, MigrationReport } from "./migration";
+export const migrationStatus = (): Promise<MigrationPreflight> => invoke("migration_status");
+export const migrationStart = (): Promise<MigrationReport> => invoke("migration_start");
+export const migrationRetry = (): Promise<MigrationReport> => invoke("migration_retry");
+export const migrationCleanupBackups = (): Promise<void> => invoke("migration_cleanup_backups");
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
@@ -967,16 +974,17 @@ export async function forgetWebdavSyncSecretsPassphrase(): Promise<void> {
return invoke("forget_webdav_sync_secrets_passphrase");
}
-export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string): Promise<WebDavSyncSummary> {
+export async function webdavSyncUpload(config: WebDavConfig, editorSettings?: unknown, secretsPassphrase?: string, includeSecrets = false): Promise<WebDavSyncSummary> {
return invoke("webdav_sync_upload", {
config,
editorSettings,
secretsPassphrase,
+ includeSecrets,
});
}
-export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string): Promise<WebDavDownloadResult> {
- return invoke("webdav_sync_download", { config, secretsPassphrase });
+export async function webdavSyncDownload(config: WebDavConfig, secretsPassphrase?: string, restoreSecrets = true): Promise<WebDavDownloadResult> {
+ return invoke("webdav_sync_download", { config, secretsPassphrase, restoreSecrets });
}
export async function snippetSyncTest(config: SnippetSyncConfig): Promise<void> {
diff --git a/apps/desktop/src/lib/connection/connectionConfigTransfer.spec.ts b/apps/desktop/src/lib/connection/connectionConfigTransfer.spec.ts
index 669ad25bd6..92bf6f4ddf 100644
--- a/apps/desktop/src/lib/connection/connectionConfigTransfer.spec.ts
+++ b/apps/desktop/src/lib/connection/connectionConfigTransfer.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { ConnectionConfig, SidebarLayout, TunnelProfile } from "@/types/database";
-import { buildConnectionConfigBundle, parseConnectionConfigObject, selectConnectionConfigBundle, snapshotConnectionsForExport } from "./connectionConfigTransfer";
+import { buildConnectionConfigBundle, parseConnectionConfigObject, prepareConnectionConfigImport, scrubConnectionForPlaintextExport, scrubTunnelProfileForPlaintextExport, selectConnectionConfigBundle, snapshotConnectionsForExport } from "./connectionConfigTransfer";
function conn(id: string, name: string, extras: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
@@ -83,11 +83,76 @@ describe("connectionConfigTransfer", () => {
});
});
+ it("keeps stable ids and removes secrets from plaintext exports", () => {
+ const exported = scrubConnectionForPlaintextExport(
+ conn("stable", "A", {
+ password: "db-password",
+ init_script: "CREATE USER secret",
+ connection_string: "postgres://user:password@host/db",
+ url_params: "applicationName=dbx&PASSWORD=url-password&sslmode=require",
+ connection_secrets: { api_token: "plugin-token" },
+ transport_layers: [{ type: "ssh", id: "layer", host: "bastion", port: 22, user: "root", password: "ssh-password", key_passphrase: "key-password" }],
+ external_config: { auth: { password: "nested-password" }, safe: "value" },
+ }),
+ );
+ expect(exported.id).toBe("stable");
+ expect(exported.password).toBe("");
+ expect(exported.connection_secrets).toEqual({});
+ expect(JSON.stringify(exported)).not.toContain("db-password");
+ expect(JSON.stringify(exported)).not.toContain("nested-password");
+ expect(JSON.stringify(exported)).not.toContain("plugin-token");
+ expect(exported.url_params).toBe("applicationName=dbx&PASSWORD=&sslmode=require");
+ expect(JSON.stringify(exported)).not.toContain("url-password");
+ expect(scrubTunnelProfileForPlaintextExport({ type: "http_tunnel", id: "t", url: "https://example", token: "token" })).toMatchObject({ id: "t", token: "" });
+ });
+
+ it("redacts structured API key auth without removing unrelated values or mutating the source", () => {
+ const source = conn("mq", "MQ", {
+ external_config: {
+ auth: { kind: "apiKey", header: "X-Api-Key", value: "api-key-secret" },
+ value: "public-root",
+ nested: [{ auth: { kind: "apiKey", header: "Authorization", value: "nested-api-key" } }, { auth: { kind: "basic", username: "user", password: "basic-password", value: "public-auth" } }, { kind: "apiKey", value: "public-non-auth" }],
+ },
+ });
+
+ const exported = scrubConnectionForPlaintextExport(source);
+
+ expect(exported.external_config).toEqual({
+ auth: { kind: "apiKey", header: "X-Api-Key", value: "" },
+ value: "public-root",
+ nested: [{ auth: { kind: "apiKey", header: "Authorization", value: "" } }, { auth: { kind: "basic", username: "user", password: "", value: "public-auth" } }, { kind: "apiKey", value: "public-non-auth" }],
+ });
+ expect(source.external_config).toMatchObject({ auth: { value: "api-key-secret" } });
+ expect(JSON.stringify(exported)).not.toContain("api-key-secret");
+ expect(JSON.stringify(exported)).not.toContain("nested-api-key");
+ expect(JSON.stringify(exported)).not.toContain("basic-password");
+ });
+
it("parses legacy arrays and dbx-config payloads without inventing a layout", () => {
expect(parseConnectionConfigObject([conn("a", "A")])).toEqual({ connections: [conn("a", "A")] });
expect(parseConnectionConfigObject({ format: "dbx-config", connections: [conn("a", "A")] })).toEqual({ connections: [conn("a", "A")] });
});
+ it("remaps ordinary import IDs on collision and updates tunnel/layout references", () => {
+ const imported = prepareConnectionConfigImport(
+ {
+ connections: [conn("same", "Imported", { transport_layers: [{ type: "ssh", id: "layer", host: "", port: 22, user: "", profile_id: "tp" }] })],
+ tunnelProfiles: [{ ...tunnel1, id: "tp" }],
+ layout: { groups: [], order: [{ type: "connection", id: "same" }] },
+ },
+ ["same"],
+ ["tp"],
+ (() => {
+ let n = 0;
+ return () => `new-${++n}`;
+ })(),
+ );
+ expect(imported.connections[0].id).toBe("new-1");
+ expect(imported.connections[0].transport_layers?.[0].profile_id).toBe("new-2");
+ expect(imported.tunnelProfiles?.[0].id).toBe("new-2");
+ expect(imported.layout?.order[0]).toEqual({ type: "connection", id: "new-1" });
+ });
+
it("selects a preview subset without mutating the original preview", () => {
const preview = {
connections: [conn("a", "A"), conn("b", "B"), conn("c", "C")],
diff --git a/apps/desktop/src/lib/connection/connectionConfigTransfer.ts b/apps/desktop/src/lib/connection/connectionConfigTransfer.ts
index c2f463dae9..bf07f5d818 100644
--- a/apps/desktop/src/lib/connection/connectionConfigTransfer.ts
+++ b/apps/desktop/src/lib/connection/connectionConfigTransfer.ts
@@ -1,5 +1,5 @@
import type { ConnectionConfig, SidebarLayout, TunnelProfile } from "@/types/database";
-import { filterSidebarLayoutByConnectionIds as filterLayoutByConnectionIds } from "@/lib/sidebar/sidebarLayout";
+import { filterSidebarLayoutByConnectionIds as filterLayoutByConnectionIds, remapSidebarLayoutConnectionIds } from "@/lib/sidebar/sidebarLayout";
export type ConnectionExportProtection = { mode: "encrypted"; passphrase: string } | { mode: "plaintext" };
@@ -60,6 +60,74 @@ export function snapshotConnectionsForExport(connections: ConnectionConfig[], op
}));
}
+/** Remove every credential-bearing field before creating a plaintext bundle. */
+export function scrubConnectionForPlaintextExport(connection: ConnectionConfig): ConnectionConfig {
+ const scrubbed: ConnectionConfig = JSON.parse(JSON.stringify(connection)) as ConnectionConfig;
+ scrubbed.password = "";
+ scrubbed.url_params = scrubUrlParams(scrubbed.url_params);
+ scrubbed.init_script = undefined;
+ scrubbed.connection_string = undefined;
+ scrubbed.redis_sentinel_password = "";
+ scrubbed.connection_secrets = {};
+ scrubbed.transport_layers = (scrubbed.transport_layers ?? []).map((layer) => {
+ const copy = { ...layer } as typeof layer;
+ if (copy.type === "ssh") {
+ copy.password = "";
+ copy.key_passphrase = "";
+ } else if (copy.type === "proxy") {
+ copy.password = "";
+ } else {
+ copy.token = "";
+ }
+ return copy;
+ });
+ scrubbed.external_config = scrubExternalConfig(scrubbed.external_config);
+ return scrubbed;
+}
+
+export function scrubTunnelProfileForPlaintextExport(profile: TunnelProfile): TunnelProfile {
+ const scrubbed = { ...profile };
+ if (scrubbed.type === "ssh") {
+ scrubbed.password = "";
+ scrubbed.key_passphrase = "";
+ } else if (scrubbed.type === "proxy") {
+ scrubbed.password = "";
+ } else {
+ scrubbed.token = "";
+ }
+ return scrubbed;
+}
+
+function scrubExternalConfig(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(scrubExternalConfig);
+ if (!value || typeof value !== "object") return value;
+ const output: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
+ if (/password|passphrase|secret|token|api[_-]?key|clientsecret|accesstoken|privatekey/i.test(key)) {
+ output[key] = typeof child === "string" ? "" : null;
+ } else if (key === "auth" && child && typeof child === "object" && !Array.isArray(child) && (child as Record<string, unknown>).kind === "apiKey") {
+ output[key] = { ...(scrubExternalConfig(child) as Record<string, unknown>), value: "" };
+ } else {
+ output[key] = scrubExternalConfig(child);
+ }
+ }
+ return output;
+}
+
+function scrubUrlParams(value: string | undefined): string | undefined {
+ if (typeof value !== "string") return value;
+ return value
+ .split("&")
+ .map((part) => {
+ const separator = part.indexOf("=");
+ if (separator < 0) return part;
+ const key = part.slice(0, separator);
+ const normalized = key.trim().toLowerCase().replace(/[_-]/g, "");
+ return /password|passphrase|secret|token|apikey|privatekey|clientsecret/.test(normalized) ? key + "=" : part;
+ })
+ .join("&");
+}
+
export function buildConnectionConfigBundle(connections: ConnectionConfig[], layout: SidebarLayout | null | undefined, tunnelProfiles: TunnelProfile[], selectedIds?: Iterable<string>): ConnectionConfigBundle {
const selectedConnections = filterConnectionsByIds(connections, selectedIds);
const selectedConnectionIds = selectedConnections.map((connection) => connection.id);
@@ -110,3 +178,84 @@ export function selectConnectionConfigBundle(bundle: ConnectionConfigBundle, sel
tunnelProfiles: filterTunnelProfilesByIds(bundle.tunnelProfiles ?? [], referencedTunnelProfileIds(selectedConnections)),
};
}
+
+/** Ordinary file imports deduplicate connections while keeping cloud sync's ID merge policy separate. */
+export function prepareConnectionConfigImport(bundle: ConnectionConfigBundle, existingConnections: Iterable<Pick<ConnectionConfig, "id" | "name" | "host" | "port"> | string>, existingTunnelProfileIds: Iterable<string>, createId: () => string): ConnectionConfigBundle {
+ const existingConnectionList = Array.from(existingConnections);
+ const existingConnectionIds = new Set(existingConnectionList.map((connection) => (typeof connection === "string" ? connection : connection.id)));
+ const existingByIdentity = new Map<string, string>();
+ for (const connection of existingConnectionList) {
+ if (typeof connection === "string") continue;
+ existingByIdentity.set(connectionIdentity(connection), connection.id);
+ }
+
+ const sourceConnections = bundle.connections.map((connection, index) => ({
+ ...connection,
+ // Anonymous legacy entries need a stable key for layout/reference remapping.
+ id: connection.id?.trim() || `__dbx_import_${index}`,
+ }));
+ const connectionIds = new Map<string, string>();
+ const importedConnections: ConnectionConfig[] = [];
+ const importedByIdentity = new Map<string, string>();
+ const seenSourceIds = new Set<string>();
+ const occupiedConnectionIds = new Set(existingConnectionIds);
+
+ for (const source of sourceConnections) {
+ if (seenSourceIds.has(source.id)) throw new Error("DUPLICATE_IMPORT_ID");
+ seenSourceIds.add(source.id);
+
+ const identity = connectionIdentity(source);
+ const duplicateId = existingByIdentity.get(identity) ?? importedByIdentity.get(identity);
+ if (duplicateId) {
+ connectionIds.set(source.id, duplicateId);
+ continue;
+ }
+
+ let targetId = createId();
+ while (!targetId || occupiedConnectionIds.has(targetId)) targetId = createId();
+ occupiedConnectionIds.add(targetId);
+ connectionIds.set(source.id, targetId);
+ importedByIdentity.set(identity, targetId);
+ importedConnections.push({ ...source, id: targetId });
+ }
+
+ const sourceProfiles = new Map<string, TunnelProfile>();
+ for (const profile of bundle.tunnelProfiles ?? []) {
+ const id = profile.id?.trim();
+ if (id && !sourceProfiles.has(id)) sourceProfiles.set(id, { ...profile, id });
+ }
+ const profileIds = new Map<string, string>();
+ const importedTunnelProfileIds = new Set<string>();
+ const occupiedProfileIds = new Set(existingTunnelProfileIds);
+ for (const connection of importedConnections) {
+ for (const layer of connection.transport_layers ?? []) {
+ const sourceProfileId = layer.profile_id;
+ if (!sourceProfileId || !sourceProfiles.has(sourceProfileId) || profileIds.has(sourceProfileId)) continue;
+ let targetId = sourceProfileId;
+ if (occupiedProfileIds.has(targetId)) {
+ targetId = createId();
+ while (!targetId || occupiedProfileIds.has(targetId)) targetId = createId();
+ }
+ occupiedProfileIds.add(targetId);
+ profileIds.set(sourceProfileId, targetId);
+ importedTunnelProfileIds.add(sourceProfileId);
+ }
+ }
+
+ return {
+ connections: importedConnections.map((connection) => ({
+ ...connection,
+ transport_layers: connection.transport_layers?.map((layer) => ({
+ ...layer,
+ // Never leave an unresolved source ID pointing at an unrelated local profile.
+ profile_id: layer.profile_id ? profileIds.get(layer.profile_id) : undefined,
+ })),
+ })),
+ tunnelProfiles: Array.from(importedTunnelProfileIds, (sourceId) => ({ ...sourceProfiles.get(sourceId)!, id: profileIds.get(sourceId)! })),
+ layout: bundle.layout ? filterSidebarLayoutByConnectionIds(remapSidebarLayoutConnectionIds(bundle.layout, connectionIds), connectionIds.values()) : undefined,
+ };
+}
+
+function connectionIdentity(connection: Pick<ConnectionConfig, "name" | "host" | "port">): string {
+ return JSON.stringify([connection.name, connection.host, connection.port]);
+}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 38e451ed03..b7859b82b1 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -77,7 +77,7 @@ function installGlobalInputAttrs() {
async function bootstrap() {
console.log("[STARTUP] frontend bootstrap begin");
- const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./App.vue")]);
+ const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./StartupGate.vue")]);
console.log("[STARTUP] frontend modules loaded");
await loadSavedLocale();
console.log("[STARTUP] locale ready");
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 63d5a106d0..e46e7d794f 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -56,7 +56,6 @@ import {
expandGroups as expandGroupsOp,
collapseAllGroups as collapseAllGroupsOp,
moveConnectionToGroup as moveConnectionToGroupOp,
- remapSidebarLayoutConnectionIds,
mergeSidebarLayout,
reorderEntry as reorderEntryOp,
reorderEntries as reorderEntriesOp,
@@ -94,11 +93,11 @@ import {
} from "@/lib/table/tableVGroup";
import {
buildConnectionConfigBundle,
- filterSidebarLayoutByConnectionIds,
- filterTunnelProfilesByIds,
parseConnectionConfigObject,
- referencedTunnelProfileIds,
+ prepareConnectionConfigImport,
selectConnectionConfigBundle,
+ scrubConnectionForPlaintextExport,
+ scrubTunnelProfileForPlaintextExport,
snapshotConnectionsForExport,
type ConnectionConfigBundle,
type ConnectionExportProtection,
@@ -9305,7 +9304,12 @@ export const useConnectionStore = defineStore("connection", () => {
const payload = await encryptConfig(json, protection.passphrase);
content = JSON.stringify(payload, null, 2);
} else {
- content = JSON.stringify(exportData, null, 2);
+ const scrubbedData = {
+ ...exportData,
+ connections: exportData.connections.map(scrubConnectionForPlaintextExport),
+ tunnelProfiles: exportData.tunnelProfiles?.map(scrubTunnelProfileForPlaintextExport),
+ };
+ content = JSON.stringify(scrubbedData, null, 2);
}
if (isTauriRuntime()) {
@@ -9545,40 +9549,19 @@ export const useConnectionStore = defineStore("connection", () => {
async function applyConnectionsImport(preview: ConnectionConfigBundle, selectedConnectionIds?: Iterable<string>): Promise<{ count: number; layout?: SidebarLayout }> {
const selected = selectConnectionConfigBundle(preview, selectedConnectionIds);
- const imported = selected.connections.map((connection) => ({ ...connection }));
- let importedLayout = selected.layout;
- const importedConnections: ConnectionConfig[] = [];
- const importedConnectionIdMap = new Map<string, string>();
- for (const config of imported) {
- const duplicate = [...connections.value, ...importedConnections].find((connection) => connection.name === config.name && connection.host === config.host && connection.port === config.port);
- if (duplicate) {
- if (typeof config.id === "string") importedConnectionIdMap.set(config.id, duplicate.id);
- continue;
- }
- const importedId = config.id;
- config.id = uuid();
- if (typeof importedId === "string") importedConnectionIdMap.set(importedId, config.id);
- importedConnections.push(normalizeConnection(config));
- }
- const importedTunnelProfileIds = referencedTunnelProfileIds(importedConnections);
- const importedTunnelProfiles = filterTunnelProfilesByIds(selected.tunnelProfiles ?? [], importedTunnelProfileIds);
- if (importedTunnelProfiles.length) {
- const importedTunnelProfileStore = useTunnelProfileStore();
- await importedTunnelProfileStore.init();
- const merged = [...importedTunnelProfileStore.profiles];
- for (const profile of importedTunnelProfiles) {
- if (!profile || typeof profile.id !== "string" || !profile.id) continue;
- const index = merged.findIndex((existing) => existing.id === profile.id);
- if (index >= 0) merged[index] = profile;
- else merged.push(profile);
- }
- await importedTunnelProfileStore.saveProfiles(merged);
- }
- for (const connection of importedConnections) await addConnection(connection);
- if (importedLayout) {
- importedLayout = filterSidebarLayoutByConnectionIds(remapSidebarLayoutConnectionIds(importedLayout, importedConnectionIdMap), importedConnectionIdMap.values());
+ const importedTunnelProfileStore = useTunnelProfileStore();
+ await importedTunnelProfileStore.init();
+ const imported = prepareConnectionConfigImport(
+ selected,
+ connections.value,
+ importedTunnelProfileStore.profiles.map((profile) => profile.id),
+ uuid,
+ );
+ if (imported.tunnelProfiles?.length) {
+ await importedTunnelProfileStore.saveProfiles([...importedTunnelProfileStore.profiles, ...imported.tunnelProfiles]);
}
- return { count: importedConnections.length, layout: importedLayout };
+ for (const connection of imported.connections) await addConnection(normalizeConnection(connection));
+ return { count: imported.connections.length, layout: imported.layout };
}
async function importConnectionsFromFile(content: string, passphrase: string | null, selectedConnectionIds?: Iterable<string>): Promise<{ count: number; layout?: SidebarLayout }> {
diff --git a/apps/desktop/src/stores/migrationStore.spec.ts b/apps/desktop/src/stores/migrationStore.spec.ts
new file mode 100644
index 0000000000..09148ae9a6
--- /dev/null
+++ b/apps/desktop/src/stores/migrationStore.spec.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from "vitest";
+import { useMigrationStore } from "./migrationStore";
+import type { MigrationPreflight, MigrationReport } from "@/lib/backend/migration";
+
+const pending = (): MigrationPreflight => ({
+ migrationId: "secret-store-v1",
+ state: "pending",
+ needsMigration: true,
+ keyProviderAvailable: true,
+ keyCreationAllowed: false,
+ databasePlaintextCount: 2,
+ connectionCount: 1,
+ pluginSecretCount: 0,
+ aiSecretCount: 0,
+ tunnelSecretCount: 0,
+ syncCredentialCount: 0,
+ legacyJsonFiles: [],
+ backupRequired: true,
+});
+const done = (): MigrationPreflight => ({ ...pending(), state: "succeeded", needsMigration: false, databasePlaintextCount: 0, backupPath: "/tmp/backup" });
+const report: MigrationReport = { migrationId: "secret-store-v1", state: "succeeded", backupPath: "/tmp/backup", databasePlaintextCount: 2, legacyJsonFiles: [], verifiedSecretCount: 2 };
+
+describe("migration store", () => {
+ it("keeps the wizard blocked until explicit entry after a successful migration", async () => {
+ const status = vi.fn().mockResolvedValueOnce(pending()).mockResolvedValue(done());
+ const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn().mockResolvedValue(report), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
+ await store.initialize();
+ expect(store.blocking.value).toBe(true);
+ await store.start();
+ expect(store.state.report).toEqual(report);
+ expect(store.blocking.value).toBe(true);
+ store.enter();
+ expect(store.blocking.value).toBe(false);
+ });
+
+ it("preserves the report and status when cleanup fails", async () => {
+ const cleanup = vi.fn().mockRejectedValue(new Error("failed"));
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: cleanup });
+ await store.initialize();
+ store.state.report = report;
+ await store.cleanup();
+ expect(store.state.error).toBe("cleanupFailed");
+ expect(store.state.report).toEqual(report);
+ });
+
+ it("allows a completed migration with a retained backup to enter after restart", async () => {
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
+ await store.initialize();
+ expect(store.completed.value).toBe(true);
+ expect(store.blocking.value).toBe(false);
+ });
+
+ it("keeps status failures on the status retry path", async () => {
+ const status = vi
+ .fn()
+ .mockRejectedValueOnce(Object.assign(new Error("unavailable"), { backendError: { code: "KEY_PROVIDER_UNAVAILABLE", detail: "safe detail" } }))
+ .mockResolvedValue(done());
+ const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
+ await store.initialize();
+ expect(store.state.error).toBe("statusFailed");
+ expect(store.state.errorCode).toBeNull();
+ expect(store.state.errorMessage).toBeNull();
+ await store.initialize();
+ expect(store.state.error).toBeNull();
+ expect(store.completed.value).toBe(true);
+ });
+ it("discards arbitrary transport exception values in state and diagnostics", async () => {
+ const secret = "password=DO_NOT_EXPOSE";
+ const failure = Object.assign(new Error(secret), { backendError: { code: secret, detail: secret } });
+ const status = vi.fn().mockRejectedValue(failure);
+ const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn().mockRejectedValue(failure), migrationRetry: vi.fn().mockRejectedValue(failure), migrationCleanupBackups: vi.fn().mockRejectedValue(failure) });
+ for (const action of [store.initialize, store.start, store.retry, store.cleanup]) {
+ await action();
+ expect(JSON.stringify(store.state)).not.toContain(secret);
+ expect(JSON.stringify(store.diagnostic())).not.toContain(secret);
+ }
+ });
+
+ it("shows safe preflight errors even when the migration is pending", async () => {
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue({ ...pending(), errorCode: "MISSING_PERSISTENT_KEY", errorMessage: "Configure a persistent key." }), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
+ await store.initialize();
+ expect(store.state.error).toBe("migrationFailed");
+ expect(store.state.errorCode).toBe("MISSING_PERSISTENT_KEY");
+ expect(store.state.errorMessage).toBe("Configure a persistent key.");
+ });
+
+ it("does not show a failure for a managed key created by migration", async () => {
+ const store = useMigrationStore({
+ migrationStatus: vi.fn().mockResolvedValue({
+ ...pending(),
+ keyProviderAvailable: false,
+ keyCreationAllowed: true,
+ errorCode: "MISSING_MANAGED_KEY",
+ errorMessage: "A managed data-directory secret key will be created when migration starts",
+ }),
+ migrationStart: vi.fn(),
+ migrationRetry: vi.fn(),
+ migrationCleanupBackups: vi.fn(),
+ });
+
+ await store.initialize();
+
+ expect(store.state.error).toBeNull();
+ expect(store.state.errorCode).toBe("MISSING_MANAGED_KEY");
+ });
+
+ it("keeps completion through a failed cleanup and successful cleanup retry", async () => {
+ let finishCleanup!: () => void;
+ const cleanup = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("password=secret"))
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishCleanup = resolve;
+ }),
+ );
+ const retry = vi.fn();
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: retry, migrationCleanupBackups: cleanup });
+ await store.initialize();
+ await store.cleanup();
+ expect(store.state.error).toBe("cleanupFailed");
+ expect(store.state.step).toBe(3);
+ expect(store.completed.value).toBe(true);
+ expect(store.state.status?.backupPath).toBe("/tmp/backup");
+ const cleanupAttempt = store.cleanup();
+ expect(store.state.busy).toBe(true);
+ await store.cleanup();
+ expect(cleanup).toHaveBeenCalledTimes(2);
+ store.enter();
+ expect(store.state.entered).toBe(true);
+ finishCleanup();
+ await cleanupAttempt;
+ expect(store.state.busy).toBe(false);
+ expect(store.state.step).toBe(3);
+ expect(store.state.error).toBeNull();
+ expect(store.completed.value).toBe(true);
+ expect(store.state.status?.backupPath).toBeNull();
+ expect(retry).not.toHaveBeenCalled();
+ });
+
+ it("recovers when a lost action response is followed by verified completion", async () => {
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn().mockRejectedValue(new Error("response lost")), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
+ await store.start();
+ expect(store.state.step).toBe(3);
+ expect(store.state.error).toBeNull();
+ expect(store.state.busy).toBe(false);
+ });
+ it("retries a failed migration and completes without losing the error report", async () => {
+ const failed = { ...pending(), state: "failed" as const, errorCode: "BACKUP_FAILED", errorMessage: "Cannot create backup" };
+ const retry = vi.fn().mockResolvedValue(report);
+ const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValueOnce(failed).mockResolvedValue(done()), migrationStart: vi.fn().mockRejectedValue(new Error("failure")), migrationRetry: retry, migrationCleanupBackups: vi.fn() });
+ await store.start();
+ expect(store.state.errorCode).toBe("BACKUP_FAILED");
+ expect(store.diagnostic().actionError).toBe("migrationFailed");
+ await store.retry();
+ expect(retry).toHaveBeenCalledOnce();
+ expect(store.state.step).toBe(3);
+ expect(store.state.error).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/stores/migrationStore.ts b/apps/desktop/src/stores/migrationStore.ts
new file mode 100644
index 0000000000..b857b48d00
--- /dev/null
+++ b/apps/desktop/src/stores/migrationStore.ts
@@ -0,0 +1,111 @@
+import { computed, reactive } from "vue";
+import * as api from "@/lib/backend/api";
+import type { MigrationPreflight, MigrationReport } from "@/lib/backend/migration";
+
+type MigrationApi = Pick<typeof api, "migrationStatus" | "migrationStart" | "migrationRetry" | "migrationCleanupBackups">;
+
+// Each startup boundary owns its state; an action failure never erases its report.
+export function useMigrationStore(backend: MigrationApi = api) {
+ const state = reactive<{
+ status: MigrationPreflight | null;
+ report: MigrationReport | null;
+ loading: boolean;
+ busy: boolean;
+ error: "statusFailed" | "migrationFailed" | "cleanupFailed" | null;
+ errorCode: string | null;
+ errorMessage: string | null;
+ entered: boolean;
+ step: 1 | 2 | 3;
+ }>({ status: null, report: null, loading: true, busy: false, error: null, errorCode: null, errorMessage: null, entered: false, step: 1 });
+ const completed = computed(() => state.status !== null && !state.status.needsMigration && ["succeeded", "not_required"].includes(state.status.state));
+ // A managed data-directory key is intentionally created when migration
+ // starts. Its absence during the read-only preflight is actionable, not a
+ // migration failure, as long as the backend explicitly allows creation.
+ const hasBlockingError = () => Boolean(state.errorCode && !(state.errorCode === "MISSING_MANAGED_KEY" && state.status?.keyCreationAllowed === true));
+ const blocking = computed(() => state.loading || state.busy || state.error === "statusFailed" || !completed.value || (!state.entered && Boolean(state.report || state.status?.backupPath)));
+ function clearError() {
+ state.error = null;
+ state.errorCode = null;
+ state.errorMessage = null;
+ }
+ async function refreshStatus() {
+ // Only this endpoint returns classified, redacted migration errors. Transport
+ // exceptions may contain configuration values and must never enter UI state.
+ state.status = await backend.migrationStatus();
+ state.errorCode = state.status.errorCode ?? null;
+ state.errorMessage = state.status.errorMessage ?? null;
+ }
+ async function initialize() {
+ state.loading = true;
+ clearError();
+ try {
+ await refreshStatus();
+ state.step = completed.value ? 3 : 1;
+ // A completed migration only needs the success page in the session that
+ // performed it. On later launches, retained backups are recovery assets,
+ // not a reason to block the normal application startup.
+ state.entered = completed.value;
+ if (state.status?.state === "failed" || hasBlockingError()) state.error = "migrationFailed";
+ } catch {
+ state.error = "statusFailed";
+ } finally {
+ state.loading = false;
+ }
+ }
+ async function run(retry: boolean) {
+ if (state.busy) return;
+ state.busy = true;
+ state.step = 2;
+ clearError();
+ try {
+ state.report = await (retry ? backend.migrationRetry() : backend.migrationStart());
+ } catch {
+ state.error = "migrationFailed";
+ }
+ try {
+ await refreshStatus();
+ if (completed.value) {
+ state.step = 3;
+ state.error = null;
+ }
+ if (!completed.value || hasBlockingError()) state.error = "migrationFailed";
+ } catch {
+ state.error = "statusFailed";
+ } finally {
+ state.busy = false;
+ }
+ }
+ async function cleanup() {
+ if (state.busy) return;
+ state.busy = true;
+ clearError();
+ try {
+ await backend.migrationCleanupBackups();
+ if (state.status) state.status.backupPath = null;
+ if (state.report) state.report.backupPath = null;
+ } catch {
+ state.error = "cleanupFailed";
+ } finally {
+ state.busy = false;
+ }
+ }
+ function diagnostic() {
+ const s = state.status;
+ return {
+ migrationId: s?.migrationId,
+ actionError: state.error,
+ step: state.step,
+ needsMigration: s?.needsMigration,
+ legacyJsonFiles: s?.legacyJsonFiles,
+ state: s?.state,
+ counts: s ? { connections: s.connectionCount, databasePlaintext: s.databasePlaintextCount, plugin: s.pluginSecretCount, ai: s.aiSecretCount, tunnel: s.tunnelSecretCount, sync: s.syncCredentialCount } : {},
+ keyProviderAvailable: s?.keyProviderAvailable,
+ backupPath: s?.backupPath,
+ errorCode: state.errorCode,
+ };
+ }
+ function enter() {
+ if (completed.value && !state.busy) state.entered = true;
+ }
+ return { state, blocking, completed, initialize, start: () => run(false), retry: () => run(true), cleanup, diagnostic, enter };
+}
diff --git a/crates/dbx-core/Cargo.toml b/crates/dbx-core/Cargo.toml
index c8a1af0c90..551facfb9b 100644
--- a/crates/dbx-core/Cargo.toml
+++ b/crates/dbx-core/Cargo.toml
@@ -62,6 +62,7 @@ aes-gcm = "0.10"
aes = "0.8"
cbc = "0.1"
argon2 = "0.5"
+keyring = { version = "3.6.3", default-features = false, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }
sha2 = "0.10"
async-trait = "0.1"
bytes = "1"
diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rs
index 0b7f1d3e86..356c7cfb68 100644
--- a/crates/dbx-core/src/persistence/cloud_sync.rs
+++ b/crates/dbx-core/src/persistence/cloud_sync.rs
@@ -14,14 +14,23 @@ use std::net::{IpAddr, Ipv4Addr};
use crate::ai::AiConfigItem;
use crate::connection_secrets::{
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
- MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY,
- MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
+ MQTT_AUTH_PASSWORD_KEY, MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY,
+ MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
+ PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
use crate::saved_sql::SavedSqlLibrary;
-use crate::storage::{DesktopSettings, SnippetPendingCleanup, Storage};
+use crate::storage::{
+ DesktopSettings, SnippetPendingCleanup, Storage, SyncImportCredential, SyncImportPlan, SyncImportSecret,
+};
-const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
+/// Version 2 introduces an explicit, versioned secrets transport payload. We
+/// still accept version 1 snapshots on import so upgrading does not strand
+/// existing devices.
+const SNAPSHOT_SCHEMA_VERSION: u32 = 2;
+const LEGACY_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
+const SENSITIVE_PAYLOAD_VERSION: u32 = 2;
+const SENSITIVE_PAYLOAD_TYPE: &str = "dbx-sync-secrets";
const ENCRYPTED_SNIPPET_SNAPSHOT_FORMAT: &str = "dbx-encrypted-sync-snapshot";
const ENCRYPTED_SNIPPET_SNAPSHOT_VERSION: u32 = 1;
const DEFAULT_REMOTE_PATH: &str = "DBX/sync/snapshot.json";
@@ -36,12 +45,14 @@ const SECRET_KEYS: &[&str] = &[
"proxy_password",
"redis_sentinel_password",
"connection_string",
+ "url_params",
"init_script",
MQ_AUTH_TOKEN_KEY,
MQ_AUTH_PASSWORD_KEY,
MQ_AUTH_API_KEY_VALUE_KEY,
MQ_AUTH_CLIENT_SECRET_KEY,
MQ_TOKEN_SIGNING_KEY,
+ MQTT_AUTH_PASSWORD_KEY,
NACOS_AUTH_PASSWORD_KEY,
NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
@@ -171,6 +182,13 @@ pub struct EncryptedSecretsBlob {
pub salt: String,
pub nonce: String,
pub ciphertext: String,
+ /// Present for the v2 sync transport envelope. Optional for backwards
+ /// compatibility with v1 blobs used by local saved credentials.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub payload_type: Option<String>,
+ /// Context authenticated as AES-GCM additional authenticated data.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub aad: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -185,6 +203,16 @@ struct EncryptedSnippetSnapshot {
#[serde(rename_all = "camelCase")]
pub struct SensitiveSyncPayload {
pub connection_secrets: Vec<ConnectionSecretSnapshot>,
+ /// Whether plugin connection secrets are authoritative in this payload.
+ /// Older payloads did not carry this marker and always included plugin
+ /// secrets when secrets were enabled, so the compatibility default is true.
+ #[serde(default = "default_plugin_secrets_included")]
+ pub plugin_secrets_included: bool,
+ /// WebDAV and GitHub/Gitee credentials are included only inside the
+ /// passphrase-protected payload. They are re-wrapped with the destination
+ /// device key on import and never appear in the public snapshot.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sync_credentials: Option<Vec<SyncCredentialSnapshot>>,
// None = legacy snapshot (fall through to ai_config migration),
// Some(vec) = explicit state (empty vec means all configs were deleted)
pub ai_configs: Option<Vec<AiConfigItem>>,
@@ -196,6 +224,17 @@ pub struct SensitiveSyncPayload {
pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
}
+fn default_plugin_secrets_included() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncCredentialSnapshot {
+ pub account: String,
+ pub secret: String,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionSecretSnapshot {
@@ -213,6 +252,19 @@ pub struct ApplySnapshotOptions<'a> {
pub restore_secrets: bool,
}
+/// Controls which sensitive values are placed in a sync snapshot. A
+/// passphrase is intentionally not enough to opt in: callers must explicitly
+/// set `include_secrets`, which prevents an accidental upload of credentials
+/// when a saved passphrase happens to be available.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SyncExportOptions<'a> {
+ pub include_secrets: bool,
+ pub sync_passphrase: Option<&'a str>,
+ pub include_ai_secrets: bool,
+ pub include_tunnel_secrets: bool,
+ pub include_plugin_secrets: bool,
+}
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplySnapshotSummary {
@@ -253,15 +305,42 @@ pub async fn build_sync_snapshot(
app_version: impl Into<String>,
editor_settings: Option<serde_json::Value>,
secrets_passphrase: Option<&str>,
+) -> Result<SyncSnapshot, String> {
+ // Keep the historical API source-compatible. Existing callers that pass
+ // a non-empty passphrase have always explicitly requested a secrets sync;
+ // new callers should use `build_sync_snapshot_with_options` so the intent
+ // is represented directly.
+ let include_secrets = normalized_passphrase(secrets_passphrase).is_some();
+ build_sync_snapshot_with_options(
+ storage,
+ app_version,
+ editor_settings,
+ SyncExportOptions {
+ include_secrets,
+ sync_passphrase: secrets_passphrase,
+ include_ai_secrets: include_secrets,
+ include_tunnel_secrets: include_secrets,
+ include_plugin_secrets: include_secrets,
+ },
+ )
+ .await
+}
+
+pub async fn build_sync_snapshot_with_options(
+ storage: &Storage,
+ app_version: impl Into<String>,
+ editor_settings: Option<serde_json::Value>,
+ options: SyncExportOptions<'_>,
) -> Result<SyncSnapshot, String> {
let mut connections = storage.load_connections().await?;
let mut tunnel_profiles = storage.load_tunnel_profiles().await?;
- let encrypted_secrets = match normalized_passphrase(secrets_passphrase) {
- Some(passphrase) => Some(encrypt_sensitive_payload(
- &build_sensitive_payload(storage, &connections, &tunnel_profiles).await?,
- passphrase,
- )?),
- None => None,
+ let encrypted_secrets = if options.include_secrets {
+ let passphrase = normalized_passphrase(options.sync_passphrase)
+ .ok_or_else(|| "A sync password is required when including synced secrets.".to_string())?;
+ let payload = build_sensitive_payload_with_options(storage, &connections, &tunnel_profiles, options).await?;
+ Some(encrypt_sensitive_payload(&payload, passphrase)?)
+ } else {
+ None
};
let mqtt_subscriptions = Some(extract_mqtt_subscriptions(&connections)?);
for config in &mut connections {
@@ -294,10 +373,36 @@ pub async fn build_sync_snapshot_with_saved_secrets(
secrets_passphrase: Option<&str>,
) -> Result<SyncSnapshot, String> {
match normalized_passphrase(secrets_passphrase) {
- Some(passphrase) => build_sync_snapshot(storage, app_version, editor_settings, Some(passphrase)).await,
+ Some(passphrase) => {
+ build_sync_snapshot_with_options(
+ storage,
+ app_version,
+ editor_settings,
+ SyncExportOptions {
+ include_secrets: true,
+ sync_passphrase: Some(passphrase),
+ include_ai_secrets: true,
+ include_tunnel_secrets: true,
+ include_plugin_secrets: true,
+ },
+ )
+ .await
+ }
None => {
let saved_passphrase = resolve_webdav_sync_secrets_passphrase(storage).await?;
- build_sync_snapshot(storage, app_version, editor_settings, saved_passphrase.as_deref()).await
+ build_sync_snapshot_with_options(
+ storage,
+ app_version,
+ editor_settings,
+ SyncExportOptions {
+ include_secrets: saved_passphrase.is_some(),
+ sync_passphrase: saved_passphrase.as_deref(),
+ include_ai_secrets: saved_passphrase.is_some(),
+ include_tunnel_secrets: saved_passphrase.is_some(),
+ include_plugin_secrets: saved_passphrase.is_some(),
+ },
+ )
+ .await
}
}
}
@@ -307,12 +412,13 @@ pub async fn apply_sync_snapshot(
snapshot: &SyncSnapshot,
options: ApplySnapshotOptions<'_>,
) -> Result<ApplySnapshotSummary, String> {
- if snapshot.schema_version != SNAPSHOT_SCHEMA_VERSION {
+ if !matches!(snapshot.schema_version, LEGACY_SNAPSHOT_SCHEMA_VERSION | SNAPSHOT_SCHEMA_VERSION) {
return Err(format!("Unsupported sync snapshot schema version: {}", snapshot.schema_version));
}
+ validate_sync_snapshot_metadata(snapshot)?;
let encrypted_secrets_present = snapshot.encrypted_secrets.is_some();
- let sensitive_payload =
+ let mut sensitive_payload =
match (options.restore_secrets, &snapshot.encrypted_secrets, normalized_passphrase(options.secrets_passphrase))
{
(true, Some(blob), Some(passphrase)) => Some(decrypt_sensitive_payload(blob, passphrase)?),
@@ -321,6 +427,47 @@ pub async fn apply_sync_snapshot(
(true, Some(_), None) => return Err("A sync password is required to restore synced secrets.".to_string()),
_ => None,
};
+ // Version-1 snapshots could carry hydrated credentials directly in the
+ // public connection JSON. Treat an explicit secret restore as the
+ // migration consent: extract those values before scrubbing metadata, then
+ // send them through the same destination SecretStore transaction used by
+ // modern encrypted payloads. With restore disabled, metadata still
+ // imports but legacy plaintext credentials are discarded.
+ if sensitive_payload.is_none() && options.restore_secrets && snapshot.encrypted_secrets.is_none() {
+ let tunnel_profiles = snapshot.tunnel_profiles.clone().unwrap_or_default();
+ let has_legacy_secrets = snapshot.connections.iter().any(connection_has_inline_secrets)
+ || tunnel_profiles.iter().any(|profile| {
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ scrubbed != *profile
+ });
+ if has_legacy_secrets {
+ sensitive_payload = Some(
+ build_sensitive_payload_with_options(
+ storage,
+ &snapshot.connections,
+ &tunnel_profiles,
+ SyncExportOptions {
+ include_secrets: false,
+ sync_passphrase: None,
+ include_ai_secrets: false,
+ include_tunnel_secrets: true,
+ include_plugin_secrets: true,
+ },
+ )
+ .await?,
+ );
+ }
+ }
+ if let Some(payload) = &sensitive_payload {
+ validate_sensitive_payload_targets(payload, &snapshot.connections, snapshot.tunnel_profiles.as_deref())?;
+ }
+ if let Some(payload) = &sensitive_payload {
+ // Validate the complete decrypted payload before touching metadata or
+ // secrets. This keeps malformed/ambiguous transport data from
+ // producing a partially-applied restore.
+ validate_sensitive_payload(payload)?;
+ }
let mut connections = snapshot.connections.clone();
if let Some(mqtt_subscriptions) = &snapshot.mqtt_subscriptions {
@@ -336,21 +483,143 @@ pub async fn apply_sync_snapshot(
scrub_connection_secrets(config);
}
- storage.save_connection_metadata_preserving_secrets(&connections).await?;
- if let Some(profiles) = &snapshot.tunnel_profiles {
- storage.save_tunnel_profiles_preserving_secrets(profiles).await?;
+ let (connection_secrets, preserve_plugin_secrets, ai_configs, tunnel_secret_profiles, sync_payload_credentials) =
+ if let Some(payload) = &sensitive_payload {
+ let ai_configs = if let Some(configs) = &payload.ai_configs {
+ Some(configs.clone())
+ } else {
+ payload.ai_config.as_ref().map(|old_config| {
+ vec![AiConfigItem {
+ id: AiConfigItem::new_id(),
+ name: old_config.provider.as_str().to_string(),
+ is_default: true,
+ config: old_config.clone(),
+ }]
+ })
+ };
+ (
+ Some(
+ payload
+ .connection_secrets
+ .iter()
+ .filter(|secret| {
+ !(matches!(
+ secret.key.as_str(),
+ "password" | NACOS_AUTH_PASSWORD_KEY | NACOS_RNACOS_CONSOLE_PASSWORD_KEY
+ ) && connections
+ .iter()
+ .any(|config| config.id == secret.connection_id && !config.save_password))
+ })
+ .map(|secret| SyncImportSecret {
+ connection_id: secret.connection_id.clone(),
+ key: secret.key.clone(),
+ secret: secret.secret.clone(),
+ })
+ .collect(),
+ ),
+ !payload.plugin_secrets_included,
+ ai_configs,
+ payload.tunnel_profiles.clone(),
+ payload.sync_credentials.clone(),
+ )
+ } else {
+ (None, false, None, None, None)
+ };
+ let sync_credentials = if let Some(credentials) = sync_payload_credentials {
+ let local_secret =
+ if credentials.is_empty() { None } else { Some(storage.load_or_create_local_device_secret().await?) };
+ Some(
+ credentials
+ .into_iter()
+ .map(|credential| {
+ let blob = local_secret
+ .as_deref()
+ .ok_or_else(|| "local sync credential key is unavailable".to_string())
+ .and_then(|secret| encrypt_text_with_secret(&credential.secret, secret))
+ .and_then(|blob| serde_json::to_string(&blob).map_err(|error| error.to_string()))?;
+ Ok(SyncImportCredential { account: credential.account.trim().to_string(), blob })
+ })
+ .collect::<Result<Vec<_>, String>>()?,
+ )
+ } else {
+ None
+ };
+ let sync_tunnel_profiles = snapshot.tunnel_profiles.clone().or_else(|| {
+ tunnel_secret_profiles.as_ref().map(|profiles| {
+ profiles
+ .iter()
+ .map(|profile| {
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ scrubbed
+ })
+ .collect()
+ })
+ });
+ storage
+ .apply_sync_import_transaction(SyncImportPlan {
+ connections,
+ tunnel_profiles: sync_tunnel_profiles,
+ tunnel_secret_profiles,
+ sidebar_layout: snapshot.sidebar_layout.clone(),
+ pinned_tree_node_ids: snapshot.pinned_tree_node_ids.clone(),
+ saved_sql: snapshot.saved_sql.clone(),
+ desktop_settings: snapshot.desktop_settings.clone(),
+ editor_settings: snapshot.editor_settings.clone(),
+ connection_secrets,
+ preserve_plugin_secrets,
+ sync_credentials,
+ ai_configs,
+ })
+ .await?;
+ Ok(ApplySnapshotSummary { encrypted_secrets_present, secrets_applied: sensitive_payload.is_some() })
+}
+
+fn validate_sensitive_payload_targets(
+ payload: &SensitiveSyncPayload,
+ connections: &[ConnectionConfig],
+ tunnel_profiles: Option<&[TransportLayerConfig]>,
+) -> Result<(), String> {
+ let connection_ids = connections.iter().map(|config| config.id.as_str()).collect::<HashSet<_>>();
+ if let Some(secret) =
+ payload.connection_secrets.iter().find(|secret| !connection_ids.contains(secret.connection_id.as_str()))
+ {
+ return Err(format!("Synced secret targets unknown connection '{}'.", secret.connection_id));
}
- if let Some(layout) = &snapshot.sidebar_layout {
- storage.save_sidebar_layout(layout).await?;
+ if let Some(synced_profiles) = &payload.tunnel_profiles {
+ if let Some(public_profiles) = tunnel_profiles {
+ let profile_ids = public_profiles.iter().map(TransportLayerConfig::id).collect::<HashSet<_>>();
+ if let Some(profile) = synced_profiles.iter().find(|profile| !profile_ids.contains(profile.id())) {
+ return Err(format!("Synced secret targets unknown tunnel profile '{}'.", profile.id()));
+ }
+ }
}
- storage.save_pinned_tree_node_ids(&snapshot.pinned_tree_node_ids).await?;
- storage.replace_saved_sql_library(&snapshot.saved_sql).await?;
- storage.save_desktop_settings(&snapshot.desktop_settings).await?;
- if let Some(payload) = &sensitive_payload {
- clear_connection_secrets(storage, &connections).await?;
- apply_sensitive_payload(storage, payload, &connections).await?;
+ Ok(())
+}
+
+fn validate_sync_snapshot_metadata(snapshot: &SyncSnapshot) -> Result<(), String> {
+ let mut connection_ids = HashSet::new();
+ for config in &snapshot.connections {
+ if config.id.trim().is_empty() {
+ return Err("Sync snapshot contains a connection with an empty id.".to_string());
+ }
+ if !connection_ids.insert(config.id.as_str()) {
+ return Err(format!("Sync snapshot contains duplicate connection id '{}'.", config.id));
+ }
}
- Ok(ApplySnapshotSummary { encrypted_secrets_present, secrets_applied: sensitive_payload.is_some() })
+ if let Some(profiles) = &snapshot.tunnel_profiles {
+ let mut profile_ids = HashSet::new();
+ for profile in profiles {
+ let id = profile.id().trim();
+ if id.is_empty() {
+ return Err("Sync snapshot contains a tunnel profile with an empty id.".to_string());
+ }
+ if !profile_ids.insert(id) {
+ return Err(format!("Sync snapshot contains duplicate tunnel profile id '{id}'."));
+ }
+ }
+ }
+ Ok(())
}
pub struct WebDavClient {
@@ -1062,6 +1331,7 @@ fn scrub_connection_secrets(config: &mut ConnectionConfig) {
}
}
config.redis_sentinel_password.clear();
+ config.url_params = config.url_params.as_deref().map(scrub_url_params);
config.connection_string = None;
config.init_script = None;
scrub_mqtt_auth_secrets(config);
@@ -1074,18 +1344,35 @@ fn scrub_connection_secrets(config: &mut ConnectionConfig) {
config.connection_secrets.clear();
}
-fn scrub_mqtt_auth_secrets(config: &mut ConnectionConfig) {
- if config.db_type != DatabaseType::Mqtt {
- return;
- }
- let Some(auth) = config.external_config.as_mut().and_then(|external| external.get_mut("auth")) else {
- return;
- };
- if auth.get("kind").and_then(serde_json::Value::as_str) == Some("password") {
- if let Some(object) = auth.as_object_mut() {
- object.insert("password".to_string(), serde_json::Value::String(String::new()));
- }
- }
+fn connection_has_inline_secrets(config: &ConnectionConfig) -> bool {
+ let mut scrubbed = config.clone();
+ scrub_connection_secrets(&mut scrubbed);
+ scrubbed != *config
+}
+
+fn scrub_url_params(value: &str) -> String {
+ value
+ .split('&')
+ .map(|part| {
+ let Some((key, _value)) = part.split_once('=') else {
+ return part.to_string();
+ };
+ let normalized = key.trim().to_ascii_lowercase().replace(['_', '-'], "");
+ if normalized.contains("password")
+ || normalized.contains("passphrase")
+ || normalized.contains("secret")
+ || normalized.contains("token")
+ || normalized.contains("apikey")
+ || normalized.contains("privatekey")
+ || normalized.contains("clientsecret")
+ {
+ format!("{key}=")
+ } else {
+ part.to_string()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("&")
}
fn webdav_password_account(config: &WebDavConfig) -> String {
@@ -1096,10 +1383,32 @@ fn webdav_password_account(config: &WebDavConfig) -> String {
URL_SAFE_NO_PAD.encode(hasher.finalize())
}
+#[cfg(test)]
async fn build_sensitive_payload(
storage: &Storage,
connections: &[ConnectionConfig],
tunnel_profiles: &[TransportLayerConfig],
+) -> Result<SensitiveSyncPayload, String> {
+ build_sensitive_payload_with_options(
+ storage,
+ connections,
+ tunnel_profiles,
+ SyncExportOptions {
+ include_secrets: true,
+ sync_passphrase: None,
+ include_ai_secrets: true,
+ include_tunnel_secrets: true,
+ include_plugin_secrets: true,
+ },
+ )
+ .await
+}
+
+async fn build_sensitive_payload_with_options(
+ storage: &Storage,
+ connections: &[ConnectionConfig],
+ tunnel_profiles: &[TransportLayerConfig],
+ options: SyncExportOptions<'_>,
) -> Result<SensitiveSyncPayload, String> {
let mut connection_secrets = Vec::new();
for config in connections {
@@ -1108,6 +1417,7 @@ async fn build_sensitive_payload(
push_secret(&mut connection_secrets, &config.id, "password", &config.password);
}
push_secret(&mut connection_secrets, &config.id, "init_script", config.init_script.as_deref().unwrap_or(""));
+ push_secret(&mut connection_secrets, &config.id, "url_params", config.url_params.as_deref().unwrap_or(""));
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(ssh) => {
@@ -1147,23 +1457,55 @@ async fn build_sensitive_payload(
push_secret(&mut connection_secrets, &config.id, "connection_string", connection_string);
}
push_mq_external_config_secrets(&mut connection_secrets, config);
+ push_mqtt_external_config_secret(&mut connection_secrets, config);
push_cassandra_tls_secrets(&mut connection_secrets, config);
if config.save_password {
push_nacos_external_config_secrets(&mut connection_secrets, config);
+ }
+ // Plugin secrets are independent of the primary connection password.
+ // A plugin may persist a token while `save_password` is disabled, so
+ // gate these values only on the explicit plugin export option.
+ if options.include_plugin_secrets {
for (key, secret) in &config.connection_secrets {
push_secret(&mut connection_secrets, &config.id, &plugin_connection_secret_key(key)?, secret);
}
}
}
+ // Loading AI configurations includes decrypting their secret blobs. A
+ // provider/decryption failure must abort the export: treating it as an
+ // empty list would produce a valid-looking snapshot that clears AI
+ // configurations on the destination during restore.
+ let ai_configs = if options.include_ai_secrets { Some(storage.load_ai_configs().await?) } else { None };
+ let sync_credentials = if options.include_secrets { Some(load_sync_credentials(storage).await?) } else { None };
Ok(SensitiveSyncPayload {
connection_secrets,
- ai_configs: Some(storage.load_ai_configs().await.unwrap_or_default()),
+ plugin_secrets_included: options.include_plugin_secrets,
+ sync_credentials,
+ ai_configs,
ai_config: None,
- tunnel_profiles: Some(tunnel_profiles.to_vec()),
+ tunnel_profiles: options.include_tunnel_secrets.then(|| tunnel_profiles.to_vec()),
})
}
+async fn load_sync_credentials(storage: &Storage) -> Result<Vec<SyncCredentialSnapshot>, String> {
+ let accounts = storage.load_webdav_password_accounts().await?;
+ if accounts.is_empty() {
+ return Ok(Vec::new());
+ }
+ let local_secret = storage.load_or_create_local_device_secret().await?;
+ let mut credentials = Vec::new();
+ for account in accounts {
+ let Some(value) = storage.load_webdav_password_blob(&account).await? else {
+ continue;
+ };
+ let blob: EncryptedSecretsBlob = serde_json::from_value(value).map_err(|error| error.to_string())?;
+ let secret = decrypt_text_with_secret(&blob, &local_secret)?;
+ credentials.push(SyncCredentialSnapshot { account, secret });
+ }
+ Ok(credentials)
+}
+
fn push_mq_external_config_secrets(secrets: &mut Vec<ConnectionSecretSnapshot>, config: &ConnectionConfig) {
let Some(external_config) = config.external_config.as_ref() else {
return;
@@ -1184,6 +1526,23 @@ fn push_mq_external_config_secrets(secrets: &mut Vec<ConnectionSecretSnapshot>,
}
}
+fn push_mqtt_external_config_secret(secrets: &mut Vec<ConnectionSecretSnapshot>, config: &ConnectionConfig) {
+ if config.db_type != DatabaseType::Mqtt {
+ return;
+ }
+ let Some(auth) = config
+ .external_config
+ .as_ref()
+ .and_then(|external| external.get("auth"))
+ .and_then(serde_json::Value::as_object)
+ else {
+ return;
+ };
+ if auth.get("kind").and_then(serde_json::Value::as_str) == Some("password") {
+ push_json_secret(secrets, &config.id, MQTT_AUTH_PASSWORD_KEY, auth, "password");
+ }
+}
+
fn scrub_mq_external_config_secrets(config: &mut ConnectionConfig) {
if config.db_type != DatabaseType::MessageQueue {
return;
@@ -1205,6 +1564,23 @@ fn scrub_mq_external_config_secrets(config: &mut ConnectionConfig) {
}
}
+fn scrub_mqtt_auth_secrets(config: &mut ConnectionConfig) {
+ if config.db_type != DatabaseType::Mqtt {
+ return;
+ }
+ let Some(auth) = config
+ .external_config
+ .as_mut()
+ .and_then(|external| external.get_mut("auth"))
+ .and_then(serde_json::Value::as_object_mut)
+ else {
+ return;
+ };
+ if auth.get("kind").and_then(serde_json::Value::as_str) == Some("password") {
+ scrub_json_secret(auth, "password");
+ }
+}
+
fn push_cassandra_tls_secrets(secrets: &mut Vec<ConnectionSecretSnapshot>, config: &ConnectionConfig) {
if config.db_type != DatabaseType::Cassandra {
return;
@@ -1318,6 +1694,7 @@ fn scrub_json_secret(object: &mut serde_json::Map<String, serde_json::Value>, fi
}
}
+#[cfg(test)]
async fn apply_sensitive_payload(
storage: &Storage,
payload: &SensitiveSyncPayload,
@@ -1362,24 +1739,61 @@ async fn apply_sensitive_payload(
Ok(())
}
-async fn clear_connection_secrets(storage: &Storage, connections: &[ConnectionConfig]) -> Result<(), String> {
- for config in connections {
- for key in SECRET_KEYS {
- storage.delete_secret(&config.id, key).await?;
+fn validate_sensitive_payload(payload: &SensitiveSyncPayload) -> Result<(), String> {
+ let mut seen = HashSet::new();
+ for secret in &payload.connection_secrets {
+ if secret.connection_id.trim().is_empty() || secret.key.trim().is_empty() {
+ return Err("Synced secrets contain an empty connection id or key.".to_string());
}
- storage.delete_secret_prefix(&config.id, PLUGIN_CONNECTION_SECRET_PREFIX).await?;
- for (index, layer) in config.transport_layers.iter().enumerate() {
- match layer {
- TransportLayerConfig::Ssh(_) => {
- storage.delete_secret(&config.id, &transport_layer_ssh_password_key(index, layer)).await?;
- storage.delete_secret(&config.id, &transport_layer_ssh_key_passphrase_key(index, layer)).await?;
- }
- TransportLayerConfig::Proxy(_) => {
- storage.delete_secret(&config.id, &transport_layer_proxy_password_key(index, layer)).await?;
- }
- TransportLayerConfig::HttpTunnel(_) => {
- storage.delete_secret(&config.id, &transport_layer_http_tunnel_token_key(index, layer)).await?;
- }
+ let accepted = SECRET_KEYS.contains(&secret.key.as_str())
+ || secret.key.starts_with(SSH_TUNNEL_SECRET_PREFIX)
+ || secret.key.starts_with(TRANSPORT_LAYER_SECRET_PREFIX)
+ || secret.key.starts_with(PLUGIN_CONNECTION_SECRET_PREFIX);
+ if !accepted {
+ return Err(format!("Synced secrets contain unsupported key '{}'.", secret.key));
+ }
+ if secret.key.starts_with(PLUGIN_CONNECTION_SECRET_PREFIX)
+ && secret.key.len() == PLUGIN_CONNECTION_SECRET_PREFIX.len()
+ {
+ return Err("Synced plugin secrets contain an empty field name.".to_string());
+ }
+ if !seen.insert((&secret.connection_id, &secret.key)) {
+ return Err(format!("Synced secrets contain a duplicate key: {} / {}", secret.connection_id, secret.key));
+ }
+ }
+ if let Some(configs) = &payload.ai_configs {
+ let mut ids = HashSet::new();
+ for config in configs {
+ if config.id.trim().is_empty() {
+ return Err("Synced AI configs contain an empty id.".to_string());
+ }
+ if !ids.insert(config.id.as_str()) {
+ return Err(format!("Synced AI configs contain duplicate id '{}'.", config.id));
+ }
+ }
+ }
+ let mut seen_accounts = HashSet::new();
+ for credential in payload.sync_credentials.iter().flatten() {
+ let account = credential.account.trim();
+ if account.is_empty() || account.len() > 512 || account.contains('\0') {
+ return Err("Synced credentials contain an invalid account name.".to_string());
+ }
+ if credential.secret.is_empty() {
+ return Err(format!("Synced credential '{account}' has an empty secret."));
+ }
+ if !seen_accounts.insert(account) {
+ return Err(format!("Synced credentials contain duplicate account '{account}'."));
+ }
+ }
+ if let Some(profiles) = &payload.tunnel_profiles {
+ let mut profile_ids = HashSet::new();
+ for profile in profiles {
+ let id = profile.id().trim();
+ if id.is_empty() {
+ return Err("Synced secrets contain a tunnel profile with an empty id.".to_string());
+ }
+ if !profile_ids.insert(id) {
+ return Err(format!("Synced secrets contain duplicate tunnel profile id '{id}'."));
}
}
}
@@ -1413,11 +1827,11 @@ fn transport_layer_http_tunnel_token_key(index: usize, layer: &TransportLayerCon
fn encrypt_sensitive_payload(payload: &SensitiveSyncPayload, passphrase: &str) -> Result<EncryptedSecretsBlob, String> {
let plaintext = serde_json::to_vec(payload).map_err(|e| e.to_string())?;
- encrypt_bytes_with_secret(&plaintext, passphrase)
+ encrypt_bytes_with_secret_context(&plaintext, passphrase, SENSITIVE_PAYLOAD_TYPE)
}
fn decrypt_sensitive_payload(blob: &EncryptedSecretsBlob, passphrase: &str) -> Result<SensitiveSyncPayload, String> {
- let plaintext = decrypt_bytes_with_secret(blob, passphrase)
+ let plaintext = decrypt_sensitive_bytes(blob, passphrase)
.map_err(|_| "Failed to decrypt synced secrets. Check the sync password.".to_string())?;
serde_json::from_slice(&plaintext).map_err(|e| e.to_string())
}
@@ -1526,9 +1940,65 @@ fn encrypt_bytes_with_secret(plaintext: &[u8], secret: &str) -> Result<Encrypted
salt: BASE64.encode(salt),
nonce: BASE64.encode(nonce),
ciphertext: BASE64.encode(ciphertext),
+ payload_type: None,
+ aad: None,
})
}
+fn encrypt_bytes_with_secret_context(
+ plaintext: &[u8],
+ secret: &str,
+ context: &str,
+) -> Result<EncryptedSecretsBlob, String> {
+ let mut salt = [0u8; 16];
+ let mut nonce = [0u8; 12];
+ OsRng.fill_bytes(&mut salt);
+ OsRng.fill_bytes(&mut nonce);
+ let key = derive_secret_key(secret, &salt)?;
+ let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?;
+ let ciphertext = cipher
+ .encrypt(Nonce::from_slice(&nonce), aes_gcm::aead::Payload { msg: plaintext, aad: context.as_bytes() })
+ .map_err(|e| e.to_string())?;
+ Ok(EncryptedSecretsBlob {
+ version: SENSITIVE_PAYLOAD_VERSION,
+ kdf: "argon2id".to_string(),
+ cipher: "aes-256-gcm".to_string(),
+ salt: BASE64.encode(salt),
+ nonce: BASE64.encode(nonce),
+ ciphertext: BASE64.encode(ciphertext),
+ payload_type: Some(context.to_string()),
+ aad: Some(context.to_string()),
+ })
+}
+
+fn decrypt_sensitive_bytes(blob: &EncryptedSecretsBlob, secret: &str) -> Result<Vec<u8>, String> {
+ if blob.version == 1 {
+ return decrypt_bytes_with_secret(blob, secret);
+ }
+ if blob.version != SENSITIVE_PAYLOAD_VERSION
+ || blob.kdf != "argon2id"
+ || blob.cipher != "aes-256-gcm"
+ || blob.payload_type.as_deref() != Some(SENSITIVE_PAYLOAD_TYPE)
+ || blob.aad.as_deref() != Some(SENSITIVE_PAYLOAD_TYPE)
+ {
+ return Err("Unsupported encrypted secrets format".to_string());
+ }
+ let salt = BASE64.decode(&blob.salt).map_err(|e| e.to_string())?;
+ let nonce = BASE64.decode(&blob.nonce).map_err(|e| e.to_string())?;
+ let ciphertext = BASE64.decode(&blob.ciphertext).map_err(|e| e.to_string())?;
+ if nonce.len() != 12 {
+ return Err("Invalid encrypted secrets nonce".to_string());
+ }
+ let key = derive_secret_key(secret, &salt)?;
+ let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?;
+ cipher
+ .decrypt(
+ Nonce::from_slice(&nonce),
+ aes_gcm::aead::Payload { msg: ciphertext.as_ref(), aad: SENSITIVE_PAYLOAD_TYPE.as_bytes() },
+ )
+ .map_err(|_| "Failed to decrypt synced secrets.".to_string())
+}
+
fn decrypt_bytes_with_secret(blob: &EncryptedSecretsBlob, secret: &str) -> Result<Vec<u8>, String> {
if blob.version != 1 || blob.kdf != "argon2id" || blob.cipher != "aes-256-gcm" {
return Err("Unsupported encrypted secrets format".to_string());
@@ -1771,18 +2241,19 @@ fn parent_collection_paths(remote_path: &str) -> Vec<String> {
mod tests {
use super::{
apply_sensitive_payload, apply_sync_snapshot, build_sensitive_payload, build_sync_snapshot,
- build_sync_snapshot_with_saved_secrets, decrypt_sensitive_payload, encrypt_sensitive_payload,
- encrypt_snippet_snapshot, finalize_snippet_migration, forget_webdav_sync_secrets_passphrase,
- gitee_snippet_payload, gitlab_instance_url, is_legacy_dbx_snapshot, normalized_remote_path,
- parent_collection_paths, parse_legacy_dbx_snapshot, parse_snippet_snapshot, prepare_legacy_snippet_snapshot,
- resolve_snippet_token, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
- save_snippet_sync_id, save_snippet_sync_id_for_instance, save_snippet_token,
+ build_sync_snapshot_with_options, build_sync_snapshot_with_saved_secrets, decrypt_sensitive_payload,
+ encrypt_sensitive_payload, encrypt_snippet_snapshot, finalize_snippet_migration,
+ forget_webdav_sync_secrets_passphrase, gitee_snippet_payload, gitlab_instance_url, is_legacy_dbx_snapshot,
+ normalized_remote_path, parent_collection_paths, parse_legacy_dbx_snapshot, parse_snippet_snapshot,
+ prepare_legacy_snippet_snapshot, resolve_snippet_token, resolve_webdav_password,
+ resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup, save_snippet_sync_id,
+ save_snippet_sync_id_for_instance, save_snippet_token, save_webdav_password,
save_webdav_sync_secrets_preference, scrub_connection_secrets, snapshot_for_snippet_upload,
snippet_file_content, snippet_provider_storage_key, snippet_response_id, snippet_saved_token_status,
snippet_sync_settings, snippet_sync_settings_for_instance, validate_snippet_id,
webdav_endpoint_uses_direct_connection, webdav_sync_secrets_status, ApplySnapshotOptions,
ConnectionSecretSnapshot, SensitiveSyncPayload, SnippetProvider, SnippetSyncClient, SnippetSyncConfig,
- WebDavClient, WebDavConfig, DEFAULT_SNIPPET_FILE_NAME,
+ SyncExportOptions, WebDavClient, WebDavConfig, DEFAULT_SNIPPET_FILE_NAME, LEGACY_SNAPSHOT_SCHEMA_VERSION,
};
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiConfigItem};
use crate::connection_secrets::{
@@ -1792,6 +2263,7 @@ mod tests {
use crate::models::connection::{
default_redis_key_separator, ConnectionConfig, DatabaseType, SshTunnelConfig, TransportLayerConfig,
};
+ use crate::persistence::secret_codec::{managed_key_path, SecretKeyPolicy};
use crate::storage::Storage;
fn make_test_config(name: &str, is_default: bool) -> AiConfigItem {
@@ -2317,7 +2789,6 @@ mod tests {
db_type: DatabaseType::Postgres,
driver_profile: None,
driver_label: None,
- url_params: None,
agent_java_options: Vec::new(),
host: "localhost".to_string(),
port: 5432,
@@ -2372,6 +2843,7 @@ mod tests {
sysdba: false,
oracle_connection_type: None,
connection_string: Some("postgres://secret".to_string()),
+ url_params: Some("applicationName=dbx&PASSWORD=url-secret&sslmode=require".to_string()),
redis_connection_mode: None,
redis_sentinel_master: String::new(),
redis_sentinel_nodes: String::new(),
@@ -2417,12 +2889,21 @@ mod tests {
}
assert!(config.redis_sentinel_password.is_empty());
assert!(config.connection_string.is_none());
+ assert_eq!(config.url_params.as_deref(), Some("applicationName=dbx&PASSWORD=&sslmode=require"));
assert!(config.init_script.is_none());
assert_eq!(config.connection_secrets.get("api_token").map(String::as_str), None);
let public_json = serde_json::to_string(&config).unwrap();
assert!(!public_json.contains("token-value"));
assert!(!public_json.contains("plugin-secret"));
assert!(super::SECRET_KEYS.contains(&"init_script"));
+
+ let mut mqtt = config.clone();
+ mqtt.db_type = DatabaseType::Mqtt;
+ mqtt.external_config = Some(serde_json::json!({
+ "auth": { "kind": "password", "username": "mqtt-user", "password": "mqtt-secret" }
+ }));
+ scrub_connection_secrets(&mut mqtt);
+ assert_eq!(mqtt.external_config.as_ref().unwrap()["auth"]["password"], "");
}
#[tokio::test]
@@ -2453,6 +2934,7 @@ mod tests {
fn encrypted_sensitive_payload_round_trips() {
let payload = SensitiveSyncPayload {
tunnel_profiles: None,
+ plugin_secrets_included: true,
connection_secrets: vec![
ConnectionSecretSnapshot {
connection_id: "c1".to_string(),
@@ -2465,6 +2947,7 @@ mod tests {
secret: "hop-secret".to_string(),
},
],
+ sync_credentials: Some(vec![]),
ai_configs: None,
ai_config: None,
};
@@ -2479,11 +2962,13 @@ mod tests {
fn encrypted_sensitive_payload_rejects_wrong_passphrase() {
let payload = SensitiveSyncPayload {
tunnel_profiles: None,
+ plugin_secrets_included: true,
connection_secrets: vec![ConnectionSecretSnapshot {
connection_id: "c1".to_string(),
key: "password".to_string(),
secret: "secret".to_string(),
}],
+ sync_credentials: Some(vec![]),
ai_configs: None,
ai_config: None,
};
@@ -2491,6 +2976,27 @@ mod tests {
assert!(decrypt_sensitive_payload(&encrypted, "wrong-pass").is_err());
}
+ #[test]
+ fn encrypted_sensitive_payload_keeps_v1_compatibility() {
+ let payload = SensitiveSyncPayload {
+ tunnel_profiles: None,
+ plugin_secrets_included: true,
+ connection_secrets: vec![ConnectionSecretSnapshot {
+ connection_id: "legacy".to_string(),
+ key: "password".to_string(),
+ secret: "legacy-secret".to_string(),
+ }],
+ sync_credentials: Some(vec![]),
+ ai_configs: None,
+ ai_config: None,
+ };
+ let plaintext = serde_json::to_vec(&payload).unwrap();
+ let legacy_blob = super::encrypt_bytes_with_secret(&plaintext, "sync-pass").unwrap();
+ assert_eq!(legacy_blob.version, 1);
+ let restored = decrypt_sensitive_payload(&legacy_blob, "sync-pass").unwrap();
+ assert_eq!(restored.connection_secrets[0].secret, "legacy-secret");
+ }
+
#[tokio::test]
async fn encrypted_snippet_snapshot_hides_and_restores_the_full_snapshot() {
let storage = Storage::open(&temp_db_path("encrypted-snippet-snapshot")).await.unwrap();
@@ -3141,6 +3647,267 @@ mod tests {
}));
}
+ #[tokio::test]
+ async fn legacy_sync_payload_preserves_credentials_but_explicit_empty_clears_them() {
+ let directory = tempfile::tempdir().unwrap();
+ let database_path = directory.path().join("dbx.db");
+ let target = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let webdav = WebDavConfig {
+ endpoint: "https://dav.example.test".to_string(),
+ username: Some("alice".to_string()),
+ password: None,
+ remote_path: None,
+ };
+ let snippet = SnippetSyncConfig {
+ provider: SnippetProvider::GitHub,
+ instance_url: None,
+ token: None,
+ snippet_id: None,
+ replace_legacy_snippet: false,
+ };
+ save_webdav_password(&target, &webdav, "local-password").await.unwrap();
+ save_snippet_token(&target, &snippet, "local-token").await.unwrap();
+ let mut snapshot = build_sync_snapshot(&target, "test", None, None).await.unwrap();
+ snapshot.schema_version = LEGACY_SNAPSHOT_SCHEMA_VERSION;
+ let legacy_json = r#"{"connectionSecrets":[]}"#;
+ let mut payload: SensitiveSyncPayload = serde_json::from_str(legacy_json).unwrap();
+ assert!(payload.sync_credentials.is_none());
+ assert!(serde_json::to_value(&payload).unwrap().get("syncCredentials").is_none());
+ snapshot.encrypted_secrets = Some(super::encrypt_text_with_secret(legacy_json, "transport-pass").unwrap());
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("transport-pass"), restore_secrets: true },
+ )
+ .await
+ .unwrap();
+ drop(target);
+ let target = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+
+ payload.sync_credentials = Some(vec![]);
+ assert_eq!(serde_json::to_value(&payload).unwrap()["syncCredentials"], serde_json::json!([]));
+ snapshot.encrypted_secrets = Some(encrypt_sensitive_payload(&payload, "transport-pass").unwrap());
+ for restore_secrets in [false, true] {
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("transport-pass"), restore_secrets },
+ )
+ .await
+ .unwrap();
+ let mut restored_webdav = webdav.clone();
+ resolve_webdav_password(&target, &mut restored_webdav).await.unwrap();
+ assert_eq!(restored_webdav.password.as_deref(), (!restore_secrets).then_some("local-password"));
+ let mut restored_snippet = snippet.clone();
+ resolve_snippet_token(&target, &mut restored_snippet).await.unwrap();
+ assert_eq!(restored_snippet.token.as_deref(), (!restore_secrets).then_some("local-token"));
+ }
+ drop(target);
+ let target = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let mut restored_webdav = webdav;
+ resolve_webdav_password(&target, &mut restored_webdav).await.unwrap();
+ assert_eq!(restored_webdav.password, None);
+ let mut restored_snippet = snippet;
+ resolve_snippet_token(&target, &mut restored_snippet).await.unwrap();
+ assert_eq!(restored_snippet.token, None);
+ }
+
+ #[tokio::test]
+ async fn metadata_only_sync_roundtrip_preserves_public_url_params_and_target_secrets() {
+ let source_directory = tempfile::tempdir().unwrap();
+ let target_directory = tempfile::tempdir().unwrap();
+ let source = Storage::open_unmigrated(&source_directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let target_path = target_directory.path().join("dbx.db");
+ let target = Storage::open_unmigrated(&target_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let mut fresh = postgres_connection("fresh", "source-password");
+ fresh.url_params = Some("applicationName=dbx&PASSWORD=source-secret&sslmode=require".to_string());
+ let mut existing = fresh.clone();
+ existing.id = "existing".to_string();
+ source.save_connections(&[fresh, existing.clone()]).await.unwrap();
+ existing.password = "target-password".to_string();
+ existing.url_params = Some("applicationName=local&PASSWORD=target-secret".to_string());
+ target.save_connections(std::slice::from_ref(&existing)).await.unwrap();
+ target.set_secret("existing", "init_script", "target-script").await.unwrap();
+
+ let snapshot = build_sync_snapshot(&source, "test", None, None).await.unwrap();
+ assert!(snapshot.encrypted_secrets.is_none());
+ let serialized = serde_json::to_string(&snapshot).unwrap();
+ assert!(!serialized.contains("source-secret"));
+ assert!(!serialized.contains("source-password"));
+ let snapshot = serde_json::from_str(&serialized).unwrap();
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: false },
+ )
+ .await
+ .unwrap();
+ drop(target);
+ let target = Storage::open_unmigrated(&target_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let loaded = target.load_connections().await.unwrap();
+ let fresh = loaded.iter().find(|config| config.id == "fresh").unwrap();
+ assert_eq!(fresh.url_params.as_deref(), Some("applicationName=dbx&PASSWORD=&sslmode=require"));
+ assert!(fresh.password.is_empty());
+ let restored = loaded.iter().find(|config| config.id == "existing").unwrap();
+ assert_eq!(restored.password, "target-password");
+ assert_eq!(restored.url_params, existing.url_params);
+ assert_eq!(restored.init_script.as_deref(), Some("target-script"));
+ let database = rusqlite::Connection::open(&target_path).unwrap();
+ let (plaintext, encrypted): (String, String) = database
+ .query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'fresh' AND key = 'url_params'",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert!(plaintext.is_empty());
+ assert!(encrypted.starts_with("dbxenc1."));
+
+ let locked_directory = tempfile::tempdir().unwrap();
+ let locked_target = Storage::open_unmigrated(&locked_directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir)
+ .with_secret_key_creation(false);
+ assert_eq!(
+ apply_sync_snapshot(
+ &locked_target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: false },
+ )
+ .await
+ .unwrap_err(),
+ "MISSING_MANAGED_KEY"
+ );
+ assert!(locked_target.load_connections().await.unwrap().is_empty());
+ assert!(!managed_key_path(locked_directory.path()).exists());
+
+ let mut without_url_params = snapshot.clone();
+ for config in &mut without_url_params.connections {
+ config.url_params = None;
+ }
+ apply_sync_snapshot(
+ &locked_target,
+ &without_url_params,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: false },
+ )
+ .await
+ .unwrap();
+ assert_eq!(locked_target.load_connections().await.unwrap().len(), 2);
+ assert!(!managed_key_path(locked_directory.path()).exists());
+
+ let unlocked_target = locked_target.with_secret_key_creation(true);
+ apply_sync_snapshot(
+ &unlocked_target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: false },
+ )
+ .await
+ .unwrap();
+ assert!(managed_key_path(locked_directory.path()).exists());
+ assert!(unlocked_target.load_connections().await.unwrap().iter().all(|config| {
+ config.url_params.as_deref() == Some("applicationName=dbx&PASSWORD=&sslmode=require")
+ && config.password.is_empty()
+ }));
+ }
+
+ #[tokio::test]
+ async fn sync_credentials_are_rewrapped_for_the_destination_device() {
+ let source = Storage::open(&temp_db_path("sync-global-credentials-source")).await.unwrap();
+ let webdav = WebDavConfig {
+ endpoint: "https://dav.example.test/remote.php/dav/files/alice".to_string(),
+ username: Some("alice".to_string()),
+ password: None,
+ remote_path: Some("DBX/sync/snapshot.json".to_string()),
+ };
+ save_webdav_password(&source, &webdav, "webdav-secret").await.unwrap();
+ let snippet = SnippetSyncConfig {
+ provider: SnippetProvider::GitHub,
+ instance_url: None,
+ token: None,
+ snippet_id: None,
+ replace_legacy_snippet: false,
+ };
+ save_snippet_token(&source, &snippet, "github-token").await.unwrap();
+
+ let snapshot = build_sync_snapshot(&source, "test-version", None, Some("transport-pass")).await.unwrap();
+ let public_json = serde_json::to_string(&snapshot).unwrap();
+ assert!(!public_json.contains("webdav-secret"));
+ assert!(!public_json.contains("github-token"));
+ let payload =
+ decrypt_sensitive_payload(snapshot.encrypted_secrets.as_ref().unwrap(), "transport-pass").unwrap();
+ let credentials = payload.sync_credentials.as_ref().unwrap();
+ assert_eq!(credentials.len(), 2);
+ assert!(credentials.iter().any(|credential| credential.secret == "webdav-secret"));
+ assert!(credentials.iter().any(|credential| credential.secret == "github-token"));
+
+ let target_path = temp_db_path("sync-global-credentials-target");
+ let target = Storage::open(&target_path).await.unwrap();
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("transport-pass"), restore_secrets: true },
+ )
+ .await
+ .unwrap();
+
+ let mut restored_webdav = webdav.clone();
+ resolve_webdav_password(&target, &mut restored_webdav).await.unwrap();
+ assert_eq!(restored_webdav.password.as_deref(), Some("webdav-secret"));
+ let mut restored_snippet = snippet.clone();
+ resolve_snippet_token(&target, &mut restored_snippet).await.unwrap();
+ assert_eq!(restored_snippet.token.as_deref(), Some("github-token"));
+
+ // The destination uses its own local wrapping key; deleting the source
+ // database does not affect the restored credentials.
+ drop(target);
+ drop(source);
+ let target = Storage::open(&target_path).await.unwrap();
+ let mut reopened_webdav = webdav.clone();
+ resolve_webdav_password(&target, &mut reopened_webdav).await.unwrap();
+ assert_eq!(reopened_webdav.password.as_deref(), Some("webdav-secret"));
+
+ // The encrypted credential list is authoritative. Removing credentials
+ // on the source must not leave stale target tokens behind.
+ // Build an empty credential payload explicitly so the test does not
+ // depend on a second live provider.
+ let mut empty_snapshot = snapshot.clone();
+ let mut empty_payload = payload.clone();
+ empty_payload.sync_credentials = Some(vec![]);
+ empty_snapshot.encrypted_secrets = Some(encrypt_sensitive_payload(&empty_payload, "transport-pass").unwrap());
+ apply_sync_snapshot(
+ &target,
+ &empty_snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("transport-pass"), restore_secrets: true },
+ )
+ .await
+ .unwrap();
+ let mut removed_webdav = webdav.clone();
+ resolve_webdav_password(&target, &mut removed_webdav).await.unwrap();
+ assert_eq!(removed_webdav.password, None);
+ let mut removed_snippet = snippet.clone();
+ resolve_snippet_token(&target, &mut removed_snippet).await.unwrap();
+ assert_eq!(removed_snippet.token, None);
+ }
+
#[tokio::test]
async fn plugin_connection_secrets_are_scrubbed_from_public_sync_metadata() {
let storage = Storage::open(&temp_db_path("plugin-public-sync")).await.unwrap();
@@ -3163,6 +3930,81 @@ mod tests {
}));
}
+ #[tokio::test]
+ async fn plugin_secrets_export_even_when_primary_password_is_not_saved() {
+ let storage = Storage::open(&temp_db_path("plugin-secret-without-password")).await.unwrap();
+ let mut config = postgres_connection("plugin-no-password", "");
+ config.db_type = DatabaseType::Plugin;
+ config.save_password = false;
+ config.plugin_id = Some("example.plugin".to_string());
+ config.plugin_connection_provider = Some("example.connection".to_string());
+ config.connection_secrets.insert("api_token".to_string(), "plugin-secret".to_string());
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let snapshot = build_sync_snapshot_with_options(
+ &storage,
+ "test-version",
+ None,
+ SyncExportOptions {
+ include_secrets: true,
+ sync_passphrase: Some("sync-pass"),
+ include_ai_secrets: false,
+ include_tunnel_secrets: false,
+ include_plugin_secrets: true,
+ },
+ )
+ .await
+ .unwrap();
+ let decrypted = decrypt_sensitive_payload(snapshot.encrypted_secrets.as_ref().unwrap(), "sync-pass").unwrap();
+ assert!(decrypted.connection_secrets.iter().any(|secret| {
+ secret.connection_id == "plugin-no-password"
+ && secret.key == format!("{PLUGIN_CONNECTION_SECRET_PREFIX}api_token")
+ && secret.secret == "plugin-secret"
+ }));
+ }
+
+ #[tokio::test]
+ async fn excluded_plugin_secrets_do_not_clear_destination_credentials() {
+ let source = Storage::open(&temp_db_path("plugin-secret-excluded-source")).await.unwrap();
+ let mut config = postgres_connection("plugin-preserve", "");
+ config.db_type = DatabaseType::Plugin;
+ config.plugin_id = Some("example.plugin".to_string());
+ config.plugin_connection_provider = Some("example.connection".to_string());
+ source.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let snapshot = build_sync_snapshot_with_options(
+ &source,
+ "test-version",
+ None,
+ SyncExportOptions {
+ include_secrets: true,
+ sync_passphrase: Some("sync-pass"),
+ include_ai_secrets: false,
+ include_tunnel_secrets: false,
+ include_plugin_secrets: false,
+ },
+ )
+ .await
+ .unwrap();
+
+ let target = Storage::open(&temp_db_path("plugin-secret-excluded-target")).await.unwrap();
+ let mut target_config = config.clone();
+ target_config.connection_secrets.insert("api_token".to_string(), "local-plugin-secret".to_string());
+ target.save_connections(std::slice::from_ref(&target_config)).await.unwrap();
+
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("sync-pass"), restore_secrets: true },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ target.get_secret("plugin-preserve", "plugin_connection.api_token").await.unwrap().as_deref(),
+ Some("local-plugin-secret")
+ );
+ }
+
#[tokio::test]
async fn sync_restore_does_not_revive_password_when_connection_disables_saving() {
let source = Storage::open(&temp_db_path("sync-no-save-password-source")).await.unwrap();
@@ -3183,6 +4025,59 @@ mod tests {
assert!(target.load_connections().await.unwrap()[0].password.is_empty());
}
+ #[tokio::test]
+ async fn wrong_sync_passphrase_does_not_modify_the_destination() {
+ let source = Storage::open(&temp_db_path("sync-wrong-pass-source")).await.unwrap();
+ source.save_connections(&[postgres_connection("remote", "remote-secret")]).await.unwrap();
+ let snapshot = build_sync_snapshot(&source, "test-version", None, Some("correct-pass")).await.unwrap();
+
+ let target = Storage::open(&temp_db_path("sync-wrong-pass-target")).await.unwrap();
+ target.save_connections(&[postgres_connection("local", "local-secret")]).await.unwrap();
+ let before = target.load_connections().await.unwrap();
+ assert!(apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: Some("wrong-pass"), restore_secrets: true },
+ )
+ .await
+ .is_err());
+ assert_eq!(target.load_connections().await.unwrap(), before);
+ assert_eq!(target.get_secret("local", "password").await.unwrap().as_deref(), Some("local-secret"));
+ assert_eq!(target.get_secret("remote", "password").await.unwrap(), None);
+ }
+
+ #[tokio::test]
+ async fn legacy_plaintext_snapshot_secrets_are_migrated_only_on_explicit_restore() {
+ let source = Storage::open(&temp_db_path("legacy-plaintext-sync-source")).await.unwrap();
+ source.save_connections(&[postgres_connection("legacy", "unused")]).await.unwrap();
+ let mut snapshot = build_sync_snapshot(&source, "legacy-version", None, None).await.unwrap();
+ snapshot.schema_version = LEGACY_SNAPSHOT_SCHEMA_VERSION;
+ snapshot.connections[0].password = "legacy-password".to_string();
+ snapshot.connections[0].init_script = Some("CREATE SECRET legacy".to_string());
+
+ let target = Storage::open(&temp_db_path("legacy-plaintext-sync-target")).await.unwrap();
+ apply_sync_snapshot(
+ &target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: true },
+ )
+ .await
+ .unwrap();
+ assert_eq!(target.get_secret("legacy", "password").await.unwrap().as_deref(), Some("legacy-password"));
+ assert_eq!(target.get_secret("legacy", "init_script").await.unwrap().as_deref(), Some("CREATE SECRET legacy"));
+
+ let metadata_only_target = Storage::open(&temp_db_path("legacy-plaintext-sync-metadata-only")).await.unwrap();
+ apply_sync_snapshot(
+ &metadata_only_target,
+ &snapshot,
+ ApplySnapshotOptions { secrets_passphrase: None, restore_secrets: false },
+ )
+ .await
+ .unwrap();
+ assert_eq!(metadata_only_target.get_secret("legacy", "password").await.unwrap(), None);
+ assert_eq!(metadata_only_target.get_secret("legacy", "init_script").await.unwrap(), None);
+ }
+
#[tokio::test]
async fn metadata_only_sync_removes_existing_password_when_connection_disables_saving() {
let source = Storage::open(&temp_db_path("sync-no-save-password-metadata-source")).await.unwrap();
@@ -3230,6 +4125,7 @@ mod tests {
}));
let legacy_payload = SensitiveSyncPayload {
+ plugin_secrets_included: true,
connection_secrets: vec![
ConnectionSecretSnapshot {
connection_id: "nacos".to_string(),
@@ -3242,6 +4138,7 @@ mod tests {
secret: "legacy-console-secret".to_string(),
},
],
+ sync_credentials: Some(vec![]),
ai_configs: None,
ai_config: None,
tunnel_profiles: None,
@@ -3301,7 +4198,9 @@ mod tests {
// No ai_configs in payload — fall through to ai_config (legacy) branch
let payload = SensitiveSyncPayload {
+ plugin_secrets_included: true,
connection_secrets: vec![],
+ sync_credentials: Some(vec![]),
ai_configs: None,
ai_config: None,
tunnel_profiles: None,
@@ -3321,7 +4220,9 @@ mod tests {
// Some([]) — explicit clear
let payload = SensitiveSyncPayload {
+ plugin_secrets_included: true,
connection_secrets: vec![],
+ sync_credentials: Some(vec![]),
ai_configs: Some(vec![]),
ai_config: None,
tunnel_profiles: None,
@@ -3346,7 +4247,9 @@ mod tests {
cursor_cfg.config.cursor_cli_path = Some("~/.local/bin/agent".to_string());
cursor_cfg.config.cursor_cli_env.insert("NO_PROXY".to_string(), "localhost".to_string());
let payload = SensitiveSyncPayload {
+ plugin_secrets_included: true,
connection_secrets: vec![],
+ sync_credentials: Some(vec![]),
ai_configs: Some(vec![cfg, cursor_cfg]),
ai_config: None,
tunnel_profiles: None,
@@ -3378,7 +4281,9 @@ mod tests {
let mut legacy_config = make_test_config("unused", true).config;
legacy_config.model = "snapshot-model".to_string();
let payload = SensitiveSyncPayload {
+ plugin_secrets_included: true,
connection_secrets: vec![],
+ sync_credentials: Some(vec![]),
ai_configs: None,
ai_config: Some(legacy_config),
tunnel_profiles: None,
diff --git a/crates/dbx-core/src/persistence/mod.rs b/crates/dbx-core/src/persistence/mod.rs
index d9e5caf1bd..3f31b17e99 100644
--- a/crates/dbx-core/src/persistence/mod.rs
+++ b/crates/dbx-core/src/persistence/mod.rs
@@ -2,5 +2,6 @@ pub mod cloud_sync;
pub mod config;
pub mod history;
pub mod saved_sql;
+pub mod secret_codec;
pub mod state_persistence;
pub mod storage;
diff --git a/crates/dbx-core/src/persistence/secret_codec.rs b/crates/dbx-core/src/persistence/secret_codec.rs
new file mode 100644
index 0000000000..1f033d44ec
--- /dev/null
+++ b/crates/dbx-core/src/persistence/secret_codec.rs
@@ -0,0 +1,609 @@
+//! Encryption primitives for values persisted in `connection_secrets`.
+//!
+//! The database deliberately stores only an envelope (`dbxenc1...`) for new
+//! values. Desktop builds keep the local key in the operating system
+//! credential store (macOS Keychain, Windows Credential Manager, or Linux
+//! Secret Service). `DBX_SECRET_KEY` and `DBX_SECRET_KEY_FILE` are supported
+//! for headless deployments. A per-user key file remains as a compatibility
+//! fallback for installations created before native credential storage was
+//! enabled; the key is always outside the database and never enters a sync file.
+
+use aes_gcm::{
+ aead::{rand_core::RngCore, Aead, KeyInit, OsRng},
+ Aes256Gcm, Nonce,
+};
+use argon2::{Algorithm, Argon2, Params, Version};
+use base64::Engine as _;
+
+const PREFIX: &str = "dbxenc1";
+const KEYRING_SERVICE: &str = "com.dbx.app.secret-store.v1";
+const KEYRING_USER: &str = "local-data-encryption-key";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SecretKeyPolicy {
+ PlatformDefault,
+ ManagedDataDir,
+ ExternalOnly,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SecretKeySource {
+ ExplicitFile,
+ ExplicitEnv,
+ ManagedDataDir,
+ PlatformStore,
+ Unavailable,
+}
+
+impl SecretKeySource {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::ExplicitFile => "explicit_file",
+ Self::ExplicitEnv => "explicit_env",
+ Self::ManagedDataDir => "managed_data_dir",
+ Self::PlatformStore => "platform_store",
+ Self::Unavailable => "unavailable",
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct SecretKeyResolution {
+ pub codec: SecretCodec,
+ pub source: SecretKeySource,
+}
+
+#[derive(Clone, Copy)]
+pub struct SecretCodec {
+ key: [u8; 32],
+}
+
+impl SecretCodec {
+ pub const fn new(key: [u8; 32]) -> Self {
+ Self { key }
+ }
+
+ /// Build a codec from a high-entropy passphrase using Argon2id.
+ pub fn from_passphrase(passphrase: &str) -> Result<Self, String> {
+ if passphrase.is_empty() {
+ return Err("secret key cannot be empty".to_string());
+ }
+ let mut key = [0u8; 32];
+ let params = Params::new(19 * 1024, 2, 1, Some(32)).map_err(|e| e.to_string())?;
+ Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
+ .hash_password_into(passphrase.as_bytes(), b"dbx-local-secret-store-v1", &mut key)
+ .map_err(|e| e.to_string())?;
+ Ok(Self::new(key))
+ }
+
+ /// Resolve the configured key without exposing key material in errors.
+ /// `allow_create` is intentionally explicit so status checks remain read-only.
+ pub fn resolve(
+ policy: SecretKeyPolicy,
+ data_dir: &std::path::Path,
+ allow_create: bool,
+ ) -> Result<SecretKeyResolution, String> {
+ if let Some(path) = std::env::var_os("DBX_SECRET_KEY_FILE") {
+ let path = std::path::PathBuf::from(path);
+ let codec = Self::read_key_file(&path, false)?;
+ return Ok(SecretKeyResolution { codec, source: SecretKeySource::ExplicitFile });
+ }
+ if let Some(value) = std::env::var_os("DBX_SECRET_KEY") {
+ let value = value.to_str().ok_or_else(|| "SECRET_KEY_INVALID".to_string())?;
+ let codec = Self::from_key_material(value.trim()).map_err(|_| "SECRET_KEY_INVALID".to_string())?;
+ return Ok(SecretKeyResolution { codec, source: SecretKeySource::ExplicitEnv });
+ }
+
+ match policy {
+ SecretKeyPolicy::ManagedDataDir => {
+ let path = managed_key_path(data_dir);
+ match path.symlink_metadata() {
+ Ok(metadata) if metadata.file_type().is_symlink() => Err("KEY_FILE_UNAVAILABLE".to_string()),
+ Ok(_) => {
+ if allow_create {
+ secure_managed_key_permissions(&path)?;
+ }
+ let codec = read_key_file_with_retry(&path, true)?;
+ Ok(SecretKeyResolution { codec, source: SecretKeySource::ManagedDataDir })
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound && allow_create => {
+ let codec = create_managed_key(&path)?;
+ Ok(SecretKeyResolution { codec, source: SecretKeySource::ManagedDataDir })
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ Err("MISSING_MANAGED_KEY".to_string())
+ }
+ Err(_) => Err("KEY_FILE_UNAVAILABLE".to_string()),
+ }
+ }
+ SecretKeyPolicy::ExternalOnly => Err("MISSING_EXTERNAL_KEY".to_string()),
+ SecretKeyPolicy::PlatformDefault => {
+ Self::resolve_platform_default(default_key_path(), allow_create, platform_keyring_codec)
+ }
+ }
+ }
+
+ fn resolve_platform_default<F>(
+ compatibility_path: Option<std::path::PathBuf>,
+ allow_create: bool,
+ platform_provider: F,
+ ) -> Result<SecretKeyResolution, String>
+ where
+ F: FnOnce(bool) -> Option<SecretCodec>,
+ {
+ let compatibility_error = if let Some(path) = compatibility_path.as_ref().filter(|path| path.exists()) {
+ match Self::read_key_file(path, false) {
+ Ok(codec) => return Ok(SecretKeyResolution { codec, source: SecretKeySource::ManagedDataDir }),
+ Err(error) => Some(error),
+ }
+ } else {
+ None
+ };
+ if let Some(codec) = platform_provider(allow_create) {
+ return Ok(SecretKeyResolution { codec, source: SecretKeySource::PlatformStore });
+ }
+ if allow_create {
+ if let Some(path) = compatibility_path {
+ let codec = create_key_file(&path, false)?;
+ return Ok(SecretKeyResolution { codec, source: SecretKeySource::ManagedDataDir });
+ }
+ }
+ compatibility_error.map_or_else(|| Err("KEY_PROVIDER_UNAVAILABLE".to_string()), Err)
+ }
+
+ /// Read an explicitly configured key, then an existing compatibility key
+ /// file, then the platform credential store. The file is checked before
+ /// creating a new keyring entry so upgrades cannot strand an existing
+ /// database behind a newly generated device key.
+ pub fn from_env_or_default() -> Result<Self, String> {
+ Self::resolve(SecretKeyPolicy::PlatformDefault, std::path::Path::new("."), true).map(|resolved| resolved.codec)
+ }
+
+ /// Inspect existing key material without creating files or keyring entries.
+ /// Headless migration must use an explicitly configured persistent key.
+ pub fn from_existing_provider(require_external: bool) -> Result<Self, String> {
+ let policy = if require_external { SecretKeyPolicy::ExternalOnly } else { SecretKeyPolicy::PlatformDefault };
+ Self::resolve(policy, std::path::Path::new("."), false).map(|resolved| resolved.codec)
+ }
+
+ /// Provision only after a read-only probe found no usable provider. This
+ /// is called by the desktop migration wizard only for plaintext-only
+ /// legacy data; headless callers never use it. If the platform keyring is
+ /// unavailable, the documented per-user key-file fallback keeps Linux
+ /// desktop upgrades recoverable without putting a key in SQLite.
+ pub fn provision_for_migration() -> Result<Self, String> {
+ Self::resolve(SecretKeyPolicy::PlatformDefault, std::path::Path::new("."), true).map(|resolved| resolved.codec)
+ }
+
+ fn read_key_file(path: &std::path::Path, reject_symlink: bool) -> Result<Self, String> {
+ let metadata = if reject_symlink { path.symlink_metadata() } else { path.metadata() }
+ .map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ if (reject_symlink && metadata.file_type().is_symlink()) || !metadata.is_file() {
+ return Err("KEY_FILE_UNAVAILABLE".to_string());
+ }
+ let value = std::fs::read_to_string(path).map_err(|error| {
+ if error.kind() == std::io::ErrorKind::InvalidData {
+ "SECRET_KEY_INVALID"
+ } else {
+ "KEY_FILE_UNAVAILABLE"
+ }
+ })?;
+ Self::from_key_material(value.trim()).map_err(|_| "SECRET_KEY_INVALID".to_string())
+ }
+
+ fn from_key_material(value: &str) -> Result<Self, String> {
+ if let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(value) {
+ if bytes.len() == 32 {
+ return bytes.try_into().map(Self::new).map_err(|_| "invalid key".into());
+ }
+ }
+ if value.is_ascii() && value.len() == 64 {
+ let mut out = [0u8; 32];
+ for (i, slot) in out.iter_mut().enumerate() {
+ *slot = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16).map_err(|_| "invalid hex key")?;
+ }
+ return Ok(Self::new(out));
+ }
+ Self::from_passphrase(value)
+ }
+
+ pub fn encrypt(&self, namespace: &str, key: &str, plaintext: &str) -> Result<String, String> {
+ let mut nonce = [0u8; 12];
+ OsRng.fill_bytes(&mut nonce);
+ let cipher = Aes256Gcm::new_from_slice(&self.key).map_err(|e| e.to_string())?;
+ let ciphertext = cipher
+ .encrypt(
+ Nonce::from_slice(&nonce),
+ aes_gcm::aead::Payload { msg: plaintext.as_bytes(), aad: aad(namespace, key).as_bytes() },
+ )
+ .map_err(|_| "secret encryption failed".to_string())?;
+ let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
+ Ok(format!("{PREFIX}.{}.{}", b64.encode(nonce), b64.encode(ciphertext)))
+ }
+
+ pub fn decrypt(&self, namespace: &str, key: &str, envelope: &str) -> Result<String, String> {
+ let mut parts = envelope.split('.');
+ if parts.next() != Some(PREFIX) {
+ return Err("unsupported secret envelope".to_string());
+ }
+ let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(parts.next().ok_or("invalid secret envelope")?)
+ .map_err(|_| "invalid secret nonce".to_string())?;
+ let ciphertext = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(parts.next().ok_or("invalid secret envelope")?)
+ .map_err(|_| "invalid secret ciphertext".to_string())?;
+ if parts.next().is_some() || nonce.len() != 12 {
+ return Err("invalid secret envelope".to_string());
+ }
+ let cipher = Aes256Gcm::new_from_slice(&self.key).map_err(|e| e.to_string())?;
+ let plaintext = cipher
+ .decrypt(
+ Nonce::from_slice(&nonce),
+ aes_gcm::aead::Payload { msg: &ciphertext, aad: aad(namespace, key).as_bytes() },
+ )
+ .map_err(|_| "secret decryption failed".to_string())?;
+ String::from_utf8(plaintext).map_err(|_| "secret is not valid UTF-8".to_string())
+ }
+}
+
+fn platform_keyring_codec(allow_create: bool) -> Option<SecretCodec> {
+ let entry = keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).ok()?;
+ match entry.get_password() {
+ Ok(value) => return SecretCodec::from_key_material(value.trim()).ok(),
+ Err(keyring::Error::NoEntry) => {}
+ Err(_) => return None,
+ }
+ if !allow_create {
+ return None;
+ }
+ let mut key = [0u8; 32];
+ OsRng.fill_bytes(&mut key);
+ let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key);
+ entry.set_password(&encoded).ok()?;
+ Some(SecretCodec::new(key))
+}
+
+fn create_managed_key(path: &std::path::Path) -> Result<SecretCodec, String> {
+ let parent = path.parent().ok_or_else(|| "KEY_FILE_UNAVAILABLE".to_string())?;
+ std::fs::create_dir_all(parent).map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))
+ .map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ }
+ create_key_file(path, true)
+}
+
+fn secure_managed_key_permissions(path: &std::path::Path) -> Result<(), String> {
+ if path.symlink_metadata().map_or(true, |metadata| metadata.file_type().is_symlink() || !metadata.is_file()) {
+ return Err("KEY_FILE_UNAVAILABLE".to_string());
+ }
+ let parent = path.parent().ok_or_else(|| "KEY_FILE_UNAVAILABLE".to_string())?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))
+ .map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
+ .map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ }
+ Ok(())
+}
+
+fn create_key_file(path: &std::path::Path, managed: bool) -> Result<SecretCodec, String> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|_| "KEY_FILE_UNAVAILABLE".to_string())?;
+ }
+ let mut key = [0u8; 32];
+ OsRng.fill_bytes(&mut key);
+ let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key);
+ let write_result = {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path).and_then(|mut file| {
+ std::io::Write::write_all(&mut file, encoded.as_bytes())?;
+ file.sync_all()
+ })
+ }
+ #[cfg(not(unix))]
+ {
+ std::fs::OpenOptions::new().write(true).create_new(true).open(path).and_then(|mut file| {
+ std::io::Write::write_all(&mut file, encoded.as_bytes())?;
+ file.sync_all()
+ })
+ }
+ };
+ if write_result.is_ok() {
+ return SecretCodec::read_key_file(path, managed);
+ }
+ match path.symlink_metadata() {
+ Ok(metadata) if managed && metadata.file_type().is_symlink() => Err("KEY_FILE_UNAVAILABLE".to_string()),
+ Ok(_) => {
+ if managed {
+ read_key_file_with_retry(path, managed)
+ } else {
+ SecretCodec::read_key_file(path, managed)
+ }
+ }
+ Err(_) => Err("KEY_FILE_UNAVAILABLE".to_string()),
+ }
+}
+
+pub fn managed_key_path(data_dir: &std::path::Path) -> std::path::PathBuf {
+ data_dir.join(".dbx").join("secret.key")
+}
+
+fn read_key_file_with_retry(path: &std::path::Path, reject_symlink: bool) -> Result<SecretCodec, String> {
+ for attempt in 0..20 {
+ match SecretCodec::read_key_file(path, reject_symlink) {
+ Ok(codec) => return Ok(codec),
+ Err(error) if attempt < 19 && error == "SECRET_KEY_INVALID" && path.metadata().is_ok() => {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ Err("KEY_FILE_UNAVAILABLE".to_string())
+}
+
+fn default_key_path() -> Option<std::path::PathBuf> {
+ #[cfg(target_os = "macos")]
+ if let Ok(home) = std::env::var("HOME") {
+ return Some(std::path::PathBuf::from(home).join("Library/Application Support/dbx/secret.key"));
+ }
+ if let Ok(config) = std::env::var("XDG_CONFIG_HOME") {
+ return Some(std::path::PathBuf::from(config).join("dbx/secret.key"));
+ }
+ std::env::var_os("APPDATA").map(std::path::PathBuf::from).map(|path| path.join("dbx/secret.key")).or_else(|| {
+ std::env::var_os("HOME").map(std::path::PathBuf::from).map(|path| path.join(".config/dbx/secret.key"))
+ })
+}
+
+fn aad(namespace: &str, key: &str) -> String {
+ format!("dbx-secret-v1\0{namespace}\0{key}")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{managed_key_path, SecretCodec, SecretKeyPolicy, SecretKeySource};
+ use base64::Engine as _;
+ use std::sync::{Mutex, OnceLock};
+
+ fn env_lock() -> &'static Mutex<()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+ }
+
+ #[test]
+ fn roundtrip_binds_namespace_and_key() {
+ let codec = SecretCodec::new([7u8; 32]);
+ let envelope = codec.encrypt("connection-1", "password", "s3cret").unwrap();
+ assert!(envelope.starts_with("dbxenc1."));
+ assert_eq!(codec.decrypt("connection-1", "password", &envelope).unwrap(), "s3cret");
+ assert!(codec.decrypt("connection-2", "password", &envelope).is_err());
+ assert!(codec.decrypt("connection-1", "token", &envelope).is_err());
+ }
+
+ #[test]
+ fn unicode_key_material_never_slices_inside_a_character() {
+ // 64 bytes, with the second byte inside a three-byte character.
+ let material = format!("{}a", "密".repeat(21));
+ assert_eq!(material.len(), 64);
+ let codec = SecretCodec::from_key_material(&material).unwrap();
+ let encrypted = codec.encrypt("n", "k", "value").unwrap();
+ assert_eq!(codec.decrypt("n", "k", &encrypted).unwrap(), "value");
+ }
+
+ #[test]
+ fn tampering_is_rejected() {
+ let codec = SecretCodec::new([3u8; 32]);
+ let mut envelope = codec.encrypt("n", "k", "value").unwrap();
+ envelope.push('x');
+ assert!(codec.decrypt("n", "k", &envelope).is_err());
+ }
+
+ #[test]
+ fn managed_key_is_created_idempotently_with_restricted_permissions() {
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let first = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true).unwrap();
+ let second = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ assert_eq!(first.source, SecretKeySource::ManagedDataDir);
+ assert_eq!(second.source, SecretKeySource::ManagedDataDir);
+ let envelope = first.codec.encrypt("n", "k", "value").unwrap();
+ assert_eq!(second.codec.decrypt("n", "k", &envelope).unwrap(), "value");
+ assert!(managed_key_path(dir.path()).is_file());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let key_dir = dir.path().join(".dbx");
+ let key_path = managed_key_path(dir.path());
+ assert_eq!(std::fs::metadata(&key_dir).unwrap().permissions().mode() & 0o777, 0o700);
+ assert_eq!(std::fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
+
+ std::fs::set_permissions(&key_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
+ std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ assert_eq!(std::fs::metadata(&key_dir).unwrap().permissions().mode() & 0o777, 0o755);
+ assert_eq!(std::fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o644);
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true).unwrap();
+ assert_eq!(std::fs::metadata(&key_dir).unwrap().permissions().mode() & 0o777, 0o700);
+ assert_eq!(std::fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+ }
+
+ #[test]
+ fn managed_key_creation_is_safe_for_concurrent_starters() {
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let paths = (0..8).map(|_| dir.path().to_path_buf()).collect::<Vec<_>>();
+ let threads = paths
+ .into_iter()
+ .map(|path| {
+ std::thread::spawn(move || SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, &path, true).unwrap())
+ })
+ .collect::<Vec<_>>();
+ let resolutions = threads.into_iter().map(|thread| thread.join().unwrap()).collect::<Vec<_>>();
+ let envelope = resolutions[0].codec.encrypt("n", "k", "value").unwrap();
+ for resolution in resolutions {
+ assert_eq!(resolution.codec.decrypt("n", "k", &envelope).unwrap(), "value");
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn managed_key_symlink_is_rejected() {
+ use std::os::unix::fs::symlink;
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real.key");
+ std::fs::write(&real, base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([4u8; 32])).unwrap();
+ let key_path = managed_key_path(dir.path());
+ std::fs::create_dir_all(key_path.parent().unwrap()).unwrap();
+ symlink(&real, &key_path).unwrap();
+ assert!(matches!(
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false),
+ Err(error) if error == "KEY_FILE_UNAVAILABLE"
+ ));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn explicit_key_file_symlink_is_allowed() {
+ use std::os::unix::fs::symlink;
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real.key");
+ let link = dir.path().join("external.key");
+ std::fs::write(&real, base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([5u8; 32])).unwrap();
+ symlink(&real, &link).unwrap();
+
+ let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
+ let previous_env = std::env::var_os("DBX_SECRET_KEY");
+ std::env::set_var("DBX_SECRET_KEY_FILE", &link);
+ std::env::remove_var("DBX_SECRET_KEY");
+ let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ assert_eq!(resolved.source, SecretKeySource::ExplicitFile);
+ restore_env("DBX_SECRET_KEY_FILE", previous_file);
+ restore_env("DBX_SECRET_KEY", previous_env);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn invalid_non_utf8_explicit_environment_key_does_not_fallback() {
+ use std::os::unix::ffi::OsStringExt;
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
+ let previous_env = std::env::var_os("DBX_SECRET_KEY");
+ std::env::remove_var("DBX_SECRET_KEY_FILE");
+ std::env::set_var("DBX_SECRET_KEY", std::ffi::OsString::from_vec(vec![0xff, 0xfe]));
+ assert!(matches!(
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true),
+ Err(error) if error == "SECRET_KEY_INVALID"
+ ));
+ restore_env("DBX_SECRET_KEY_FILE", previous_file);
+ restore_env("DBX_SECRET_KEY", previous_env);
+ }
+
+ #[test]
+ fn unavailable_platform_probe_does_not_create_a_fallback_key() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("secret.key");
+ let result = SecretCodec::resolve_platform_default(Some(path.clone()), false, |allow_create| {
+ assert!(!allow_create);
+ None
+ });
+ assert!(matches!(result, Err(error) if error == "KEY_PROVIDER_UNAVAILABLE"));
+ assert!(!path.exists());
+ }
+
+ #[test]
+ fn unavailable_platform_creation_uses_a_stable_fallback_key() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("secret.key");
+ let created = SecretCodec::resolve_platform_default(Some(path.clone()), true, |allow_create| {
+ assert!(allow_create);
+ None
+ })
+ .unwrap();
+ let envelope = created.codec.encrypt("connection", "password", "secret").unwrap();
+ let original = std::fs::read(&path).unwrap();
+ let reopened = SecretCodec::resolve_platform_default(Some(path.clone()), true, |_| {
+ panic!("an existing compatibility key must take precedence over the platform provider")
+ })
+ .unwrap();
+ assert_eq!(reopened.source, SecretKeySource::ManagedDataDir);
+ assert_eq!(reopened.codec.decrypt("connection", "password", &envelope).unwrap(), "secret");
+ assert_eq!(std::fs::read(path).unwrap(), original);
+ }
+
+ #[test]
+ fn unavailable_platform_provider_does_not_replace_a_corrupt_fallback_key() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("secret.key");
+ std::fs::write(&path, "\n").unwrap();
+ for allow_create in [false, true] {
+ let result = SecretCodec::resolve_platform_default(Some(path.clone()), allow_create, |_| None);
+ assert!(matches!(result, Err(error) if error == "SECRET_KEY_INVALID"));
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "\n");
+ }
+ }
+
+ #[test]
+ fn platform_default_falls_back_after_corrupt_compatibility_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let compatibility_path = dir.path().join("secret.key");
+ std::fs::write(&compatibility_path, "\n").unwrap();
+
+ let resolution = SecretCodec::resolve_platform_default(Some(compatibility_path), false, |_| {
+ Some(SecretCodec::new([9u8; 32]))
+ })
+ .unwrap();
+
+ assert_eq!(resolution.source, SecretKeySource::PlatformStore);
+ let envelope = resolution.codec.encrypt("n", "k", "value").unwrap();
+ assert_eq!(resolution.codec.decrypt("n", "k", &envelope).unwrap(), "value");
+ }
+
+ #[test]
+ fn explicit_sources_follow_precedence_without_fallback() {
+ let _guard = env_lock().lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("external.key");
+ let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
+ let previous_env = std::env::var("DBX_SECRET_KEY").ok();
+ std::env::remove_var("DBX_SECRET_KEY_FILE");
+ std::env::remove_var("DBX_SECRET_KEY");
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true).unwrap();
+
+ std::fs::write(&file, "\n").unwrap();
+ std::env::set_var("DBX_SECRET_KEY_FILE", &file);
+ std::env::set_var("DBX_SECRET_KEY", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([2u8; 32]));
+ assert!(matches!(
+ SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false),
+ Err(error) if error == "SECRET_KEY_INVALID"
+ ));
+
+ std::fs::write(&file, base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([1u8; 32])).unwrap();
+ let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ assert_eq!(resolved.source, SecretKeySource::ExplicitFile);
+
+ std::env::remove_var("DBX_SECRET_KEY_FILE");
+ let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ assert_eq!(resolved.source, SecretKeySource::ExplicitEnv);
+
+ restore_env("DBX_SECRET_KEY_FILE", previous_file);
+ restore_env("DBX_SECRET_KEY", previous_env.map(std::ffi::OsString::from));
+ }
+
+ fn restore_env(name: &str, value: Option<std::ffi::OsString>) {
+ if let Some(value) = value {
+ std::env::set_var(name, value);
+ } else {
+ std::env::remove_var(name);
+ }
+ }
+}
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index 147d223d77..c905a95815 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -5,6 +5,7 @@ pub use dbx_drivers::runtime_config::{
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
+use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use log::warn;
@@ -21,10 +22,10 @@ use crate::ai::{
};
use crate::connection_secrets::{
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TLS_SECRET_PREFIX,
- CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY,
- MQ_AUTH_SECRET_PREFIX, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX,
- NACOS_AUTH_PASSWORD_KEY, NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
- PLUGIN_CONNECTION_SECRET_PREFIX,
+ CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQTT_AUTH_PASSWORD_KEY, MQTT_AUTH_SECRET_PREFIX, MQ_AUTH_API_KEY_VALUE_KEY,
+ MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY,
+ MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY, NACOS_AUTH_SECRET_PREFIX,
+ NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
use crate::history::{
@@ -32,12 +33,19 @@ use crate::history::{
HistorySearchRequest, HistorySearchResult, MAX_HISTORY,
};
use crate::models::connection::{ConnectionConfig, DatabaseConnectionInfo, DatabaseType, TransportLayerConfig};
+use crate::persistence::secret_codec::{SecretCodec, SecretKeyPolicy, SecretKeyResolution, SecretKeySource};
use crate::prompt_template::PromptTemplate;
use crate::saved_sql::{SavedSqlFile, SavedSqlFolder, SavedSqlLibrary};
const SSH_TUNNEL_SECRET_PREFIX: &str = "ssh_tunnels.";
const TRANSPORT_LAYER_SECRET_PREFIX: &str = "transport_layers.";
+const URL_PARAMS_SECRET_KEY: &str = "url_params";
+const AI_SECRET_NAMESPACE_PREFIX: &str = "ai_config.";
+const TUNNEL_SECRET_NAMESPACE_PREFIX: &str = "tunnel_profile.";
+const CONFIG_SECRET_BLOB_KEY: &str = "config";
+pub(crate) const GLOBAL_SECRET_NAMESPACE: &str = "dbx.global";
const STORAGE_DB_FILE_NAME: &str = "dbx.db";
+static DATA_MIGRATION_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
const APP_STATE_EDITOR_SETTINGS_KEY: &str = "editor_settings";
const APP_STATE_OPEN_TABS_KEY: &str = "open_tabs";
const APP_STATE_SAVED_SQL_EDITOR_POSITIONS_KEY: &str = "saved_sql_editor_positions";
@@ -169,6 +177,139 @@ pub struct Storage {
/// Path to the SQLite database file (`dbx.db`). Its parent directory is the
/// application data dir where dbx-managed state (e.g. `known_hosts`) lives.
path: PathBuf,
+ /// The owning process chooses the key lifecycle. Desktop keeps the
+ /// platform credential-store default; Web selects the data-dir policy.
+ secret_key_policy: SecretKeyPolicy,
+ /// Standalone CLI/MCP processes may use an existing key but must never
+ /// provision one as a side effect of a write.
+ secret_key_creation_allowed: bool,
+}
+
+pub const SECRET_STORE_MIGRATION_ID: &str = "secret-store-v1";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum MigrationState {
+ Pending,
+ Running,
+ Succeeded,
+ Failed,
+ NotRequired,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyJsonFileStatus {
+ pub name: String,
+ pub exists: bool,
+ pub bytes: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct MigrationPreflight {
+ pub migration_id: String,
+ pub state: MigrationState,
+ pub needs_migration: bool,
+ pub key_provider_available: bool,
+ /// Desktop may provision a new local key only for plaintext-only data.
+ /// Headless callers always set this false.
+ pub key_creation_allowed: bool,
+ pub database_plaintext_count: usize,
+ pub connection_count: usize,
+ pub plugin_secret_count: usize,
+ pub ai_secret_count: usize,
+ pub tunnel_secret_count: usize,
+ pub sync_credential_count: usize,
+ pub legacy_json_files: Vec<LegacyJsonFileStatus>,
+ pub backup_required: bool,
+ pub backup_path: Option<String>,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub data_dir: String,
+ pub backup_dir: String,
+ pub key_file_configured: bool,
+ pub key_file_readable: bool,
+ pub persistent_key_configured: bool,
+ pub key_source: String,
+}
+
+impl MigrationPreflight {
+ pub fn is_ready(&self) -> bool {
+ // A brand-new desktop profile has no secrets and may provision its
+ // first key lazily. Strict headless profiles report missing keys as
+ // `needs_migration`, so no additional provider check is needed here.
+ !self.needs_migration && matches!(self.state, MigrationState::Succeeded | MigrationState::NotRequired)
+ }
+}
+
+struct MigrationStateRecord {
+ state: MigrationState,
+ backup_path: Option<String>,
+ error_code: Option<String>,
+ error_message: Option<String>,
+ source_fingerprint: Option<String>,
+ counts_json: String,
+}
+
+impl Default for MigrationStateRecord {
+ fn default() -> Self {
+ Self {
+ state: MigrationState::Pending,
+ backup_path: None,
+ error_code: None,
+ error_message: None,
+ source_fingerprint: None,
+ counts_json: "{}".to_string(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct MigrationReport {
+ pub migration_id: String,
+ pub state: MigrationState,
+ pub backup_path: Option<String>,
+ pub database_plaintext_count: usize,
+ pub legacy_json_files: Vec<String>,
+ pub verified_secret_count: usize,
+ pub error_code: Option<String>,
+ pub error_message: Option<String>,
+}
+
+/// All state needed by a sync restore is committed through one SQLite
+/// transaction. The sync module deliberately passes plain values here; this
+/// type stays independent from the transport envelope and keeps local secret
+/// re-encryption inside the storage boundary.
+pub(crate) struct SyncImportPlan {
+ pub connections: Vec<ConnectionConfig>,
+ pub tunnel_profiles: Option<Vec<TransportLayerConfig>>,
+ pub tunnel_secret_profiles: Option<Vec<TransportLayerConfig>>,
+ pub sidebar_layout: Option<serde_json::Value>,
+ pub pinned_tree_node_ids: Vec<String>,
+ pub saved_sql: SavedSqlLibrary,
+ pub desktop_settings: DesktopSettings,
+ pub editor_settings: Option<serde_json::Value>,
+ pub connection_secrets: Option<Vec<SyncImportSecret>>,
+ /// Keep destination plugin credentials when the transport payload
+ /// intentionally omitted plugin secrets.
+ pub preserve_plugin_secrets: bool,
+ pub sync_credentials: Option<Vec<SyncImportCredential>>,
+ pub ai_configs: Option<Vec<AiConfigItem>>,
+}
+
+pub(crate) struct SyncImportSecret {
+ pub connection_id: String,
+ pub key: String,
+ pub secret: String,
+}
+
+pub(crate) struct SyncImportCredential {
+ pub account: String,
+ /// JSON representation of an `EncryptedSecretsBlob`, wrapped with the
+ /// destination device secret before it is stored in `connection_secrets`.
+ pub blob: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -712,6 +853,17 @@ impl DesktopIconTheme {
}
const SCHEMA_STATEMENTS: &[&str] = &[
+ "CREATE TABLE IF NOT EXISTS data_migrations (
+ migration_id TEXT PRIMARY KEY,
+ state TEXT NOT NULL,
+ source_fingerprint TEXT,
+ counts_json TEXT NOT NULL DEFAULT '{}',
+ backup_path TEXT,
+ error_code TEXT,
+ error_message TEXT,
+ started_at TEXT,
+ completed_at TEXT
+ )",
"CREATE TABLE IF NOT EXISTS connections (
id TEXT PRIMARY KEY,
config_json TEXT NOT NULL
@@ -720,6 +872,7 @@ const SCHEMA_STATEMENTS: &[&str] = &[
connection_id TEXT NOT NULL,
key TEXT NOT NULL,
secret TEXT NOT NULL,
+ secret_enc TEXT,
PRIMARY KEY (connection_id, key)
)",
"CREATE TABLE IF NOT EXISTS history (
@@ -879,12 +1032,106 @@ const SCHEMA_STATEMENTS: &[&str] = &[
)",
];
+fn migration_counts_json(preflight: &MigrationPreflight) -> String {
+ serde_json::json!({
+ "databasePlaintextCount": preflight.database_plaintext_count,
+ "connectionCount": preflight.connection_count,
+ "pluginSecretCount": preflight.plugin_secret_count,
+ "aiSecretCount": preflight.ai_secret_count,
+ "tunnelSecretCount": preflight.tunnel_secret_count,
+ "syncCredentialCount": preflight.sync_credential_count,
+ })
+ .to_string()
+}
+
+fn migration_backup_paths(counts: &serde_json::Value) -> Result<Vec<String>, String> {
+ let Some(value) = counts.get("backupPaths") else {
+ return Ok(Vec::new());
+ };
+ serde_json::from_value::<Vec<String>>(value.clone())
+ .map_err(|_| "Invalid migration backup manifest: backupPaths must be an array".to_string())
+}
+
+fn migration_error_code(error: &str) -> &'static str {
+ if error.contains("MISSING_MANAGED_KEY") {
+ "MISSING_MANAGED_KEY"
+ } else if error.contains("ENCRYPTED_DATA_KEY_MISSING") {
+ "ENCRYPTED_DATA_KEY_MISSING"
+ } else if error.contains("SECRET_KEY_MISMATCH") {
+ "SECRET_KEY_MISMATCH"
+ } else if error.contains("SECRET_KEY_INVALID") {
+ "SECRET_KEY_INVALID"
+ } else if error.contains("KEY_FILE_UNAVAILABLE") {
+ "KEY_FILE_UNAVAILABLE"
+ } else if error.contains("MISSING_EXTERNAL_KEY") || error.contains("MISSING_PERSISTENT_KEY") {
+ "MISSING_EXTERNAL_KEY"
+ } else if error.contains("KEY_PROVIDER_UNAVAILABLE") {
+ "KEY_PROVIDER_UNAVAILABLE"
+ } else if error.contains("JSON") || error.contains("json") {
+ "LEGACY_JSON_INVALID"
+ } else if error.contains("verification") || error.contains("plaintext remains") {
+ "VERIFICATION_FAILED"
+ } else if error.contains("backup") {
+ "BACKUP_FAILED"
+ } else {
+ "MIGRATION_FAILED"
+ }
+}
+
+fn migration_safe_message(code: &str, _error: &str) -> String {
+ match code {
+ "MISSING_MANAGED_KEY" => "A managed data-directory secret key is required".to_string(),
+ "ENCRYPTED_DATA_KEY_MISSING" => "The key for existing encrypted data is missing".to_string(),
+ "SECRET_KEY_MISMATCH" => "The configured secret key cannot decrypt existing data".to_string(),
+ "SECRET_KEY_INVALID" => "The configured secret key is invalid".to_string(),
+ "KEY_FILE_UNAVAILABLE" => "The configured secret key file is unavailable".to_string(),
+ "MISSING_EXTERNAL_KEY" => "An external secret key is required".to_string(),
+ "BACKUP_FAILED" => "Could not create a migration backup".to_string(),
+ "LEGACY_JSON_INVALID" => "A legacy configuration file could not be read".to_string(),
+ "VERIFICATION_FAILED" => "Encrypted data verification failed".to_string(),
+ "KEY_PROVIDER_UNAVAILABLE" => "The local secret provider is unavailable".to_string(),
+ _ => "Data migration failed; your original data was preserved".to_string(),
+ }
+}
+
+const LEGACY_JSON_NAMES: &[&str] = &[
+ "connections.json",
+ "secrets.json",
+ "ai_config.json",
+ "ai_conversations.json",
+ "query_history.json",
+ "sidebar_layout.json",
+];
+
+fn file_digest(path: &Path) -> Result<String, String> {
+ use sha2::{Digest, Sha256};
+ let bytes = std::fs::read(path).map_err(|_| "Cannot read migration source file".to_string())?;
+ Ok(format!("{:x}", Sha256::digest(bytes)))
+}
+
impl Storage {
pub async fn open(db_path: &Path) -> Result<Self, String> {
+ let storage = Self::open_unmigrated(db_path).await?;
+ let preflight = storage.inspect_data_migration().await?;
+ if preflight.needs_migration && !preflight.key_provider_available && !preflight.key_creation_allowed {
+ return Err(preflight.error_code.unwrap_or_else(|| "KEY_PROVIDER_UNAVAILABLE".to_string()));
+ }
+ if preflight.database_plaintext_count > 0 || preflight.sync_credential_count > 0 {
+ let codec = storage.secret_codec(preflight.key_creation_allowed)?;
+ storage.run_database_legacy_migrations(&codec).await?;
+ }
+ Ok(storage)
+ }
+
+ /// Open the database schema without touching legacy plaintext data. The
+ /// desktop and web applications use this entry point so the migration
+ /// wizard can inspect and execute the upgrade visibly.
+ pub async fn open_unmigrated(db_path: &Path) -> Result<Self, String> {
let path = db_path.to_path_buf();
let db_path = db_path.to_string_lossy().to_string();
let db = connect_path_create_if_missing(&db_path).await?;
- let storage = Self { db, path };
+ let storage =
+ Self { db, path, secret_key_policy: SecretKeyPolicy::PlatformDefault, secret_key_creation_allowed: true };
// Best-effort: switching journal mode is itself a lock-sensitive
// operation, so a transient failure here (e.g. another process
// racing to open the same brand-new database file) must never stop
@@ -893,7 +1140,7 @@ impl Storage {
// depend on the journal-mode switch or the schema pass succeeding.
restrict_db_file_permissions(&storage.path);
storage.enable_wal_mode().await;
- let schema = storage.init_schema().await;
+ let schema = storage.init_schema(false).await;
// Second pass: the journal sidecars only appear once something has
// written to the database, and this runs on the failure path too.
restrict_db_file_permissions(&storage.path);
@@ -901,6 +1148,67 @@ impl Storage {
Ok(storage)
}
+ pub fn with_secret_key_policy(mut self, policy: SecretKeyPolicy) -> Self {
+ self.secret_key_policy = policy;
+ self
+ }
+
+ pub fn with_secret_key_creation(mut self, allowed: bool) -> Self {
+ self.secret_key_creation_allowed = allowed;
+ self
+ }
+
+ /// Compatibility builder for callers that require an externally managed key.
+ pub fn require_persistent_key(self) -> Self {
+ self.with_secret_key_policy(SecretKeyPolicy::ExternalOnly)
+ }
+
+ pub fn require_persistent_secret_key(self) -> Self {
+ self.require_persistent_key()
+ }
+
+ fn resolve_secret_key(&self, allow_create: bool) -> Result<SecretKeyResolution, String> {
+ SecretCodec::resolve(self.secret_key_policy, self.data_dir(), allow_create)
+ }
+
+ fn secret_codec(&self, allow_create: bool) -> Result<SecretCodec, String> {
+ self.resolve_secret_key(allow_create).map(|resolved| resolved.codec)
+ }
+
+ async fn secret_codec_for_write(&self, needs_key: bool) -> Result<SecretCodec, String> {
+ match self.secret_codec(false) {
+ Ok(codec) => Ok(codec),
+ Err(error)
+ if matches!(
+ error.as_str(),
+ "MISSING_MANAGED_KEY" | "MISSING_EXTERNAL_KEY" | "KEY_PROVIDER_UNAVAILABLE"
+ ) =>
+ {
+ if !needs_key {
+ return Ok(SecretCodec::new([0u8; 32]));
+ }
+ if !self.secret_key_creation_allowed {
+ return Err(error);
+ }
+ let has_ciphertext = self
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM connection_secrets WHERE secret_enc IS NOT NULL AND secret_enc <> '')",
+ [],
+ |row| row.get::<_, bool>(0),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await?;
+ if has_ciphertext {
+ return Err("ENCRYPTED_DATA_KEY_MISSING".to_string());
+ }
+ self.secret_codec(true)
+ }
+ Err(error) => Err(error),
+ }
+ }
+
/// Multiple `dbx` processes can end up pointed at the same data directory
/// (e.g. a portable install shared by several users on one machine).
/// WAL mode lets readers and writers proceed without blocking each other,
@@ -944,16 +1252,719 @@ impl Storage {
self.path.parent().unwrap_or_else(|| Path::new("."))
}
- async fn init_schema(&self) -> Result<(), String> {
- self.db.with_connection(|conn| {
+ /// Hash logical rows so changes still in SQLite's WAL and same-size
+ /// replacement JSON files invalidate the cached migration scan.
+ async fn migration_source_fingerprint(&self) -> Result<String, String> {
+ let mut digest = self
+ .with_conn(|conn| {
+ use sha2::{Digest, Sha256};
+ let mut digest = Sha256::new();
+ for table in [
+ "connections",
+ "connection_secrets",
+ "ai_configs",
+ "ai_config",
+ "ai_provider_configs",
+ "tunnel_profiles",
+ "app_settings",
+ ] {
+ digest.update(table.as_bytes());
+ let mut stmt = conn
+ .prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))
+ .map_err(|_| "Cannot inspect migration source")?;
+ let columns = stmt.column_count();
+ let mut rows = stmt.query([]).map_err(|_| "Cannot inspect migration source")?;
+ while let Some(row) = rows.next().map_err(|_| "Cannot inspect migration source")? {
+ for i in 0..columns {
+ let value = format!("{:?}", row.get_ref(i).map_err(|_| "Cannot inspect migration source")?);
+ digest.update((value.len() as u64).to_le_bytes());
+ digest.update(value.as_bytes());
+ }
+ }
+ }
+ Ok(digest)
+ })
+ .await?;
+ use sha2::Digest;
+ for name in LEGACY_JSON_NAMES {
+ digest.update(name.as_bytes());
+ let path = self.data_dir().join(name);
+ if path.exists() {
+ digest.update(file_digest(&path)?.as_bytes());
+ }
+ }
+ Ok(format!("{:x}", digest.finalize()))
+ }
+
+ pub async fn inspect_data_migration(&self) -> Result<MigrationPreflight, String> {
+ let files = self.legacy_json_files().await?;
+ let stored = self.load_migration_state().await?;
+ let current_fingerprint = self.migration_source_fingerprint().await?;
+ let cached_scan: Option<(i64, i64, i64, i64, i64, i64, i64)> =
+ if stored.source_fingerprint.as_deref() == Some(current_fingerprint.as_str()) {
+ serde_json::from_str::<serde_json::Value>(&stored.counts_json).ok().and_then(|value| {
+ // A state transition may update source_fingerprint without a scan.
+ // Legacy caches lacking their own fingerprint must be rescanned.
+ (value["cachedScanFingerprint"].as_str() == Some(current_fingerprint.as_str()))
+ .then(|| serde_json::from_value(value["cachedScan"].clone()).ok())
+ .flatten()
+ })
+ } else {
+ None
+ };
+ let (plaintext, encrypted, connections, plugins, ai, tunnels, sync_credentials) = match cached_scan {
+ Some(scan) => scan,
+ None => {
+ self.with_conn(|conn| {
+ let plaintext: i64 = conn
+ .query_row("SELECT COUNT(*) FROM connection_secrets WHERE secret <> ''", [], |row| row.get(0))
+ .map_err(|e| e.to_string())?;
+ let encrypted: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM connection_secrets WHERE secret_enc IS NOT NULL AND secret_enc <> ''",
+ [],
+ |row| row.get(0),
+ )
+ .map_err(|e| e.to_string())?;
+ let connections: i64 = conn
+ .query_row("SELECT COUNT(*) FROM connections", [], |row| row.get(0))
+ .map_err(|e| e.to_string())?;
+ let plugins: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM connection_secrets WHERE key LIKE 'plugin_connection.%' AND secret <> ''",
+ [],
+ |row| row.get(0),
+ )
+ .map_err(|e| e.to_string())?;
+ let ai = count_ai_secret_rows(conn)?;
+ let tunnels = count_tunnel_secret_rows(conn)?;
+ let inline_connections: i64 = {
+ let mut statement =
+ conn.prepare("SELECT config_json FROM connections").map_err(|e| e.to_string())?;
+ let rows = statement.query_map([], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())?;
+ let mut count = 0;
+ for row in rows {
+ let json = row.map_err(|e| e.to_string())?;
+ let config: ConnectionConfig = serde_json::from_str(&json).map_err(|e| {
+ format!("invalid connection configuration during migration preflight: {e}")
+ })?;
+ if connection_config_has_inline_secrets(&config) {
+ count += 1;
+ }
+ }
+ count
+ };
+ let sync_credentials: i64 = conn
+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| {
+ row.get::<_, String>(0)
+ })
+ .optional()
+ .map_err(|e| e.to_string())?
+ .map(|json| {
+ serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json)
+ .ok()
+ .map(|settings| {
+ ["local_device_secret", "webdav_sync_secrets_passphrase"]
+ .iter()
+ .filter(|key| settings.get(**key).is_some_and(nonempty_json_value))
+ .count()
+ + settings
+ .get("webdav_passwords")
+ .and_then(serde_json::Value::as_object)
+ .map_or(0, serde_json::Map::len)
+ })
+ .unwrap_or(0) as i64
+ })
+ .unwrap_or(0);
+ Ok((plaintext + inline_connections, encrypted, connections, plugins, ai, tunnels, sync_credentials))
+ })
+ .await?
+ }
+ };
+ // This probe is deliberately read-only. It must not create a keyring
+ // entry, key file, or change permissions while displaying status.
+ let key_probe = self.resolve_secret_key(false);
+ let mut key_provider_available = key_probe.is_ok();
+ let database_plaintext_count = (plaintext + ai + tunnels).max(0) as usize;
+ let has_legacy_data =
+ database_plaintext_count > 0 || sync_credentials > 0 || files.iter().any(|file| file.exists);
+ let key_creation_allowed = key_probe
+ .as_ref()
+ .err()
+ .is_some_and(|error| matches!(error.as_str(), "MISSING_MANAGED_KEY" | "KEY_PROVIDER_UNAVAILABLE"))
+ && matches!(self.secret_key_policy, SecretKeyPolicy::PlatformDefault | SecretKeyPolicy::ManagedDataDir)
+ && encrypted == 0
+ && (database_plaintext_count > 0 || sync_credentials > 0 || files.iter().any(|file| file.exists));
+ let mut key_error_code = key_probe.as_ref().err().cloned();
+ if let Ok(resolved) = key_probe.as_ref() {
+ if encrypted > 0 && self.validate_existing_encrypted_data(resolved.codec).await.is_err() {
+ key_provider_available = false;
+ key_error_code = Some("SECRET_KEY_MISMATCH".to_string());
+ }
+ } else if encrypted > 0
+ && matches!(
+ key_error_code.as_deref(),
+ Some("MISSING_MANAGED_KEY") | Some("MISSING_EXTERNAL_KEY") | Some("KEY_PROVIDER_UNAVAILABLE")
+ )
+ {
+ key_error_code = Some("ENCRYPTED_DATA_KEY_MISSING".to_string());
+ }
+ // External-only profiles require explicit configuration. Managed
+ // profiles may create their key later, but never when ciphertext
+ // already exists without its original key.
+ let missing_required_key =
+ !key_provider_available && matches!(self.secret_key_policy, SecretKeyPolicy::ExternalOnly);
+ let missing_existing_key = encrypted > 0 && !key_provider_available;
+ let fatal_key_error = key_error_code.as_deref().is_some_and(|code| {
+ matches!(
+ code,
+ "SECRET_KEY_INVALID"
+ | "SECRET_KEY_MISMATCH"
+ | "KEY_FILE_UNAVAILABLE"
+ | "MISSING_EXTERNAL_KEY"
+ | "ENCRYPTED_DATA_KEY_MISSING"
+ )
+ });
+ let source_changed = stored.source_fingerprint.as_deref().is_some_and(|value| value != current_fingerprint);
+ let state = if fatal_key_error
+ || missing_required_key
+ || missing_existing_key
+ || (has_legacy_data
+ && (source_changed || matches!(stored.state, MigrationState::Succeeded | MigrationState::NotRequired)))
+ {
+ MigrationState::Pending
+ } else if !has_legacy_data && matches!(stored.state, MigrationState::Pending) {
+ MigrationState::NotRequired
+ } else {
+ stored.state.clone()
+ };
+ let needs_migration = fatal_key_error
+ || missing_required_key
+ || missing_existing_key
+ || matches!(state, MigrationState::Failed | MigrationState::Running)
+ || (has_legacy_data && !matches!(state, MigrationState::Succeeded | MigrationState::NotRequired));
+ let (error_code, error_message) = if let Some(code) = key_error_code.clone() {
+ let message = match code.as_str() {
+ "MISSING_MANAGED_KEY" => {
+ "A managed data-directory secret key will be created when migration or first secret write starts"
+ }
+ "ENCRYPTED_DATA_KEY_MISSING" => "The key for existing encrypted data is missing",
+ "SECRET_KEY_INVALID" => "The configured secret key is invalid",
+ "SECRET_KEY_MISMATCH" => "The configured secret key cannot decrypt existing data",
+ "KEY_FILE_UNAVAILABLE" => "The configured secret key file is unavailable",
+ "MISSING_EXTERNAL_KEY" => "An external secret key is required",
+ _ => "The local secret provider is unavailable",
+ };
+ (Some(code), Some(message.to_string()))
+ } else if missing_required_key {
+ (Some("MISSING_EXTERNAL_KEY".to_string()), Some("An external secret key is required".to_string()))
+ } else if missing_existing_key {
+ (
+ Some("ENCRYPTED_DATA_KEY_MISSING".to_string()),
+ Some("The key for existing encrypted data is missing".to_string()),
+ )
+ } else {
+ (stored.error_code, stored.error_message)
+ };
+ let key_source = key_probe
+ .as_ref()
+ .map(|resolved| resolved.source.as_str())
+ .unwrap_or(SecretKeySource::Unavailable.as_str())
+ .to_string();
+ let preflight = MigrationPreflight {
+ migration_id: SECRET_STORE_MIGRATION_ID.to_string(),
+ state,
+ needs_migration,
+ key_provider_available,
+ key_creation_allowed,
+ database_plaintext_count,
+ connection_count: connections.max(0) as usize,
+ plugin_secret_count: plugins.max(0) as usize,
+ ai_secret_count: ai.max(0) as usize,
+ tunnel_secret_count: tunnels.max(0) as usize,
+ sync_credential_count: sync_credentials.max(0) as usize,
+ legacy_json_files: files,
+ backup_required: needs_migration,
+ backup_path: stored.backup_path,
+ error_message,
+ error_code,
+ data_dir: self.data_dir().to_string_lossy().to_string(),
+ backup_dir: self.data_dir().to_string_lossy().to_string(),
+ key_file_configured: std::env::var_os("DBX_SECRET_KEY_FILE").is_some(),
+ key_file_readable: std::env::var("DBX_SECRET_KEY_FILE")
+ .ok()
+ .is_some_and(|path| std::fs::read_to_string(path).is_ok()),
+ persistent_key_configured: key_provider_available,
+ key_source,
+ };
+ Ok(preflight)
+ }
+
+ async fn validate_existing_encrypted_data(&self, codec: SecretCodec) -> Result<(), String> {
+ self.with_conn(move |conn| {
+ let mut statement = conn
+ .prepare(
+ "SELECT connection_id, key, secret_enc FROM connection_secrets
+ WHERE secret_enc IS NOT NULL AND secret_enc <> ''",
+ )
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)))
+ .map_err(|error| error.to_string())?;
+ for row in rows {
+ let (connection_id, key, envelope) = row.map_err(|error| error.to_string())?;
+ codec.decrypt(&connection_id, &key, &envelope).map_err(|_| "SECRET_KEY_MISMATCH".to_string())?;
+ }
+ Ok(())
+ })
+ .await
+ }
+
+ pub async fn start_data_migration(&self) -> Result<MigrationReport, String> {
+ let lock = DATA_MIGRATION_LOCK.get_or_init(|| tokio::sync::Mutex::new(())).lock().await;
+ let preflight = self.inspect_data_migration().await?;
+ if preflight.is_ready() {
+ return Ok(MigrationReport {
+ migration_id: SECRET_STORE_MIGRATION_ID.to_string(),
+ state: preflight.state,
+ backup_path: preflight.backup_path,
+ database_plaintext_count: 0,
+ legacy_json_files: Vec::new(),
+ verified_secret_count: 0,
+ error_code: None,
+ error_message: None,
+ });
+ }
+ if !preflight.key_provider_available && !preflight.key_creation_allowed {
+ let code = preflight.error_code.as_deref().unwrap_or("KEY_PROVIDER_UNAVAILABLE");
+ let error = code.to_string();
+ self.set_migration_state(MigrationState::Failed, None, Some(code), Some(&error), None).await?;
+ return Err(error);
+ }
+ self.set_migration_state(MigrationState::Running, None, None, None, Some(&migration_counts_json(&preflight)))
+ .await?;
+ let backup_path = match self.create_migration_backup().await {
+ Ok(path) => path,
+ Err(error) => {
+ let _ = self
+ .set_migration_state(MigrationState::Failed, None, Some("BACKUP_FAILED"), Some(&error), None)
+ .await;
+ return Err(error);
+ }
+ };
+ self.set_migration_state(MigrationState::Running, Some(&backup_path), None, None, None).await?;
+ let result = async {
+ let codec = self.secret_codec(preflight.key_creation_allowed)?;
+ self.run_database_legacy_migrations(&codec).await?;
+ self.migrate_from_json_staged(self.data_dir()).await?;
+ let verified = self.verify_migration().await?;
+ let renamed = self.finalize_legacy_json_files().await?;
+ self.set_migration_state(
+ MigrationState::Succeeded,
+ Some(&backup_path),
+ None,
+ None,
+ Some(&{
+ let mut counts: serde_json::Value =
+ serde_json::from_str(&migration_counts_json(&preflight)).unwrap();
+ let mut files = serde_json::Map::new();
+ for name in &renamed {
+ let name = format!("{name}.bak");
+ files.insert(
+ name.clone(),
+ serde_json::Value::String(file_digest(&self.data_dir().join(&name))?),
+ );
+ }
+ counts["legacyBakFiles"] = serde_json::Value::Object(files);
+ counts.to_string()
+ }),
+ )
+ .await?;
+ Ok::<MigrationReport, String>(MigrationReport {
+ migration_id: SECRET_STORE_MIGRATION_ID.to_string(),
+ state: MigrationState::Succeeded,
+ backup_path: Some(backup_path.clone()),
+ database_plaintext_count: preflight.database_plaintext_count,
+ legacy_json_files: renamed,
+ verified_secret_count: verified,
+ error_code: None,
+ error_message: None,
+ })
+ }
+ .await;
+ if let Err(error) = &result {
+ // Every database migration helper uses its own transaction. Restore
+ // the pre-migration SQLite snapshot if a later JSON parse, write,
+ // or verification step fails, so the live database is never left
+ // half-upgraded.
+ let _ = self.restore_database_backup(&backup_path).await;
+ let _ = self
+ .set_migration_state(
+ MigrationState::Failed,
+ Some(&backup_path),
+ Some(migration_error_code(error)),
+ Some(error),
+ None,
+ )
+ .await;
+ }
+ drop(lock);
+ result
+ }
+
+ pub async fn retry_data_migration(&self) -> Result<MigrationReport, String> {
+ self.start_data_migration().await
+ }
+
+ pub async fn cleanup_migration_backups(&self) -> Result<(), String> {
+ let _lock = DATA_MIGRATION_LOCK.get_or_init(|| tokio::sync::Mutex::new(())).lock().await;
+ let record = self.load_migration_state().await?;
+ if record.state != MigrationState::Succeeded {
+ return Err("Migration backups may only be cleaned after success".to_string());
+ }
+ let mut counts: serde_json::Value =
+ serde_json::from_str(&record.counts_json).map_err(|_| "Invalid migration backup manifest")?;
+ let mut paths = migration_backup_paths(&counts)?;
+ if let Some(path) = record.backup_path {
+ if !paths.contains(&path) {
+ paths.push(path);
+ }
+ }
+ let root = self.data_dir().canonicalize().map_err(|_| "Cannot access migration backup directory")?;
+ let mut backups = Vec::new();
+ for path in paths {
+ let path = PathBuf::from(path);
+ if !path.exists() {
+ continue;
+ }
+ let candidate = path.canonicalize().map_err(|_| "Invalid migration backup path")?;
+ if candidate.parent() != Some(root.as_path())
+ || !candidate
+ .file_name()
+ .and_then(|v| v.to_str())
+ .is_some_and(|v| v.starts_with("dbx-secret-migration-"))
+ || path.symlink_metadata().map_err(|_| "Invalid migration backup path")?.file_type().is_symlink()
+ {
+ return Err("Invalid migration backup path".to_string());
+ }
+ backups.push(path);
+ }
+ let mut legacy = Vec::new();
+ if let Some(files) = counts["legacyBakFiles"].as_object() {
+ for (name, expected_hash) in files {
+ if !LEGACY_JSON_NAMES.iter().any(|allowed| name == &format!("{allowed}.bak")) {
+ return Err("Invalid legacy backup manifest".to_string());
+ }
+ let path = self.data_dir().join(name);
+ if !path.exists() {
+ continue;
+ }
+ if path.symlink_metadata().map_err(|_| "Cannot inspect legacy backup")?.file_type().is_symlink()
+ || expected_hash.as_str() != Some(file_digest(&path)?.as_str())
+ {
+ return Err("Legacy backup changed; manual inspection is required".to_string());
+ }
+ legacy.push(path);
+ }
+ }
+ // Validate every manifest entry before removing any file.
+ for path in legacy {
+ std::fs::remove_file(path).map_err(|_| "Cannot clean legacy backup")?;
+ }
+ for path in backups {
+ std::fs::remove_dir_all(path).map_err(|_| "Cannot clean migration backup")?;
+ }
+ counts["legacyBakFiles"] = serde_json::json!({});
+ counts["backupPaths"] = serde_json::json!([]);
+ self.with_conn(move |conn| {
+ conn.execute(
+ "UPDATE data_migrations SET backup_path=NULL, counts_json=?1 WHERE migration_id=?2",
+ params![counts.to_string(), SECRET_STORE_MIGRATION_ID],
+ )
+ .map_err(|_| "Cannot update backup manifest")?;
+ Ok(())
+ })
+ .await
+ }
+
+ async fn restore_database_backup(&self, backup_path: &str) -> Result<(), String> {
+ let backup = PathBuf::from(backup_path).join(STORAGE_DB_FILE_NAME);
+ if !backup.is_file() {
+ return Err("migration database backup is missing".to_string());
+ }
+ let live = self.path.clone();
+ self.with_conn(move |_conn| {
+ let source =
+ Connection::open_with_flags(&backup, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(|e| e.to_string())?;
+ source.backup(DatabaseName::Main, &live, None).map_err(|e| e.to_string())
+ })
+ .await
+ }
+
+ async fn legacy_json_files(&self) -> Result<Vec<LegacyJsonFileStatus>, String> {
+ let names = [
+ "connections.json",
+ "secrets.json",
+ "ai_config.json",
+ "ai_conversations.json",
+ "query_history.json",
+ "sidebar_layout.json",
+ ];
+ names
+ .into_iter()
+ .map(|name| {
+ let path = self.data_dir().join(name);
+ let metadata = std::fs::metadata(&path).ok();
+ Ok(LegacyJsonFileStatus {
+ name: name.to_string(),
+ exists: metadata.is_some(),
+ bytes: metadata.map(|m| m.len()).unwrap_or(0),
+ })
+ })
+ .collect()
+ }
+
+ async fn load_migration_state(&self) -> Result<MigrationStateRecord, String> {
+ self.with_conn(|conn| {
+ type MigrationStateRow = (String, Option<String>, Option<String>, Option<String>, Option<String>, Option<String>);
+ let row: Option<MigrationStateRow> = conn
+ .query_row(
+ "SELECT state, backup_path, error_code, error_message, source_fingerprint, counts_json FROM data_migrations WHERE migration_id = ?1",
+ [SECRET_STORE_MIGRATION_ID],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?)),
+ )
+ .optional()
+ .map_err(|e| e.to_string())?;
+ let Some((state, backup, error_code, error_message, source_fingerprint, counts_json)) = row else {
+ return Ok(MigrationStateRecord::default());
+ };
+ let state = serde_json::from_value(serde_json::Value::String(state)).unwrap_or(MigrationState::Pending);
+ Ok(MigrationStateRecord { state, backup_path: backup, error_code, error_message, source_fingerprint, counts_json: counts_json.unwrap_or_else(|| "{}".to_string()) })
+ })
+ .await
+ }
+
+ async fn set_migration_state(
+ &self,
+ state: MigrationState,
+ backup_path: Option<&str>,
+ error_code: Option<&str>,
+ error_message: Option<&str>,
+ counts_json: Option<&str>,
+ ) -> Result<(), String> {
+ let state = serde_json::to_value(state).map_err(|e| e.to_string())?.as_str().unwrap_or("pending").to_string();
+ let backup_path = backup_path.map(ToOwned::to_owned);
+ let error_code = error_code.map(ToOwned::to_owned);
+ let error_message = error_message
+ .map(|value| migration_safe_message(error_code.as_deref().unwrap_or("MIGRATION_FAILED"), value));
+ let previous = self.load_migration_state().await?;
+ let mut counts: serde_json::Value =
+ serde_json::from_str(&previous.counts_json).map_err(|_| "Invalid migration backup manifest".to_string())?;
+ if let Some(update) = counts_json {
+ let update: serde_json::Map<String, serde_json::Value> =
+ serde_json::from_str(update).map_err(|_| "Invalid migration state update".to_string())?;
+ for (key, value) in update {
+ counts[&key] = value;
+ }
+ }
+ let mut paths = migration_backup_paths(&counts)?;
+ for path in previous.backup_path.iter().chain(backup_path.iter()) {
+ if !paths.contains(path) {
+ paths.push(path.clone());
+ }
+ }
+ counts["backupPaths"] = serde_json::json!(paths);
+ // Never associate pre-migration scan counts with the post-migration source.
+ if let Some(object) = counts.as_object_mut() {
+ object.remove("cachedScan");
+ object.remove("cachedScanFingerprint");
+ }
+ let counts_json = counts.to_string();
+ let backup_path = backup_path.or(previous.backup_path);
+ let source_fingerprint = Some(self.migration_source_fingerprint().await?);
+ self.with_conn(move |conn| {
+ conn.execute(
+ "INSERT INTO data_migrations (migration_id,state,source_fingerprint,counts_json,backup_path,error_code,error_message,started_at,completed_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,datetime('now'),CASE WHEN ?2 IN ('succeeded','not_required') THEN datetime('now') ELSE NULL END)
+ ON CONFLICT(migration_id) DO UPDATE SET state=excluded.state, backup_path=excluded.backup_path,
+ source_fingerprint=excluded.source_fingerprint, counts_json=excluded.counts_json,
+ error_code=excluded.error_code, error_message=excluded.error_message,
+ completed_at=excluded.completed_at",
+ params![SECRET_STORE_MIGRATION_ID, state, source_fingerprint, counts_json, backup_path, error_code, error_message],
+ )
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ })
+ .await
+ }
+
+ async fn create_migration_backup(&self) -> Result<String, String> {
+ let root = self.data_dir().join(format!("dbx-secret-migration-{}", Uuid::new_v4()));
+ std::fs::create_dir_all(&root).map_err(|e| e.to_string())?;
+ restrict_backup_permissions(&root);
+ let result = async {
+ let backup_db = root.join(STORAGE_DB_FILE_NAME);
+ let backup_db_for_sqlite = backup_db.clone();
+ self.with_conn(move |conn| {
+ conn.backup(DatabaseName::Main, &backup_db_for_sqlite, None).map_err(|e| e.to_string())
+ })
+ .await?;
+ for name in [
+ "connections.json",
+ "secrets.json",
+ "ai_config.json",
+ "ai_conversations.json",
+ "query_history.json",
+ "sidebar_layout.json",
+ ] {
+ let source = self.data_dir().join(name);
+ if source.is_file() {
+ std::fs::copy(&source, root.join(name)).map_err(|e| e.to_string())?;
+ }
+ }
+ for entry in std::fs::read_dir(&root).map_err(|e| e.to_string())?.flatten() {
+ restrict_backup_file_permissions(&entry.path());
+ }
+ Ok::<(), String>(())
+ }
+ .await;
+ match result {
+ Ok(()) => Ok(root.to_string_lossy().to_string()),
+ Err(error) => {
+ // A failed backup may already contain a plaintext JSON copy.
+ // Remove the temporary directory before reporting failure so a
+ // retry cannot accumulate an untracked sensitive backup.
+ let _ = std::fs::remove_dir_all(&root);
+ Err(error)
+ }
+ }
+ }
+
+ async fn verify_migration(&self) -> Result<usize, String> {
+ let codec = self.secret_codec(false)?;
+ self.with_conn(move |conn| {
+ let mut statement = conn
+ .prepare("SELECT connection_id,key,secret,secret_enc FROM connection_secrets")
+ .map_err(|e| e.to_string())?;
+ let rows = statement
+ .query_map([], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, Option<String>>(3)?,
+ ))
+ })
+ .map_err(|e| e.to_string())?;
+ let mut count = 0;
+ for row in rows {
+ let (namespace, key, legacy, encrypted) = row.map_err(|e| e.to_string())?;
+ if !legacy.is_empty() {
+ return Err("plaintext secret remains after migration".to_string());
+ }
+ if let Some(encrypted) = encrypted.filter(|value| !value.is_empty()) {
+ codec.decrypt(&namespace, &key, &encrypted)?;
+ count += 1;
+ }
+ }
+ let mut configs = conn.prepare("SELECT config_json FROM connections").map_err(|e| e.to_string())?;
+ for row in configs.query_map([], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())? {
+ let json = row.map_err(|e| e.to_string())?;
+ let config: ConnectionConfig = serde_json::from_str(&json).map_err(|e| e.to_string())?;
+ if connection_config_has_inline_secrets(&config) {
+ return Err("plaintext connection configuration remains after migration".to_string());
+ }
+ }
+ for (table, query) in [
+ ("ai_configs", "SELECT config_json FROM ai_configs"),
+ ("ai_config", "SELECT config_json FROM ai_config"),
+ ("ai_provider_configs", "SELECT config_json FROM ai_provider_configs"),
+ ] {
+ let mut statement = conn.prepare(query).map_err(|e| e.to_string())?;
+ for row in statement.query_map([], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())? {
+ let json = row.map_err(|e| e.to_string())?;
+ let config: AiConfig = serde_json::from_str(&json)
+ .map_err(|e| format!("invalid {table} config after migration: {e}"))?;
+ let (_sanitized, secrets) = split_ai_config_secrets(&config)?;
+ if secrets.as_object().is_some_and(|value| !value.is_empty()) {
+ return Err(format!("plaintext {table} configuration remains after migration"));
+ }
+ }
+ }
+ let mut statement = conn.prepare("SELECT config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
+ for row in statement.query_map([], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())? {
+ let json = row.map_err(|e| e.to_string())?;
+ let profile: TransportLayerConfig = serde_json::from_str(&json).map_err(|e| e.to_string())?;
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ if scrubbed != profile {
+ return Err("plaintext tunnel configuration remains after migration".to_string());
+ }
+ }
+ Ok(count)
+ })
+ .await
+ }
+
+ async fn finalize_legacy_json_files(&self) -> Result<Vec<String>, String> {
+ for name in LEGACY_JSON_NAMES {
+ if self.data_dir().join(name).is_file() && self.data_dir().join(format!("{name}.bak")).exists() {
+ return Err("legacy backup file already exists".to_string());
+ }
+ }
+ let mut renamed = Vec::new();
+ for name in [
+ "connections.json",
+ "secrets.json",
+ "ai_config.json",
+ "ai_conversations.json",
+ "query_history.json",
+ "sidebar_layout.json",
+ ] {
+ let source = self.data_dir().join(name);
+ if source.is_file() {
+ let target = self.data_dir().join(format!("{name}.bak"));
+ if target.exists() {
+ return Err("legacy backup file already exists".to_string());
+ }
+ if let Err(error) = std::fs::rename(&source, &target) {
+ // Restore files already renamed in this pass. The DB
+ // snapshot is restored by the caller as well.
+ for previous in &renamed {
+ let old = self.data_dir().join(previous);
+ let bak = self.data_dir().join(format!("{previous}.bak"));
+ let _ = std::fs::rename(bak, old);
+ }
+ return Err(error.to_string());
+ }
+ renamed.push(name.to_string());
+ }
+ }
+ Ok(renamed)
+ }
+
+ async fn init_schema(&self, migrate_legacy: bool) -> Result<(), String> {
+ let migration_codec = migrate_legacy.then(|| self.secret_codec(true)).transpose()?;
+ self.db.with_connection(move |conn| {
for statement in SCHEMA_STATEMENTS {
conn.execute(statement, []).map_err(|e| e.to_string())?;
}
ensure_history_columns_sync(conn)?;
+ ensure_connection_secret_columns_sync(conn)?;
+ if migrate_legacy {
+ let codec = migration_codec.as_ref().ok_or_else(|| "KEY_PROVIDER_UNAVAILABLE".to_string())?;
+ migrate_legacy_connection_secrets_sync(conn, codec)?;
+ migrate_legacy_connection_config_json_sync(conn, codec)?;
+ }
ensure_saved_sql_columns_sync(conn)?;
ensure_tab_runtime_cache_columns_sync(conn)?;
ensure_schema_cache_columns_sync(conn)?;
ensure_ai_configs_columns_sync(conn)?;
+ if migrate_legacy {
+ let codec = migration_codec.as_ref().ok_or_else(|| "KEY_PROVIDER_UNAVAILABLE".to_string())?;
+ migrate_legacy_config_secrets_sync(conn, codec)?;
+ migrate_legacy_app_settings_secrets_sync(conn, codec)?;
+ }
ensure_state_store_columns_sync(conn)?;
ensure_ai_conversations_columns_sync(conn)?;
ensure_ai_runs_columns_sync(conn)?;
@@ -961,6 +1972,17 @@ impl Storage {
})
}
+ async fn run_database_legacy_migrations(&self, codec: &SecretCodec) -> Result<(), String> {
+ let codec = *codec;
+ self.with_conn(move |conn| {
+ migrate_legacy_connection_secrets_sync(conn, &codec)?;
+ migrate_legacy_connection_config_json_sync(conn, &codec)?;
+ migrate_legacy_config_secrets_sync(conn, &codec)?;
+ migrate_legacy_app_settings_secrets_sync(conn, &codec)
+ })
+ .await
+ }
+
async fn with_conn<T, F>(&self, f: F) -> Result<T, String>
where
T: Send + 'static,
@@ -971,67 +1993,470 @@ impl Storage {
}
}
-fn inspect_sqlite_db_file(path: &Path) -> Result<SqliteDbFileState, String> {
- if !path.exists() {
- return Ok(SqliteDbFileState::Missing);
- }
-
- let metadata = path.metadata().map_err(|e| format!("Failed to inspect db file: {e}"))?;
- if metadata.len() == 0 {
- return Ok(SqliteDbFileState::Empty);
+fn inspect_sqlite_db_file(path: &Path) -> Result<SqliteDbFileState, String> {
+ if !path.exists() {
+ return Ok(SqliteDbFileState::Missing);
+ }
+
+ let metadata = path.metadata().map_err(|e| format!("Failed to inspect db file: {e}"))?;
+ if metadata.len() == 0 {
+ return Ok(SqliteDbFileState::Empty);
+ }
+
+ if crate::db::sqlite::path_has_sqlite_header(path)? {
+ Ok(SqliteDbFileState::Valid)
+ } else {
+ Ok(SqliteDbFileState::Invalid)
+ }
+}
+
+fn ensure_schema_cache_columns_sync(conn: &Connection) -> Result<(), String> {
+ let mut columns = HashSet::new();
+ let mut statement = conn.prepare("PRAGMA table_info(schema_cache)").map_err(|error| error.to_string())?;
+ let rows = statement.query_map([], |row| row.get::<_, String>(1)).map_err(|error| error.to_string())?;
+ for row in rows {
+ columns.insert(row.map_err(|error| error.to_string())?);
+ }
+
+ for (name, definition) in [
+ ("updated_at_ms", "INTEGER NOT NULL DEFAULT 0"),
+ ("last_accessed_at_ms", "INTEGER NOT NULL DEFAULT 0"),
+ ("byte_size", "INTEGER NOT NULL DEFAULT 0"),
+ ("owner_id", "TEXT NOT NULL DEFAULT ''"),
+ ] {
+ if !columns.contains(name) {
+ conn.execute(&format!("ALTER TABLE schema_cache ADD COLUMN {name} {definition}"), [])
+ .map_err(|error| error.to_string())?;
+ }
+ }
+
+ conn.execute(
+ "UPDATE schema_cache
+ SET byte_size = length(payload_json)
+ WHERE byte_size = 0 AND payload_json IS NOT NULL",
+ [],
+ )
+ .map_err(|error| error.to_string())?;
+ conn.execute(
+ "UPDATE schema_cache
+ SET updated_at_ms = COALESCE(CAST(strftime('%s', updated_at) AS INTEGER) * 1000, 0),
+ last_accessed_at_ms = COALESCE(CAST(strftime('%s', updated_at) AS INTEGER) * 1000, 0)
+ WHERE updated_at_ms = 0",
+ [],
+ )
+ .map_err(|error| error.to_string())?;
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_schema_cache_updated_at_ms ON schema_cache (updated_at_ms)", [])
+ .map_err(|error| error.to_string())?;
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_schema_cache_owner_lru
+ ON schema_cache (owner_id, last_accessed_at_ms, updated_at_ms, cache_key)",
+ [],
+ )
+ .map_err(|error| error.to_string())?;
+ Ok(())
+}
+
+fn ensure_connection_secret_columns_sync(conn: &Connection) -> Result<(), String> {
+ let mut columns = HashSet::new();
+ let mut statement = conn.prepare("PRAGMA table_info(connection_secrets)").map_err(|error| error.to_string())?;
+ let rows = statement.query_map([], |row| row.get::<_, String>(1)).map_err(|error| error.to_string())?;
+ for row in rows {
+ columns.insert(row.map_err(|error| error.to_string())?);
+ }
+ if !columns.contains("secret_enc") {
+ conn.execute("ALTER TABLE connection_secrets ADD COLUMN secret_enc TEXT", [])
+ .map_err(|error| error.to_string())?;
+ }
+ Ok(())
+}
+
+/// Upgrade every legacy plaintext secret during database initialization. The
+/// old lazy-on-read migration left untouched rows readable in `dbx.db`; doing
+/// this as part of schema startup gives upgrades a deterministic at-rest
+/// guarantee while keeping the migration in one SQLite transaction.
+fn migrate_legacy_connection_secrets_sync(conn: &mut Connection, codec: &SecretCodec) -> Result<(), String> {
+ let rows = {
+ let mut statement = conn
+ .prepare("SELECT connection_id, key, secret FROM connection_secrets WHERE secret <> '' AND (secret_enc IS NULL OR secret_enc = '')")
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)))
+ .map_err(|error| error.to_string())?;
+ rows.collect::<Result<Vec<_>, _>>().map_err(|error| error.to_string())?
+ };
+ if rows.is_empty() {
+ return Ok(());
+ }
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?;
+ for (connection_id, key, secret) in rows {
+ let encrypted = codec.encrypt(&connection_id, &key, &secret)?;
+ tx.execute(
+ "UPDATE connection_secrets SET secret = '', secret_enc = ?1 WHERE connection_id = ?2 AND key = ?3",
+ params![encrypted, connection_id, key],
+ )
+ .map_err(|error| error.to_string())?;
+ }
+ tx.commit().map_err(|error| error.to_string())
+}
+
+/// Older databases stored the hydrated `ConnectionConfig` directly in
+/// `connections.config_json`. Re-save only rows that still contain inline
+/// credentials so the existing connection persistence path moves every
+/// supported field into encrypted `connection_secrets` in one transaction.
+///
+/// The parsed JSON only carries the fields that were still inline, so every
+/// field an earlier release already externalized reads back as empty here.
+/// Re-saving writes those empty values through `persist_secret_in_tx`, which
+/// turns them into DELETEs: a legacy row with an empty inline `password` next to
+/// an inline `url_params` would silently lose its stored password. Snapshot the
+/// stored secrets first so the re-save can never drop one. Rows are copied
+/// verbatim, and `migrate_legacy_connection_secrets_sync` has already encrypted
+/// every legacy plaintext value before this runs, so the restored rows keep the
+/// at-rest guarantee. `save_password == false` is the one case where losing the
+/// password is intended, so that row is not restored.
+fn migrate_legacy_connection_config_json_sync(conn: &mut Connection, codec: &SecretCodec) -> Result<(), String> {
+ let rows = {
+ let mut statement =
+ conn.prepare("SELECT id, config_json FROM connections").map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ rows
+ };
+ let mut legacy = Vec::new();
+ for (id, json) in rows {
+ let config: ConnectionConfig = match serde_json::from_str(&json) {
+ Ok(config) => config,
+ Err(error) => {
+ return Err(format!("Failed to parse legacy connection '{id}' during secret migration: {error}"))
+ }
+ };
+ if connection_config_has_inline_secrets(&config) {
+ legacy.push(config);
+ }
+ }
+ if legacy.is_empty() {
+ return Ok(());
+ }
+ let keep_password =
+ legacy.iter().filter(|config| config.save_password).map(|config| config.id.clone()).collect::<HashSet<_>>();
+ let connection_ids = legacy.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
+ let stored_secrets = load_stored_connection_secrets_sync(conn, &connection_ids)?;
+
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?;
+ for config in legacy {
+ tx.execute("DELETE FROM connections WHERE id = ?1", [&config.id]).map_err(|error| error.to_string())?;
+ persist_connection_in_tx(&tx, codec, &config)?;
+ }
+ for (connection_id, key, secret, secret_enc) in stored_secrets {
+ if key == "password" && !keep_password.contains(&connection_id) {
+ continue;
+ }
+ if connection_secret_in_tx_exists(&tx, &connection_id, &key)? {
+ continue;
+ }
+ tx.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?1, ?2, ?3, ?4)",
+ params![connection_id, key, secret, secret_enc],
+ )
+ .map_err(|error| error.to_string())?;
+ }
+ tx.commit().map_err(|error| error.to_string())
+}
+
+type StoredConnectionSecretRow = (String, String, String, Option<String>);
+
+/// Read every non-empty secret row that belongs to `connection_ids` so a
+/// migration re-save can put back anything it would otherwise delete.
+fn load_stored_connection_secrets_sync(
+ conn: &Connection,
+ connection_ids: &HashSet<String>,
+) -> Result<Vec<StoredConnectionSecretRow>, String> {
+ let mut statement = conn
+ .prepare(
+ "SELECT connection_id, key, secret, secret_enc FROM connection_secrets
+ WHERE secret <> '' OR (secret_enc IS NOT NULL AND secret_enc <> '')",
+ )
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, Option<String>>(3)?,
+ ))
+ })
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ Ok(rows.into_iter().filter(|(connection_id, ..)| connection_ids.contains(connection_id)).collect())
+}
+
+fn connection_secret_in_tx_exists(
+ tx: &rusqlite::Transaction<'_>,
+ connection_id: &str,
+ key: &str,
+) -> Result<bool, String> {
+ tx.query_row(
+ "SELECT 1 FROM connection_secrets
+ WHERE connection_id = ?1 AND key = ?2 AND (secret <> '' OR (secret_enc IS NOT NULL AND secret_enc <> ''))",
+ params![connection_id, key],
+ |_| Ok(()),
+ )
+ .optional()
+ .map(|row| row.is_some())
+ .map_err(|error| error.to_string())
+}
+
+fn connection_config_has_inline_secrets(config: &ConnectionConfig) -> bool {
+ if !config.password.is_empty()
+ || config.url_params.as_deref().is_some_and(|value| !value.is_empty())
+ || config.init_script.as_deref().is_some_and(|value| !value.is_empty())
+ || config.connection_string.as_deref().is_some_and(|value| !value.is_empty())
+ || !config.redis_sentinel_password.is_empty()
+ || config.connection_secrets.values().any(|value| !value.is_empty())
+ {
+ return true;
+ }
+ for layer in &config.transport_layers {
+ match layer {
+ TransportLayerConfig::Ssh(layer) if !layer.password.is_empty() || !layer.key_passphrase.is_empty() => {
+ return true;
+ }
+ TransportLayerConfig::Proxy(layer) if !layer.password.is_empty() => return true,
+ TransportLayerConfig::HttpTunnel(layer) if !layer.token.is_empty() => return true,
+ _ => {}
+ }
+ }
+ let Some(external) = config.external_config.as_ref().and_then(serde_json::Value::as_object) else {
+ return false;
+ };
+ let auth_secret = external
+ .get("auth")
+ .and_then(serde_json::Value::as_object)
+ .and_then(|auth| ["token", "password", "value", "clientSecret"].iter().find_map(|key| auth.get(*key)))
+ .is_some_and(nonempty_json_value);
+ let signing_secret = external
+ .get("tokenSigning")
+ .and_then(serde_json::Value::as_object)
+ .and_then(|signing| signing.get("key"))
+ .is_some_and(nonempty_json_value);
+ let nacos_console_secret = external
+ .get("rnacosConsoleAuth")
+ .and_then(serde_json::Value::as_object)
+ .and_then(|auth| auth.get("password"))
+ .is_some_and(nonempty_json_value);
+ let cassandra_secret = external.get("tls").and_then(serde_json::Value::as_object).is_some_and(|tls| {
+ ["truststore_password", "keystore_password"].iter().filter_map(|key| tls.get(*key)).any(nonempty_json_value)
+ });
+ auth_secret || signing_secret || nacos_console_secret || cassandra_secret
+}
+
+fn nonempty_json_value(value: &serde_json::Value) -> bool {
+ match value {
+ serde_json::Value::String(value) => !value.is_empty(),
+ serde_json::Value::Null => false,
+ _ => true,
+ }
+}
+
+/// Move credentials that older releases kept inline in AI and Tunnel JSON into
+/// the same encrypted secret store used by connections. This runs during
+/// startup so a successful upgrade never leaves a known credential in
+/// `config_json`. Existing encrypted blobs win over stale inline values.
+fn migrate_legacy_config_secrets_sync(conn: &mut Connection, codec: &SecretCodec) -> Result<(), String> {
+ let legacy_ai = {
+ let mut statement =
+ conn.prepare("SELECT id, config_json FROM ai_configs").map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ rows
+ };
+ let legacy_ai_single = {
+ let mut statement =
+ conn.prepare("SELECT config_json FROM ai_config WHERE id = 1").map_err(|error| error.to_string())?;
+ statement.query_row([], |row| row.get::<_, String>(0)).optional().map_err(|error| error.to_string())?
+ };
+ let legacy_ai_providers = {
+ let mut statement =
+ conn.prepare("SELECT provider, config_json FROM ai_provider_configs").map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ rows
+ };
+ let legacy_tunnels = {
+ let mut statement =
+ conn.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|error| error.to_string())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ rows
+ };
+ if legacy_ai.is_empty() && legacy_ai_single.is_none() && legacy_ai_providers.is_empty() && legacy_tunnels.is_empty()
+ {
+ return Ok(());
+ }
+
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?;
+
+ for (id, json) in legacy_ai {
+ let config: AiConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let (sanitized, secrets) = split_ai_config_secrets(&config)?;
+ let sanitized_json = serde_json::to_string(&sanitized).map_err(|error| error.to_string())?;
+ tx.execute("UPDATE ai_configs SET config_json = ?1 WHERE id = ?2", params![sanitized_json, id])
+ .map_err(|error| error.to_string())?;
+ migrate_config_blob_in_tx(&tx, codec, &format!("{AI_SECRET_NAMESPACE_PREFIX}{id}"), &secrets)?;
+ }
+ if let Some(json) = legacy_ai_single {
+ let config: AiConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let (sanitized, secrets) = split_ai_config_secrets(&config)?;
+ let sanitized_json = serde_json::to_string(&sanitized).map_err(|error| error.to_string())?;
+ tx.execute("UPDATE ai_config SET config_json = ?1 WHERE id = 1", [sanitized_json])
+ .map_err(|error| error.to_string())?;
+ migrate_config_blob_in_tx(&tx, codec, &format!("{AI_SECRET_NAMESPACE_PREFIX}legacy"), &secrets)?;
+ }
+ for (provider, json) in legacy_ai_providers {
+ let config: AiConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let (sanitized, secrets) = split_ai_config_secrets(&config)?;
+ let sanitized_json = serde_json::to_string(&sanitized).map_err(|error| error.to_string())?;
+ tx.execute(
+ "UPDATE ai_provider_configs SET config_json = ?1 WHERE provider = ?2",
+ params![sanitized_json, provider],
+ )
+ .map_err(|error| error.to_string())?;
+ migrate_config_blob_in_tx(&tx, codec, &format!("{AI_SECRET_NAMESPACE_PREFIX}provider.{provider}"), &secrets)?;
+ }
+ for (id, json) in legacy_tunnels {
+ let profile: TransportLayerConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let mut sanitized = profile.clone();
+ sanitized.scrub_secrets();
+ let sanitized_json = serde_json::to_string(&sanitized).map_err(|error| error.to_string())?;
+ tx.execute("UPDATE tunnel_profiles SET config_json = ?1 WHERE id = ?2", params![sanitized_json, id])
+ .map_err(|error| error.to_string())?;
+ if sanitized != profile {
+ migrate_config_blob_in_tx(
+ &tx,
+ codec,
+ &format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{id}"),
+ &serde_json::to_value(profile).map_err(|error| error.to_string())?,
+ )?;
+ }
+ }
+ tx.commit().map_err(|error| error.to_string())
+}
+
+fn migrate_config_blob_in_tx(
+ tx: &Transaction<'_>,
+ codec: &SecretCodec,
+ namespace: &str,
+ value: &serde_json::Value,
+) -> Result<(), String> {
+ let has_value = value.as_object().is_some_and(|object| !object.is_empty());
+ if !has_value {
+ return Ok(());
}
-
- if crate::db::sqlite::path_has_sqlite_header(path)? {
- Ok(SqliteDbFileState::Valid)
- } else {
- Ok(SqliteDbFileState::Invalid)
+ let existing: Option<String> = tx
+ .query_row(
+ "SELECT secret_enc FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, CONFIG_SECRET_BLOB_KEY],
+ |row| row.get(0),
+ )
+ .optional()
+ .map_err(|error| error.to_string())?;
+ if existing.as_deref().is_some_and(|value| !value.is_empty()) {
+ tx.execute(
+ "UPDATE connection_secrets SET secret = '' WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, CONFIG_SECRET_BLOB_KEY],
+ )
+ .map_err(|error| error.to_string())?;
+ return Ok(());
}
+ let encrypted = codec.encrypt(namespace, CONFIG_SECRET_BLOB_KEY, &value.to_string())?;
+ tx.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?1, ?2, '', ?3)",
+ params![namespace, CONFIG_SECRET_BLOB_KEY, encrypted],
+ )
+ .map_err(|error| error.to_string())?;
+ Ok(())
}
-fn ensure_schema_cache_columns_sync(conn: &Connection) -> Result<(), String> {
- let mut columns = HashSet::new();
- let mut statement = conn.prepare("PRAGMA table_info(schema_cache)").map_err(|error| error.to_string())?;
- let rows = statement.query_map([], |row| row.get::<_, String>(1)).map_err(|error| error.to_string())?;
- for row in rows {
- columns.insert(row.map_err(|error| error.to_string())?);
+/// Move credentials that older releases kept in `app_settings.settings_json`
+/// into the encrypted global namespace during database initialization. This
+/// is deliberately eager rather than lazy: after a successful upgrade, a
+/// plain-text settings row must not remain merely because the user has not
+/// opened the sync settings screen yet.
+fn migrate_legacy_app_settings_secrets_sync(conn: &mut Connection, codec: &SecretCodec) -> Result<(), String> {
+ let Some(json) = conn
+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get::<_, String>(0))
+ .optional()
+ .map_err(|error| error.to_string())?
+ else {
+ return Ok(());
+ };
+ let mut settings =
+ serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json).map_err(|error| error.to_string())?;
+ let legacy_device_secret = settings.remove("local_device_secret");
+ let legacy_sync_passphrase = settings.remove("webdav_sync_secrets_passphrase");
+ let legacy_accounts =
+ settings.remove("webdav_passwords").and_then(|value| value.as_object().cloned()).unwrap_or_default();
+ let has_migration =
+ legacy_device_secret.is_some() || legacy_sync_passphrase.is_some() || !legacy_accounts.is_empty();
+ if !has_migration {
+ return Ok(());
}
- for (name, definition) in [
- ("updated_at_ms", "INTEGER NOT NULL DEFAULT 0"),
- ("last_accessed_at_ms", "INTEGER NOT NULL DEFAULT 0"),
- ("byte_size", "INTEGER NOT NULL DEFAULT 0"),
- ("owner_id", "TEXT NOT NULL DEFAULT ''"),
- ] {
- if !columns.contains(name) {
- conn.execute(&format!("ALTER TABLE schema_cache ADD COLUMN {name} {definition}"), [])
- .map_err(|error| error.to_string())?;
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?;
+ let store_value = |namespace: &str, key: &str, value: &serde_json::Value| -> Result<(), String> {
+ let plaintext = match value {
+ serde_json::Value::String(value) if !value.is_empty() => value.clone(),
+ value if !value.is_null() => value.to_string(),
+ _ => return Ok(()),
+ };
+ let existing: Option<String> = tx
+ .query_row(
+ "SELECT secret_enc FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, key],
+ |row| row.get(0),
+ )
+ .optional()
+ .map_err(|error| error.to_string())?;
+ if existing.as_deref().is_some_and(|value| !value.is_empty()) {
+ return Ok(());
}
+ let encrypted = codec.encrypt(namespace, key, &plaintext)?;
+ tx.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?1, ?2, '', ?3)",
+ params![namespace, key, encrypted],
+ )
+ .map_err(|error| error.to_string())?;
+ Ok(())
+ };
+
+ if let Some(value) = legacy_device_secret {
+ store_value(GLOBAL_SECRET_NAMESPACE, "local_device_secret", &value)?;
+ }
+ if let Some(value) = legacy_sync_passphrase {
+ store_value(GLOBAL_SECRET_NAMESPACE, "webdav_sync_secrets_passphrase", &value)?;
+ }
+ for (account, value) in legacy_accounts {
+ store_value(GLOBAL_SECRET_NAMESPACE, &format!("webdav_password.{account}"), &value)?;
}
- conn.execute(
- "UPDATE schema_cache
- SET byte_size = length(payload_json)
- WHERE byte_size = 0 AND payload_json IS NOT NULL",
- [],
- )
- .map_err(|error| error.to_string())?;
- conn.execute(
- "UPDATE schema_cache
- SET updated_at_ms = COALESCE(CAST(strftime('%s', updated_at) AS INTEGER) * 1000, 0),
- last_accessed_at_ms = COALESCE(CAST(strftime('%s', updated_at) AS INTEGER) * 1000, 0)
- WHERE updated_at_ms = 0",
- [],
- )
- .map_err(|error| error.to_string())?;
- conn.execute("CREATE INDEX IF NOT EXISTS idx_schema_cache_updated_at_ms ON schema_cache (updated_at_ms)", [])
+ let updated = serde_json::Value::Object(settings).to_string();
+ tx.execute("UPDATE app_settings SET settings_json = ?1 WHERE id = 1", [updated])
.map_err(|error| error.to_string())?;
- conn.execute(
- "CREATE INDEX IF NOT EXISTS idx_schema_cache_owner_lru
- ON schema_cache (owner_id, last_accessed_at_ms, updated_at_ms, cache_key)",
- [],
- )
- .map_err(|error| error.to_string())?;
- Ok(())
+ tx.commit().map_err(|error| error.to_string())
}
fn open_read_only_sqlite(path: &Path) -> Result<Connection, String> {
@@ -1097,8 +2522,8 @@ fn sqlite_file_set(db_path: &Path) -> [PathBuf; 4] {
/// Restrict the SQLite files to the sharing model declared by the data
/// directory itself.
///
-/// `connection_secrets` stores connection passwords in plaintext, so the file
-/// mode is what keeps other local accounts out of the credential store on
+/// `connection_secrets` stores authenticated ciphertext, while the file mode
+/// still keeps the local credential store out of reach of other local accounts on
/// platforms whose per-user data directory is world-traversable: most Linux
/// desktops create `~/.local/share` as 0755, unlike `~/Library` on macOS.
///
@@ -1143,6 +2568,26 @@ fn restrict_db_file_permissions(db_path: &Path) {
#[cfg(not(unix))]
fn restrict_db_file_permissions(_db_path: &Path) {}
+#[cfg(unix)]
+fn restrict_backup_permissions(path: &Path) {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
+}
+
+#[cfg(unix)]
+fn restrict_backup_file_permissions(path: &Path) {
+ use std::os::unix::fs::PermissionsExt;
+ if let Ok(metadata) = std::fs::metadata(path) {
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(metadata.permissions().mode() & 0o600));
+ }
+}
+
+#[cfg(not(unix))]
+fn restrict_backup_permissions(_path: &Path) {}
+
+#[cfg(not(unix))]
+fn restrict_backup_file_permissions(_path: &Path) {}
+
fn ensure_history_columns_sync(conn: &Connection) -> Result<(), String> {
const COLUMNS: &[(&str, &str)] = &[
("activity_kind", "TEXT NOT NULL DEFAULT 'query'"),
@@ -1346,6 +2791,21 @@ fn scrub_mq_auth_secrets(config: &mut ConnectionConfig) {
}
}
+fn scrub_mqtt_auth_secrets(config: &mut ConnectionConfig) {
+ if config.db_type != DatabaseType::Mqtt {
+ return;
+ }
+ let Some(auth) = config.external_config.as_mut().and_then(|external| external.get_mut("auth")) else {
+ return;
+ };
+ let Some(auth) = auth.as_object_mut() else {
+ return;
+ };
+ if auth.get("kind").and_then(serde_json::Value::as_str) == Some("password") {
+ scrub_json_secret(auth, "password");
+ }
+}
+
fn scrub_mq_token_signing_secret(config: &mut ConnectionConfig) {
if config.db_type != DatabaseType::MessageQueue {
return;
@@ -1372,12 +2832,6 @@ fn scrub_nacos_auth_secrets(config: &mut ConnectionConfig) {
}
}
-fn scrub_plugin_connection_secrets(config: &mut ConnectionConfig) {
- for secret in config.connection_secrets.values_mut() {
- secret.clear();
- }
-}
-
fn scrub_cassandra_tls_secrets(config: &mut ConnectionConfig) {
if config.db_type != DatabaseType::Cassandra {
return;
@@ -1765,11 +3219,25 @@ fn ai_provider_from_key(provider: &str) -> Result<AiProvider, String> {
impl Storage {
pub async fn save_ai_config(&self, config: &AiConfig) -> Result<(), String> {
- let json = serde_json::to_string(config).map_err(|e| e.to_string())?;
+ let (sanitized, secrets) = split_ai_config_secrets(config)?;
+ let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
+ let secrets_json = serde_json::to_string(&secrets).map_err(|e| e.to_string())?;
+ let codec = self.secret_codec_for_write(secrets.as_object().is_some_and(|object| !object.is_empty())).await?;
self.with_conn(move |conn| {
- conn.execute("INSERT OR REPLACE INTO ai_config (id, config_json) VALUES (1, ?1)", [json])
- .map(|_| ())
- .map_err(|e| e.to_string())
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
+ tx.execute("INSERT OR REPLACE INTO ai_config (id, config_json) VALUES (1, ?1)", [json])
+ .map_err(|e| e.to_string())?;
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}legacy");
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ persist_secret_in_tx(&tx, &codec, &namespace, CONFIG_SECRET_BLOB_KEY, &secrets_json)?;
+ } else {
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, CONFIG_SECRET_BLOB_KEY],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+ tx.commit().map_err(|e| e.to_string())
})
.await
}
@@ -1782,12 +3250,30 @@ impl Storage {
.map_err(|e| e.to_string())
})
.await?;
- json.map(|value| serde_json::from_str(&value).map_err(|e| e.to_string())).transpose()
+ let Some(json) = json else {
+ return Ok(None);
+ };
+ let mut config: AiConfig = serde_json::from_str(&json).map_err(|e| e.to_string())?;
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}legacy");
+ if let Some(blob) = self.get_secret(&namespace, CONFIG_SECRET_BLOB_KEY).await? {
+ merge_ai_config_secrets(&mut config, &blob)?;
+ } else {
+ let (_sanitized, secrets) = split_ai_config_secrets(&config)?;
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ self.set_secret(
+ &namespace,
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&secrets).map_err(|e| e.to_string())?,
+ )
+ .await?;
+ }
+ }
+ Ok(Some(config))
}
pub async fn save_ai_provider_config(&self, provider: &str, config: &AiConfig) -> Result<(), String> {
let parsed_provider = ai_provider_from_key(provider)?;
- let mut config = config.clone();
+ let (mut config, secrets) = split_ai_config_secrets(config)?;
let config_provider = ai_provider_key(&config.provider);
if config_provider != provider {
warn!(
@@ -1797,20 +3283,34 @@ impl Storage {
config.provider = parsed_provider;
}
let provider = provider.to_string();
+ let secret_provider = provider.clone();
let json = serde_json::to_string(&config).map_err(|e| e.to_string())?;
+ let secrets_json = serde_json::to_string(&secrets).map_err(|e| e.to_string())?;
+ let codec = self.secret_codec_for_write(secrets.as_object().is_some_and(|object| !object.is_empty())).await?;
self.with_conn(move |conn| {
- conn.execute(
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
+ tx.execute(
"INSERT OR REPLACE INTO ai_provider_configs (provider, config_json) VALUES (?1, ?2)",
params![provider, json],
)
- .map(|_| ())
- .map_err(|e| e.to_string())
+ .map_err(|e| e.to_string())?;
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}provider.{secret_provider}");
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ persist_secret_in_tx(&tx, &codec, &namespace, CONFIG_SECRET_BLOB_KEY, &secrets_json)?;
+ } else {
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, CONFIG_SECRET_BLOB_KEY],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+ tx.commit().map_err(|e| e.to_string())
})
.await
}
pub async fn load_ai_provider_configs(&self) -> Result<HashMap<String, AiConfig>, String> {
- self.with_conn(|conn| {
+ let mut map = self.with_conn(|conn| {
let mut stmt = conn
.prepare("SELECT provider, config_json FROM ai_provider_configs")
.map_err(|e| e.to_string())?;
@@ -1841,15 +3341,43 @@ impl Storage {
}
Ok(map)
})
- .await
+ .await?;
+ for (provider, config) in &mut map {
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}provider.{provider}");
+ if let Some(blob) = self.get_secret(&namespace, CONFIG_SECRET_BLOB_KEY).await? {
+ merge_ai_config_secrets(config, &blob)?;
+ } else {
+ let (_sanitized, secrets) = split_ai_config_secrets(config)?;
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ self.set_secret(
+ &namespace,
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&secrets).map_err(|e| e.to_string())?,
+ )
+ .await?;
+ }
+ }
+ }
+ Ok(map)
}
pub async fn save_ai_configs(&self, configs: &[AiConfigItem]) -> Result<(), String> {
- let configs = configs.to_vec();
+ let mut sanitized_configs = Vec::with_capacity(configs.len());
+ let mut secret_blobs = Vec::with_capacity(configs.len());
+ for item in configs {
+ let (config, secrets) = split_ai_config_secrets(&item.config)?;
+ sanitized_configs.push(AiConfigItem { config, ..item.clone() });
+ secret_blobs.push((item.id.clone(), secrets));
+ }
+ let needs_key =
+ secret_blobs.iter().any(|(_, secrets)| secrets.as_object().is_some_and(|object| !object.is_empty()));
+ let codec = self.secret_codec_for_write(needs_key).await?;
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
- for config in &configs {
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
+ .map_err(|e| e.to_string())?;
+ for config in &sanitized_configs {
let json = serde_json::to_string(&config.config).map_err(|e| e.to_string())?;
let models_json = serde_json::to_string(&config.config.models).map_err(|e| e.to_string())?;
tx.execute(
@@ -1861,6 +3389,12 @@ impl Storage {
// Clear old single-config tables — migration is complete, avoids re-migration on empty ai_configs
tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
+ for (id, secrets) in &secret_blobs {
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ let blob = serde_json::to_string(secrets).map_err(|e| e.to_string())?;
+ persist_secret_in_tx(&tx, &codec, &format!("{AI_SECRET_NAMESPACE_PREFIX}{id}"), CONFIG_SECRET_BLOB_KEY, &blob)?;
+ }
+ }
tx.commit().map_err(|e| e.to_string())?;
Ok(())
})
@@ -1868,49 +3402,71 @@ impl Storage {
}
pub async fn load_ai_configs(&self) -> Result<Vec<AiConfigItem>, String> {
- self.with_conn(|conn| {
- let mut stmt = conn
- .prepare("SELECT id, name, model, models, config_json, is_default FROM ai_configs")
- .map_err(|e| e.to_string())?;
- let rows = stmt
- .query_map([], |row| {
- Ok((
- row.get::<_, String>(0)?,
- row.get::<_, String>(1)?,
- row.get::<_, String>(2)?,
- row.get::<_, String>(3)?,
- row.get::<_, String>(4)?,
- row.get::<_, bool>(5)?,
- ))
- })
- .map_err(|e| e.to_string())?;
- let mut configs = Vec::new();
- for row in rows {
- let (id, name, model_col, models_json_col, json, is_default_col) = row.map_err(|e| e.to_string())?;
- match serde_json::from_str::<AiConfig>(&json) {
- Ok(mut config) => {
- // 优先使用列值,如果列值为空则从 config_json 回退读取
- if model_col.is_empty() {
- // config.model 已经从 json 解析出来了
- } else {
- config.model = model_col;
+ let mut configs = self
+ .with_conn(|conn| {
+ let mut stmt = conn
+ .prepare("SELECT id, name, model, models, config_json, is_default FROM ai_configs")
+ .map_err(|e| e.to_string())?;
+ let rows = stmt
+ .query_map([], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, String>(3)?,
+ row.get::<_, String>(4)?,
+ row.get::<_, bool>(5)?,
+ ))
+ })
+ .map_err(|e| e.to_string())?;
+ let mut configs = Vec::new();
+ for row in rows {
+ let (id, name, model_col, models_json_col, json, is_default_col) =
+ row.map_err(|e| e.to_string())?;
+ match serde_json::from_str::<AiConfig>(&json) {
+ Ok(mut config) => {
+ // 优先使用列值,如果列值为空则从 config_json 回退读取
+ if model_col.is_empty() {
+ // config.model 已经从 json 解析出来了
+ } else {
+ config.model = model_col;
+ }
+ if models_json_col.is_empty() || models_json_col == "[]" {
+ // config.models 已经从 json 解析出来了
+ } else {
+ config.models = serde_json::from_str(&models_json_col).unwrap_or_default();
+ }
+ let is_default = is_default_col;
+ configs.push(AiConfigItem { id, name, is_default, config });
}
- if models_json_col.is_empty() || models_json_col == "[]" {
- // config.models 已经从 json 解析出来了
- } else {
- config.models = serde_json::from_str(&models_json_col).unwrap_or_default();
+ Err(e) => {
+ warn!("Failed to deserialize AI config item '{}': {}", id, e);
}
- let is_default = is_default_col;
- configs.push(AiConfigItem { id, name, is_default, config });
- }
- Err(e) => {
- warn!("Failed to deserialize AI config item '{}': {}", id, e);
}
}
+ Ok(configs)
+ })
+ .await?;
+ for item in &mut configs {
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}{}", item.id);
+ if let Some(blob) = self.get_secret(&namespace, CONFIG_SECRET_BLOB_KEY).await? {
+ merge_ai_config_secrets(&mut item.config, &blob)?;
+ } else {
+ // Existing databases kept these fields inside config_json.
+ // Hydrate first, then opportunistically move them into the
+ // encrypted store on the next save.
+ let (_sanitized, secrets) = split_ai_config_secrets(&item.config)?;
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ self.set_secret(
+ &namespace,
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&secrets).map_err(|e| e.to_string())?,
+ )
+ .await?;
+ }
}
- Ok(configs)
- })
- .await
+ }
+ Ok(configs)
}
pub async fn set_default_ai_config(&self, config_id: &str) -> Result<(), String> {
@@ -1927,10 +3483,14 @@ impl Storage {
}
pub async fn save_ai_config_item(&self, config: &AiConfigItem) -> Result<(), String> {
- let config = config.clone();
+ let (sanitized_config, secrets) = split_ai_config_secrets(&config.config)?;
+ let config = AiConfigItem { config: sanitized_config, ..config.clone() };
+ let secret_id = config.id.clone();
+ let codec = self.secret_codec_for_write(secrets.as_object().is_some_and(|object| !object.is_empty())).await?;
self.with_conn(move |conn| {
let json = serde_json::to_string(&config.config).map_err(|e| e.to_string())?;
let models_json = serde_json::to_string(&config.config.models).map_err(|e| e.to_string())?;
+ let secrets_json = serde_json::to_string(&secrets).map_err(|e| e.to_string())?;
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
// 如果设该配置为默认,先清除其他默认,避免与 idx_ai_configs_default 冲突
@@ -1959,6 +3519,17 @@ impl Storage {
}
})?;
+ let namespace = format!("{AI_SECRET_NAMESPACE_PREFIX}{secret_id}");
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ persist_secret_in_tx(&tx, &codec, &namespace, CONFIG_SECRET_BLOB_KEY, &secrets_json)?;
+ } else {
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![namespace, CONFIG_SECRET_BLOB_KEY],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+
tx.commit().map_err(|e| e.to_string())?;
Ok(())
})
@@ -1967,18 +3538,25 @@ impl Storage {
pub async fn delete_ai_config(&self, config_id: &str) -> Result<(), String> {
let config_id = config_id.to_string();
+ let delete_id = config_id.clone();
self.with_conn(move |conn| {
- conn.execute("DELETE FROM ai_configs WHERE id = ?1", params![config_id]).map_err(|e| e.to_string())?;
- Ok(())
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_configs WHERE id = ?1", params![config_id]).map_err(|e| e.to_string())?;
+ tx.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![format!("{AI_SECRET_NAMESPACE_PREFIX}{delete_id}"), CONFIG_SECRET_BLOB_KEY],
+ )
+ .map_err(|e| e.to_string())?;
+ tx.commit().map_err(|e| e.to_string())
})
.await
}
}
// Tunnel profiles — shared transport-layer configurations managed in
-// Settings and referenced from connections via `profile_id`. Secrets stay
-// inline in `config_json`; that matches the plaintext-at-rest posture of
-// `connection_secrets` in the same database file.
+// Settings and referenced from connections via `profile_id`. Public profile
+// metadata is stored in `config_json`; credentials are kept in the encrypted
+// Secret Store and hydrated only when a profile is loaded.
impl Storage {
pub async fn load_tunnel_profiles(&self) -> Result<Vec<TransportLayerConfig>, String> {
@@ -1999,6 +3577,27 @@ impl Storage {
Err(e) => warn!("Failed to deserialize tunnel profile: {}", e),
}
}
+ for profile in &mut profiles {
+ let namespace = format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{}", profile.id());
+ if let Some(blob) = self.get_secret(&namespace, CONFIG_SECRET_BLOB_KEY).await? {
+ let stored: TransportLayerConfig = serde_json::from_str(&blob).map_err(|e| e.to_string())?;
+ merge_missing_tunnel_profile_secrets(profile, &stored);
+ } else {
+ // Migrate legacy inline tunnel credentials on first read.
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ if serde_json::to_value(&scrubbed).map_err(|e| e.to_string())?
+ != serde_json::to_value(&*profile).map_err(|e| e.to_string())?
+ {
+ self.set_secret(
+ &namespace,
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&*profile).map_err(|e| e.to_string())?,
+ )
+ .await?;
+ }
+ }
+ }
Ok(profiles)
}
@@ -2008,11 +3607,23 @@ impl Storage {
return Err("Tunnel profile id must not be empty".to_string());
}
}
- let profiles = profiles.to_vec();
+ let mut sanitized_profiles = Vec::with_capacity(profiles.len());
+ let mut secret_blobs = Vec::with_capacity(profiles.len());
+ for profile in profiles {
+ let mut sanitized = profile.clone();
+ sanitized.scrub_secrets();
+ sanitized_profiles.push(sanitized);
+ secret_blobs.push((profile.id().to_string(), profile.clone()));
+ }
+ let needs_key =
+ sanitized_profiles.iter().zip(&secret_blobs).any(|(sanitized, (_, profile))| sanitized != profile);
+ let codec = self.secret_codec_for_write(needs_key).await?;
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
- for profile in &profiles {
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
+ .map_err(|e| e.to_string())?;
+ for profile in &sanitized_profiles {
let json = serde_json::to_string(profile).map_err(|e| e.to_string())?;
tx.execute(
"INSERT INTO tunnel_profiles (id, config_json) VALUES (?1, ?2)",
@@ -2020,6 +3631,20 @@ impl Storage {
)
.map_err(|e| e.to_string())?;
}
+ for (id, profile) in &secret_blobs {
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ if scrubbed != *profile {
+ let blob = serde_json::to_string(profile).map_err(|e| e.to_string())?;
+ persist_secret_in_tx(
+ &tx,
+ &codec,
+ &format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{id}"),
+ CONFIG_SECRET_BLOB_KEY,
+ &blob,
+ )?;
+ }
+ }
tx.commit().map_err(|e| e.to_string())
})
.await
@@ -2073,6 +3698,99 @@ fn merge_missing_tunnel_profile_secrets(profile: &mut TransportLayerConfig, prev
}
}
+fn split_ai_config_secrets(config: &AiConfig) -> Result<(AiConfig, serde_json::Value), String> {
+ let mut value = serde_json::to_value(config).map_err(|e| e.to_string())?;
+ let Some(object) = value.as_object_mut() else {
+ return Err("AI config must serialize to an object".to_string());
+ };
+ let mut secrets = serde_json::Map::new();
+ for field in [
+ "apiKey",
+ "customHeaders",
+ "proxyUrl",
+ "codexCliEnv",
+ "claudeCodeCliEnv",
+ "piAgentCliEnv",
+ "opencodeCliEnv",
+ "cursorCliEnv",
+ "grokCliEnv",
+ "codebuddyCliEnv",
+ "qoderCliEnv",
+ ] {
+ if let Some(value) = object.remove(field) {
+ let keep = match &value {
+ serde_json::Value::String(value) => !value.is_empty(),
+ serde_json::Value::Object(value) => !value.is_empty(),
+ _ => !value.is_null(),
+ };
+ if keep {
+ secrets.insert(field.to_string(), value);
+ }
+ }
+ }
+ let sanitized = serde_json::from_value(value).map_err(|e| e.to_string())?;
+ Ok((sanitized, serde_json::Value::Object(secrets)))
+}
+
+fn count_ai_secret_rows(conn: &Connection) -> Result<i64, String> {
+ let mut count = 0;
+ for (table, query) in [
+ ("ai_configs", "SELECT id, config_json FROM ai_configs"),
+ ("ai_config", "SELECT id, config_json FROM ai_config"),
+ ("ai_provider_configs", "SELECT provider, config_json FROM ai_provider_configs"),
+ ] {
+ let mut statement = conn.prepare(query).map_err(|e| e.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, rusqlite::types::Value>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|e| e.to_string())?;
+ for row in rows {
+ let (id, json) = row.map_err(|e| e.to_string())?;
+ let id = format!("{id:?}");
+ let config: AiConfig = serde_json::from_str(&json).map_err(|e| format!("invalid {table} row {id}: {e}"))?;
+ let (_, secrets) = split_ai_config_secrets(&config)?;
+ if secrets.as_object().is_some_and(|value| !value.is_empty()) {
+ count += 1;
+ }
+ }
+ }
+ Ok(count)
+}
+
+fn count_tunnel_secret_rows(conn: &Connection) -> Result<i64, String> {
+ let mut statement = conn.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|e| e.to_string())?;
+ let mut count = 0;
+ for row in rows {
+ let (id, json) = row.map_err(|e| e.to_string())?;
+ let profile: TransportLayerConfig =
+ serde_json::from_str(&json).map_err(|e| format!("invalid tunnel profile {id}: {e}"))?;
+ let mut scrubbed = profile.clone();
+ scrubbed.scrub_secrets();
+ if scrubbed != profile {
+ count += 1;
+ }
+ }
+ Ok(count)
+}
+
+fn merge_ai_config_secrets(config: &mut AiConfig, blob: &str) -> Result<(), String> {
+ let secret_value: serde_json::Value = serde_json::from_str(blob).map_err(|e| e.to_string())?;
+ let mut value = serde_json::to_value(&*config).map_err(|e| e.to_string())?;
+ let Some(target) = value.as_object_mut() else {
+ return Err("AI config must serialize to an object".to_string());
+ };
+ let Some(source) = secret_value.as_object() else {
+ return Err("AI secret payload must be an object".to_string());
+ };
+ for (key, value) in source {
+ target.insert(key.clone(), value.clone());
+ }
+ *config = serde_json::from_value(value).map_err(|e| e.to_string())?;
+ Ok(())
+}
+
// App Settings
impl Storage {
@@ -2515,43 +4233,102 @@ impl Storage {
pub async fn load_or_create_local_device_secret(&self) -> Result<String, String> {
let mut settings = self.load_app_settings_json().await?;
- if let Some(secret) = settings.get("local_device_secret").and_then(|value| value.as_str()) {
+ if let Some(secret) = self.get_secret(GLOBAL_SECRET_NAMESPACE, "local_device_secret").await? {
+ return Ok(secret);
+ }
+ if let Some(secret) = settings.get("local_device_secret").and_then(|value| value.as_str()).map(str::to_string) {
if !secret.is_empty() {
- return Ok(secret.to_string());
+ self.set_secret(GLOBAL_SECRET_NAMESPACE, "local_device_secret", &secret).await?;
+ settings.remove("local_device_secret");
+ self.save_app_settings_json(&settings).await?;
+ return Ok(secret);
}
}
let secret = Uuid::new_v4().to_string();
- settings.insert("local_device_secret".to_string(), serde_json::Value::String(secret.clone()));
- self.save_app_settings_json(&settings).await?;
+ self.set_secret(GLOBAL_SECRET_NAMESPACE, "local_device_secret", &secret).await?;
Ok(secret)
}
pub async fn save_webdav_password_blob(&self, account: &str, blob: &serde_json::Value) -> Result<(), String> {
- let mut settings = self.load_app_settings_json().await?;
- let mut credentials =
- settings.remove("webdav_passwords").and_then(|value| value.as_object().cloned()).unwrap_or_default();
- credentials.insert(account.to_string(), blob.clone());
- settings.insert("webdav_passwords".to_string(), serde_json::Value::Object(credentials));
- self.save_app_settings_json(&settings).await
+ self.set_secret(
+ GLOBAL_SECRET_NAMESPACE,
+ &format!("webdav_password.{account}"),
+ &serde_json::to_string(blob).map_err(|e| e.to_string())?,
+ )
+ .await
}
pub async fn load_webdav_password_blob(&self, account: &str) -> Result<Option<serde_json::Value>, String> {
- let settings = self.load_app_settings_json().await?;
- Ok(settings
+ if let Some(blob) = self.get_secret(GLOBAL_SECRET_NAMESPACE, &format!("webdav_password.{account}")).await? {
+ return serde_json::from_str(&blob).map(Some).map_err(|e| e.to_string());
+ }
+ let mut settings = self.load_app_settings_json().await?;
+ let legacy = settings
.get("webdav_passwords")
.and_then(|value| value.as_object())
.and_then(|credentials| credentials.get(account))
- .cloned())
+ .cloned();
+ if let Some(blob) = &legacy {
+ self.save_webdav_password_blob(account, blob).await?;
+ if let Some(credentials) = settings.get_mut("webdav_passwords").and_then(|value| value.as_object_mut()) {
+ credentials.remove(account);
+ }
+ self.save_app_settings_json(&settings).await?;
+ }
+ Ok(legacy)
+ }
+
+ /// List locally stored WebDAV/snippet credential account names so the
+ /// sync transport can explicitly re-encrypt them for another device.
+ pub async fn load_webdav_password_accounts(&self) -> Result<Vec<String>, String> {
+ const PREFIX: &str = "webdav_password.";
+ let mut accounts = self
+ .with_conn(|conn| {
+ let mut statement = conn
+ .prepare("SELECT key FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2")
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map(params![GLOBAL_SECRET_NAMESPACE, format!("{PREFIX}%")], |row| row.get::<_, String>(0))
+ .map_err(|error| error.to_string())?;
+ let mut accounts = Vec::new();
+ for row in rows {
+ let key = row.map_err(|error| error.to_string())?;
+ if let Some(account) = key.strip_prefix(PREFIX).filter(|account| !account.is_empty()) {
+ accounts.push(account.to_string());
+ }
+ }
+ accounts.sort();
+ accounts.dedup();
+ Ok(accounts)
+ })
+ .await?;
+
+ // Upgrade legacy app-settings credentials even when the caller is
+ // building a snapshot directly (without first making a WebDAV or
+ // snippet request that would otherwise trigger lazy migration).
+ let legacy_accounts = self
+ .load_app_settings_json()
+ .await?
+ .get("webdav_passwords")
+ .and_then(serde_json::Value::as_object)
+ .map(|credentials| credentials.keys().cloned().collect::<Vec<_>>())
+ .unwrap_or_default();
+ for account in legacy_accounts {
+ if self.load_webdav_password_blob(&account).await?.is_some() {
+ accounts.push(account);
+ }
+ }
+ accounts.sort();
+ accounts.dedup();
+ Ok(accounts)
}
pub async fn delete_webdav_password_blob(&self, account: &str) -> Result<(), String> {
+ self.delete_secret(GLOBAL_SECRET_NAMESPACE, &format!("webdav_password.{account}")).await?;
let mut settings = self.load_app_settings_json().await?;
- let Some(mut credentials) = settings.remove("webdav_passwords").and_then(|value| value.as_object().cloned())
- else {
- return Ok(());
- };
- credentials.remove(account);
- settings.insert("webdav_passwords".to_string(), serde_json::Value::Object(credentials));
+ if let Some(credentials) = settings.get_mut("webdav_passwords").and_then(|value| value.as_object_mut()) {
+ credentials.remove(account);
+ }
self.save_app_settings_json(&settings).await
}
@@ -2563,7 +4340,12 @@ impl Storage {
let mut settings = self.load_app_settings_json().await?;
settings.insert("webdav_sync_secrets_enabled".to_string(), serde_json::Value::Bool(enabled));
if let Some(blob) = blob {
- settings.insert("webdav_sync_secrets_passphrase".to_string(), blob.clone());
+ self.set_secret(
+ GLOBAL_SECRET_NAMESPACE,
+ "webdav_sync_secrets_passphrase",
+ &serde_json::to_string(blob).map_err(|e| e.to_string())?,
+ )
+ .await?;
}
self.save_app_settings_json(&settings).await
}
@@ -2574,12 +4356,25 @@ impl Storage {
}
pub async fn load_webdav_sync_secrets_passphrase_blob(&self) -> Result<Option<serde_json::Value>, String> {
- let settings = self.load_app_settings_json().await?;
- Ok(settings.get("webdav_sync_secrets_passphrase").cloned())
+ if let Some(blob) = self.get_secret(GLOBAL_SECRET_NAMESPACE, "webdav_sync_secrets_passphrase").await? {
+ return serde_json::from_str(&blob).map(Some).map_err(|e| e.to_string());
+ }
+ let mut settings = self.load_app_settings_json().await?;
+ let legacy = settings.remove("webdav_sync_secrets_passphrase");
+ if let Some(blob) = &legacy {
+ self.save_webdav_sync_secrets_preference(
+ settings.get("webdav_sync_secrets_enabled").and_then(serde_json::Value::as_bool).unwrap_or(false),
+ Some(blob),
+ )
+ .await?;
+ self.save_app_settings_json(&settings).await?;
+ }
+ Ok(legacy)
}
pub async fn delete_webdav_sync_secrets_passphrase_blob(&self) -> Result<(), String> {
let mut settings = self.load_app_settings_json().await?;
+ self.delete_secret(GLOBAL_SECRET_NAMESPACE, "webdav_sync_secrets_passphrase").await?;
settings.remove("webdav_sync_secrets_passphrase");
self.save_app_settings_json(&settings).await
}
@@ -3290,11 +5085,13 @@ fn ensure_mcp_connection_change_allowed_in_tx(
fn sanitized_connection_config(config: &ConnectionConfig) -> ConnectionConfig {
let mut sanitized = config.clone().canonicalized();
sanitized.password = String::new();
+ sanitized.url_params = None;
scrub_transport_layer_secrets(&mut sanitized);
sanitized.redis_sentinel_password = String::new();
sanitized.connection_string = None;
sanitized.init_script = None;
scrub_mq_auth_secrets(&mut sanitized);
+ scrub_mqtt_auth_secrets(&mut sanitized);
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
@@ -3302,7 +5099,11 @@ fn sanitized_connection_config(config: &ConnectionConfig) -> ConnectionConfig {
sanitized
}
-fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionConfig) -> Result<(), String> {
+fn persist_connection_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ config: &ConnectionConfig,
+) -> Result<(), String> {
let config = config.clone().canonicalized();
let config_id = config.id.clone();
let sanitized = sanitized_connection_config(&config);
@@ -3312,20 +5113,27 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
.map_err(|e| e.to_string())?;
if config.save_password {
- persist_secret_in_tx(tx, &config.id, "password", &config.password)?;
+ persist_secret_in_tx(tx, codec, &config.id, "password", &config.password)?;
} else {
// "Don't save password": write an empty value, which persist_secret_in_tx
// turns into a DELETE — the password secret is never persisted (and any
// previously stored secret is removed on this save).
- persist_secret_in_tx(tx, &config.id, "password", "")?;
+ persist_secret_in_tx(tx, codec, &config.id, "password", "")?;
}
delete_secret_prefix_in_tx(tx, &config.id, TRANSPORT_LAYER_SECRET_PREFIX)?;
for (index, layer) in config.transport_layers.iter().enumerate() {
match layer {
TransportLayerConfig::Ssh(ssh) => {
- persist_secret_in_tx(tx, &config.id, &transport_layer_ssh_password_key(index, layer), &ssh.password)?;
persist_secret_in_tx(
tx,
+ codec,
+ &config.id,
+ &transport_layer_ssh_password_key(index, layer),
+ &ssh.password,
+ )?;
+ persist_secret_in_tx(
+ tx,
+ codec,
&config.id,
&transport_layer_ssh_key_passphrase_key(index, layer),
&ssh.key_passphrase,
@@ -3334,6 +5142,7 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
TransportLayerConfig::Proxy(proxy) => {
persist_secret_in_tx(
tx,
+ codec,
&config.id,
&transport_layer_proxy_password_key(index, layer),
&proxy.password,
@@ -3342,6 +5151,7 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
TransportLayerConfig::HttpTunnel(http) => {
persist_secret_in_tx(
tx,
+ codec,
&config.id,
&transport_layer_http_tunnel_token_key(index, layer),
&http.token,
@@ -3349,13 +5159,18 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
}
}
}
- persist_secret_in_tx(tx, &config.id, "redis_sentinel_password", &config.redis_sentinel_password)?;
- persist_secret_in_tx(tx, &config.id, "ssh_password", "")?;
- persist_secret_in_tx(tx, &config.id, "ssh_key_passphrase", "")?;
- persist_secret_in_tx(tx, &config.id, "proxy_password", "")?;
+ persist_secret_in_tx(tx, codec, &config.id, "redis_sentinel_password", &config.redis_sentinel_password)?;
+ if let Some(url_params) = &config.url_params {
+ persist_secret_in_tx(tx, codec, &config.id, URL_PARAMS_SECRET_KEY, url_params)?;
+ } else {
+ persist_secret_in_tx(tx, codec, &config.id, URL_PARAMS_SECRET_KEY, "")?;
+ }
+ persist_secret_in_tx(tx, codec, &config.id, "ssh_password", "")?;
+ persist_secret_in_tx(tx, codec, &config.id, "ssh_key_passphrase", "")?;
+ persist_secret_in_tx(tx, codec, &config.id, "proxy_password", "")?;
delete_secret_prefix_in_tx(tx, &config.id, SSH_TUNNEL_SECRET_PREFIX)?;
if let Some(cs) = &config.connection_string {
- persist_secret_in_tx(tx, &config.id, "connection_string", cs)?;
+ persist_secret_in_tx(tx, codec, &config.id, "connection_string", cs)?;
} else {
tx.execute(
"DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
@@ -3364,7 +5179,7 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
.map_err(|e| e.to_string())?;
}
if let Some(script) = &config.init_script {
- persist_secret_in_tx(tx, &config.id, "init_script", script)?;
+ persist_secret_in_tx(tx, codec, &config.id, "init_script", script)?;
} else {
tx.execute(
"DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
@@ -3372,14 +5187,15 @@ fn persist_connection_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionC
)
.map_err(|e| e.to_string())?;
}
- persist_mq_auth_secrets_in_tx(tx, &config)?;
- persist_mq_token_signing_secret_in_tx(tx, &config)?;
- persist_nacos_auth_secrets_in_tx(tx, &config)?;
- persist_cassandra_tls_secrets_in_tx(tx, &config)?;
+ persist_mq_auth_secrets_in_tx(tx, codec, &config)?;
+ persist_mqtt_auth_secrets_in_tx(tx, codec, &config)?;
+ persist_mq_token_signing_secret_in_tx(tx, codec, &config)?;
+ persist_nacos_auth_secrets_in_tx(tx, codec, &config)?;
+ persist_cassandra_tls_secrets_in_tx(tx, codec, &config)?;
delete_secret_prefix_in_tx(tx, &config.id, PLUGIN_CONNECTION_SECRET_PREFIX)?;
for (key, secret) in &config.connection_secrets {
if !key.is_empty() {
- persist_secret_in_tx(tx, &config.id, &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"), secret)?;
+ persist_secret_in_tx(tx, codec, &config.id, &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"), secret)?;
}
}
Ok(())
@@ -3390,18 +5206,28 @@ async fn load_plugin_connection_secrets(
connection_id: &str,
) -> Result<HashMap<String, String>, String> {
let connection_id = connection_id.to_string();
+ let secret_storage = storage.clone();
storage
.with_conn(move |conn| {
let like = format!("{PLUGIN_CONNECTION_SECRET_PREFIX}%");
let mut statement = conn
- .prepare("SELECT key, secret FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2")
+ .prepare(
+ "SELECT key, secret, secret_enc FROM connection_secrets WHERE connection_id = ?1 AND key LIKE ?2",
+ )
.map_err(|error| error.to_string())?;
let rows = statement
- .query_map(params![connection_id, like], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .query_map(params![connection_id, like], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option<String>>(2)?))
+ })
.map_err(|error| error.to_string())?;
let mut secrets = HashMap::new();
for row in rows {
- let (key, secret) = row.map_err(|error| error.to_string())?;
+ let (key, secret, encrypted) = row.map_err(|error| error.to_string())?;
+ let secret = encrypted
+ .filter(|value| !value.is_empty())
+ .map(|value| secret_storage.secret_codec(false)?.decrypt(&connection_id, &key, &value))
+ .transpose()?
+ .unwrap_or(secret);
if let Some(key) = key.strip_prefix(PLUGIN_CONNECTION_SECRET_PREFIX) {
secrets.insert(key.to_string(), secret);
}
@@ -3503,10 +5329,23 @@ fn delete_unreferenced_connection_secrets_in_tx(
retained_ids: &[String],
) -> Result<(), String> {
if retained_ids.is_empty() {
- tx.execute("DELETE FROM connection_secrets", []).map_err(|e| e.to_string())?;
+ tx.execute(
+ "DELETE FROM connection_secrets
+ WHERE connection_id NOT LIKE 'ai_config.%'
+ AND connection_id NOT LIKE 'tunnel_profile.%'
+ AND connection_id != 'dbx.global'",
+ [],
+ )
+ .map_err(|e| e.to_string())?;
} else {
let placeholders = vec!["?"; retained_ids.len()].join(",");
- let sql = format!("DELETE FROM connection_secrets WHERE connection_id NOT IN ({placeholders})");
+ let sql = format!(
+ "DELETE FROM connection_secrets
+ WHERE connection_id NOT IN ({placeholders})
+ AND connection_id NOT LIKE 'ai_config.%'
+ AND connection_id NOT LIKE 'tunnel_profile.%'
+ AND connection_id != 'dbx.global'"
+ );
let ids = retained_ids.iter().map(|id| id as &dyn ToSql);
tx.execute(&sql, params_from_iter(ids)).map_err(|e| e.to_string())?;
}
@@ -3514,11 +5353,88 @@ fn delete_unreferenced_connection_secrets_in_tx(
}
impl Storage {
+ pub(crate) async fn apply_sync_import_transaction(&self, plan: SyncImportPlan) -> Result<(), String> {
+ let needs_key =
+ plan.connections.iter().any(|config| config.url_params.as_deref().is_some_and(|value| !value.is_empty()))
+ || plan
+ .connection_secrets
+ .as_ref()
+ .is_some_and(|secrets| secrets.iter().any(|secret| !secret.secret.is_empty()))
+ || plan.sync_credentials.as_ref().is_some_and(|credentials| !credentials.is_empty())
+ || plan.tunnel_secret_profiles.is_some()
+ || plan.ai_configs.is_some();
+ let codec = self.secret_codec_for_write(needs_key).await?;
+ self.with_conn(move |conn| {
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
+
+ apply_sync_connections_in_tx(&tx, &codec, &plan.connections)?;
+ if let Some(profiles) = &plan.tunnel_profiles {
+ apply_sync_tunnel_profiles_in_tx(&tx, &codec, profiles, plan.tunnel_secret_profiles.as_deref())?;
+ }
+ if let Some(layout) = &plan.sidebar_layout {
+ let json = serde_json::to_string(layout).map_err(|e| e.to_string())?;
+ tx.execute("INSERT OR REPLACE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
+ .map_err(|e| e.to_string())?;
+ }
+ let pinned = serde_json::to_string(&plan.pinned_tree_node_ids).map_err(|e| e.to_string())?;
+ update_app_settings_key_in_tx(
+ &tx,
+ "pinned_tree_node_ids",
+ serde_json::from_str(&pinned).map_err(|e| e.to_string())?,
+ )?;
+ apply_saved_sql_in_tx(&tx, &plan.saved_sql)?;
+ apply_desktop_settings_in_tx(&tx, &plan.desktop_settings)?;
+ if let Some(editor_settings) = &plan.editor_settings {
+ let value = serde_json::to_string(editor_settings).map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT OR REPLACE INTO app_state (key, value_json) VALUES (?1, ?2)",
+ params![APP_STATE_EDITOR_SETTINGS_KEY, value],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+ if let Some(ai_configs) = &plan.ai_configs {
+ apply_ai_configs_in_tx(&tx, &codec, ai_configs)?;
+ }
+ if let Some(secrets) = &plan.connection_secrets {
+ clear_sync_connection_secrets_in_tx(&tx, &plan.connections, plan.preserve_plugin_secrets)?;
+ for secret in secrets {
+ if secret.secret.is_empty() {
+ continue;
+ }
+ persist_secret_in_tx(&tx, &codec, &secret.connection_id, &secret.key, &secret.secret)?;
+ }
+ }
+ if let Some(credentials) = &plan.sync_credentials {
+ tx.execute(
+ "DELETE FROM connection_secrets
+ WHERE connection_id = ?1 AND key LIKE 'webdav_password.%'",
+ [GLOBAL_SECRET_NAMESPACE],
+ )
+ .map_err(|e| e.to_string())?;
+ for credential in credentials {
+ if credential.account.trim().is_empty() {
+ return Err("Synced credential account must not be empty".to_string());
+ }
+ persist_secret_in_tx(
+ &tx,
+ &codec,
+ GLOBAL_SECRET_NAMESPACE,
+ &format!("webdav_password.{}", credential.account),
+ &credential.blob,
+ )?;
+ }
+ }
+ tx.commit().map_err(|e| e.to_string())
+ })
+ .await
+ }
+
pub async fn save_connection_metadata_preserving_secrets(
&self,
configs: &[ConnectionConfig],
) -> Result<(), String> {
let configs = configs.to_vec();
+ let codec = self.secret_codec_for_write(false).await?;
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
@@ -3531,16 +5447,18 @@ impl Storage {
// Metadata-only imports/sync preserve existing secrets by default.
// This preference is an exception: retaining the old password would
// make a no-save connection silently authenticate without prompting.
- persist_secret_in_tx(&tx, &config.id, "password", "")?;
+ persist_secret_in_tx(&tx, &codec, &config.id, "password", "")?;
delete_secret_prefix_in_tx(&tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
}
let mut sanitized = config;
sanitized.password = String::new();
+ sanitized.url_params = None;
scrub_transport_layer_secrets(&mut sanitized);
sanitized.redis_sentinel_password = String::new();
sanitized.connection_string = None;
sanitized.init_script = None;
scrub_mq_auth_secrets(&mut sanitized);
+ scrub_mqtt_auth_secrets(&mut sanitized);
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
@@ -3561,13 +5479,15 @@ impl Storage {
pub async fn save_connections(&self, configs: &[ConnectionConfig]) -> Result<(), String> {
let configs = configs.to_vec();
+ let needs_key = configs.iter().any(connection_config_has_inline_secrets);
+ let codec = self.secret_codec_for_write(needs_key).await?;
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
let mut retained_ids = preserve_unreadable_connections_for_replacement(&tx, &replacement_ids)?;
for config in &configs {
- persist_connection_in_tx(&tx, config)?;
+ persist_connection_in_tx(&tx, &codec, config)?;
}
retained_ids.extend(configs.iter().map(|config| config.id.clone()));
@@ -3580,10 +5500,11 @@ impl Storage {
pub async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {
let config = config.canonicalized();
+ let codec = self.secret_codec_for_write(connection_config_has_inline_secrets(&config)).await?;
self.with_conn(move |conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
ensure_mcp_connection_change_allowed_in_tx(&tx, None)?;
- persist_connection_in_tx(&tx, &config)?;
+ persist_connection_in_tx(&tx, &codec, &config)?;
tx.commit().map_err(|e| e.to_string())?;
Ok(config)
})
@@ -3600,6 +5521,7 @@ impl Storage {
let copy_id = copy_id.to_string();
let copied_id = copy_id.clone();
let copy_name = copy_name.to_string();
+ let codec = self.secret_codec(false)?;
self.with_conn(move |conn| {
let tx =
conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|error| error.to_string())?;
@@ -3629,12 +5551,33 @@ impl Storage {
let copy_json = serde_json::to_string(&copy).map_err(|error| error.to_string())?;
tx.execute("INSERT INTO connections (id, config_json) VALUES (?1, ?2)", params![copy_id, copy_json])
.map_err(|error| error.to_string())?;
- tx.execute(
- "INSERT INTO connection_secrets (connection_id, key, secret) \
- SELECT ?1, key, secret FROM connection_secrets WHERE connection_id = ?2",
- params![copy.id, source_id],
- )
- .map_err(|error| error.to_string())?;
+ let source_secrets = {
+ let mut statement = tx
+ .prepare("SELECT key, secret, secret_enc FROM connection_secrets WHERE connection_id = ?1")
+ .map_err(|error| error.to_string())?;
+ let rows = statement
+ .query_map([&source_id], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option<String>>(2)?))
+ })
+ .map_err(|error| error.to_string())?;
+ rows.collect::<Result<Vec<_>, _>>().map_err(|error| error.to_string())?
+ };
+ for (key, legacy, encrypted) in source_secrets {
+ let plaintext = encrypted
+ .filter(|value| !value.is_empty())
+ .map(|value| codec.decrypt(&source_id, &key, &value))
+ .transpose()?
+ .unwrap_or(legacy);
+ if plaintext.is_empty() {
+ continue;
+ }
+ let rewrapped = codec.encrypt(&copy.id, &key, &plaintext)?;
+ tx.execute(
+ "INSERT INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?1, ?2, '', ?3)",
+ params![copy.id, key, rewrapped],
+ )
+ .map_err(|error| error.to_string())?;
+ }
copy_sidebar_layout_entry_in_tx(&tx, &source_id, &copy.id)?;
tx.commit().map_err(|error| error.to_string())?;
Ok(copy)
@@ -3678,7 +5621,9 @@ impl Storage {
.optional()
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("Connection config not found: {connection_id}"))?;
- let mut config: ConnectionConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let mut config = sanitized_connection_config(
+ &serde_json::from_str::<ConnectionConfig>(&json).map_err(|error| error.to_string())?,
+ );
config.database_info = database_info;
let json = serde_json::to_string(&config).map_err(|error| error.to_string())?;
conn.execute("UPDATE connections SET config_json = ?1 WHERE id = ?2", params![json, connection_id])
@@ -3736,7 +5681,9 @@ impl Storage {
.optional()
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("Connection config not found: {connection_id}"))?;
- let mut config: ConnectionConfig = serde_json::from_str(&json).map_err(|error| error.to_string())?;
+ let mut config = sanitized_connection_config(
+ &serde_json::from_str::<ConnectionConfig>(&json).map_err(|error| error.to_string())?,
+ );
let mut external_config = config.external_config.take().unwrap_or_else(|| serde_json::json!({}));
let Some(external_object) = external_config.as_object_mut() else {
return Err("MQTT external_config 必须是 JSON 对象".to_string());
@@ -3839,6 +5786,7 @@ impl Storage {
}
};
config.password = self.get_secret(&id, "password").await?.unwrap_or_default();
+ config.url_params = self.get_secret(&id, URL_PARAMS_SECRET_KEY).await?.or(config.url_params);
for index in 0..config.transport_layers.len() {
let layer_for_key = config.transport_layers[index].clone();
match &mut config.transport_layers[index] {
@@ -3898,6 +5846,7 @@ impl Storage {
config.connection_secrets = stored_plugin_secrets;
}
let needs_mq_auth_rewrite = self.hydrate_mq_auth_secrets(&id, &mut config).await?;
+ let needs_mqtt_auth_rewrite = self.hydrate_mqtt_auth_secret(&id, &mut config).await?;
let needs_mq_token_signing_rewrite = self.hydrate_mq_token_signing_secret(&id, &mut config).await?;
let needs_nacos_auth_rewrite = self.hydrate_nacos_auth_secret(&id, &mut config).await?;
let needs_cassandra_tls_rewrite = self.hydrate_cassandra_tls_secrets(&id, &mut config).await?;
@@ -3916,17 +5865,17 @@ impl Storage {
}
}
let needs_external_secret_rewrite = needs_mq_auth_rewrite
+ || needs_mqtt_auth_rewrite
|| needs_mq_token_signing_rewrite
|| needs_nacos_auth_rewrite
|| needs_cassandra_tls_rewrite
|| needs_plugin_secret_rewrite;
if needs_external_secret_rewrite {
- let mut sanitized = config.clone().canonicalized();
- scrub_mq_auth_secrets(&mut sanitized);
- scrub_mq_token_signing_secret(&mut sanitized);
- scrub_nacos_auth_secrets(&mut sanitized);
- scrub_cassandra_tls_secrets(&mut sanitized);
- scrub_plugin_connection_secrets(&mut sanitized);
+ // `config` is hydrated above, so always use the canonical
+ // full scrubber before persisting it again. Otherwise a
+ // plugin-secret rewrite could write the decrypted password,
+ // SSH credentials, or connection string back to config_json.
+ let sanitized = sanitized_connection_config(&config);
let sanitized_json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
let update_id = id.clone();
self.with_conn(move |conn| {
@@ -3973,6 +5922,26 @@ impl Storage {
Ok(needs_rewrite)
}
+ async fn hydrate_mqtt_auth_secret(
+ &self,
+ connection_id: &str,
+ config: &mut ConnectionConfig,
+ ) -> Result<bool, String> {
+ if config.db_type != DatabaseType::Mqtt {
+ return Ok(false);
+ }
+ let Some(auth) = config.external_config.as_mut().and_then(|external| external.get_mut("auth")) else {
+ return Ok(false);
+ };
+ let Some(auth) = auth.as_object_mut() else {
+ return Ok(false);
+ };
+ if auth.get("kind").and_then(serde_json::Value::as_str) != Some("password") {
+ return Ok(false);
+ }
+ hydrate_mq_json_secret(self, connection_id, MQTT_AUTH_PASSWORD_KEY, auth, "password").await
+ }
+
async fn hydrate_mq_token_signing_secret(
&self,
connection_id: &str,
@@ -4416,26 +6385,56 @@ impl Storage {
pub async fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {
let connection_id = connection_id.to_string();
let key = key.to_string();
- self.with_conn(move |conn| {
- conn.query_row(
- "SELECT secret FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
- params![connection_id, key],
- |row| row.get(0),
- )
- .optional()
- .map_err(|e| e.to_string())
- })
- .await
+ let result = self
+ .with_conn({
+ let connection_id = connection_id.clone();
+ let key = key.clone();
+ move |conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![connection_id, key],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .optional()
+ .map_err(|e| e.to_string())
+ }
+ })
+ .await?;
+ let Some((legacy, encrypted)) = result else {
+ return Ok(None);
+ };
+ if let Some(encrypted) = encrypted.filter(|value| !value.is_empty()) {
+ return self.secret_codec(false)?.decrypt(&connection_id, &key, &encrypted).map(Some);
+ }
+ if !legacy.is_empty() {
+ // Read old plaintext rows during migration and opportunistically
+ // rewrite them in the new envelope format.
+ self.set_secret(&connection_id, &key, &legacy).await?;
+ return Ok(Some(legacy));
+ }
+ Ok(None)
}
pub async fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {
let connection_id = connection_id.to_string();
let key = key.to_string();
let secret = secret.to_string();
+ let codec = if secret.is_empty() { None } else { Some(self.secret_codec_for_write(true).await?) };
self.with_conn(move |conn| {
+ if secret.is_empty() {
+ conn.execute(
+ "DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![connection_id, key],
+ ).map_err(|e| e.to_string())?;
+ return Ok(());
+ }
+ let encrypted = codec
+ .as_ref()
+ .ok_or_else(|| "KEY_PROVIDER_UNAVAILABLE".to_string())?
+ .encrypt(&connection_id, &key, &secret)?;
conn.execute(
- "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)",
- params![connection_id, key, secret],
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?, ?, '', ?)",
+ params![connection_id, key, encrypted],
)
.map(|_| ())
.map_err(|e| e.to_string())
@@ -5102,82 +7101,100 @@ impl Storage {
impl Storage {
pub async fn migrate_from_json(&self, data_dir: &Path) -> Result<(), String> {
- self.migrate_connections_json(data_dir).await?;
- self.migrate_secrets_json(data_dir).await?;
- self.migrate_history_json(data_dir).await?;
- self.migrate_ai_config_json(data_dir).await?;
- self.migrate_ai_conversations_json(data_dir).await?;
- self.migrate_sidebar_layout_json(data_dir).await?;
+ self.migrate_from_json_with_finalize(data_dir, true).await
+ }
+
+ async fn migrate_from_json_staged(&self, data_dir: &Path) -> Result<(), String> {
+ self.migrate_from_json_with_finalize(data_dir, false).await
+ }
+
+ async fn migrate_from_json_with_finalize(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
+ self.migrate_connections_json(data_dir, finalize).await?;
+ self.migrate_secrets_json(data_dir, finalize).await?;
+ self.migrate_history_json(data_dir, finalize).await?;
+ self.migrate_ai_config_json(data_dir, finalize).await?;
+ self.migrate_ai_conversations_json(data_dir, finalize).await?;
+ self.migrate_sidebar_layout_json(data_dir, finalize).await?;
Ok(())
}
- async fn migrate_connections_json(&self, data_dir: &Path) -> Result<(), String> {
+ async fn migrate_connections_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
let path = data_dir.join("connections.json");
if tokio::fs::metadata(&path).await.is_err() {
return Ok(());
}
let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
- let configs: Vec<ConnectionConfig> = serde_json::from_str(&json).unwrap_or_default();
- for config in &configs {
- let config_json = serde_json::to_string(config).map_err(|e| e.to_string())?;
- let id = config.id.clone();
- self.with_conn(move |conn| {
- conn.execute(
- "INSERT OR IGNORE INTO connections (id, config_json) VALUES (?1, ?2)",
- params![id, config_json],
- )
- .map(|_| ())
- .map_err(|e| e.to_string())
- })
- .await?;
+ let configs: Vec<ConnectionConfig> = serde_json::from_str(&json)
+ .map_err(|error| format!("Failed to parse legacy connections.json; original file was kept: {error}"))?;
+ // Route legacy hydrated configs through the same sanitized/encrypted
+ // persistence path as normal saves. Inserting the old JSON directly
+ // would briefly reintroduce plaintext credentials into dbx.db.
+ let codec = self.secret_codec_for_write(true).await?;
+ self.with_conn(move |conn| {
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(|e| e.to_string())?;
+ for config in &configs {
+ let exists: bool = tx
+ .query_row("SELECT EXISTS(SELECT 1 FROM connections WHERE id = ?1)", [&config.id], |row| row.get(0))
+ .map_err(|e| e.to_string())?;
+ if !exists {
+ persist_connection_in_tx(&tx, &codec, config)?;
+ }
+ }
+ tx.commit().map_err(|e| e.to_string())
+ })
+ .await?;
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("connections.json.bak")).await.map_err(|e| e.to_string())?;
}
- let _ = tokio::fs::rename(&path, data_dir.join("connections.json.bak")).await;
Ok(())
}
- async fn migrate_secrets_json(&self, data_dir: &Path) -> Result<(), String> {
+ async fn migrate_secrets_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
let path = data_dir.join("secrets.json");
if tokio::fs::metadata(&path).await.is_err() {
return Ok(());
}
let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
- let secrets: HashMap<String, String> = serde_json::from_str(&json).unwrap_or_default();
+ let secrets: HashMap<String, String> = serde_json::from_str(&json)
+ .map_err(|error| format!("Failed to parse legacy secrets.json; original file was kept: {error}"))?;
for (key, secret) in &secrets {
let parts: Vec<&str> = key.splitn(3, ':').collect();
if parts.len() == 3 && parts[0] == "connection" {
let connection_id = parts[1].to_string();
let field = parts[2].to_string();
let secret = secret.clone();
- self.with_conn(move |conn| {
- conn.execute(
- "INSERT OR IGNORE INTO connection_secrets (connection_id, key, secret) VALUES (?1, ?2, ?3)",
- params![connection_id, field, secret],
- )
- .map(|_| ())
- .map_err(|e| e.to_string())
- })
- .await?;
+ // Legacy JSON files contain plaintext values. Route them
+ // through the same encrypted writer used by normal saves;
+ // never copy the old value directly into SQLite.
+ if self.get_secret(&connection_id, &field).await?.is_none() {
+ self.set_secret(&connection_id, &field, &secret).await?;
+ }
}
}
- let _ = tokio::fs::rename(&path, data_dir.join("secrets.json.bak")).await;
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("secrets.json.bak")).await.map_err(|e| e.to_string())?;
+ }
Ok(())
}
- async fn migrate_history_json(&self, data_dir: &Path) -> Result<(), String> {
+ async fn migrate_history_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
let path = data_dir.join("query_history.json");
if tokio::fs::metadata(&path).await.is_err() {
return Ok(());
}
let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
- let entries: Vec<HistoryEntry> = serde_json::from_str(&json).unwrap_or_default();
+ let entries: Vec<HistoryEntry> = serde_json::from_str(&json)
+ .map_err(|error| format!("Failed to parse legacy query_history.json; original file was kept: {error}"))?;
for entry in &entries {
self.save_history_entry(entry).await?;
}
- let _ = tokio::fs::rename(&path, data_dir.join("query_history.json.bak")).await;
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("query_history.json.bak")).await.map_err(|e| e.to_string())?;
+ }
Ok(())
}
- async fn migrate_ai_config_json(&self, data_dir: &Path) -> Result<(), String> {
+ async fn migrate_ai_config_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
let path = data_dir.join("ai_config.json");
if tokio::fs::metadata(&path).await.is_err() {
return Ok(());
@@ -5189,24 +7206,27 @@ impl Storage {
})
.await?;
if count == 0 {
- self.with_conn(move |conn| {
- conn.execute("INSERT OR IGNORE INTO ai_config (id, config_json) VALUES (1, ?1)", [json])
- .map(|_| ())
- .map_err(|e| e.to_string())
- })
- .await?;
+ // Parse and save through the split/secrets path instead of copying
+ // the legacy hydrated JSON into the database.
+ let config = serde_json::from_str::<AiConfig>(&json)
+ .map_err(|error| format!("Failed to parse legacy ai_config.json; original file was kept: {error}"))?;
+ self.save_ai_config(&config).await?;
+ }
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("ai_config.json.bak")).await.map_err(|e| e.to_string())?;
}
- let _ = tokio::fs::rename(&path, data_dir.join("ai_config.json.bak")).await;
Ok(())
}
- async fn migrate_ai_conversations_json(&self, data_dir: &Path) -> Result<(), String> {
+ async fn migrate_ai_conversations_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
let path = data_dir.join("ai_conversations.json");
if tokio::fs::metadata(&path).await.is_err() {
return Ok(());
}
let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
- let conversations: Vec<AiConversation> = serde_json::from_str(&json).unwrap_or_default();
+ let conversations: Vec<AiConversation> = serde_json::from_str(&json).map_err(|error| {
+ format!("Failed to parse legacy ai_conversations.json; original file was kept: {error}")
+ })?;
for conv in &conversations {
let conv = conv.clone();
let messages_json = serde_json::to_string(&conv.messages).map_err(|e| e.to_string())?;
@@ -5231,54 +7251,309 @@ impl Storage {
})
.await?;
}
- let _ = tokio::fs::rename(&path, data_dir.join("ai_conversations.json.bak")).await;
- Ok(())
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("ai_conversations.json.bak")).await.map_err(|e| e.to_string())?;
+ }
+ Ok(())
+ }
+
+ async fn migrate_sidebar_layout_json(&self, data_dir: &Path, finalize: bool) -> Result<(), String> {
+ let path = data_dir.join("sidebar_layout.json");
+ if tokio::fs::metadata(&path).await.is_err() {
+ return Ok(());
+ }
+ let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
+ serde_json::from_str::<serde_json::Value>(&json)
+ .map_err(|error| format!("Failed to parse legacy sidebar_layout.json; original file was kept: {error}"))?;
+ let count: i64 = self
+ .with_conn(|conn| {
+ conn.query_row("SELECT COUNT(*) FROM sidebar_layout", [], |row| row.get(0)).map_err(|e| e.to_string())
+ })
+ .await?;
+ if count == 0 {
+ self.with_conn(move |conn| {
+ conn.execute("INSERT OR IGNORE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ })
+ .await?;
+ }
+ if finalize {
+ tokio::fs::rename(&path, data_dir.join("sidebar_layout.json.bak")).await.map_err(|e| e.to_string())?;
+ }
+ Ok(())
+ }
+}
+
+fn persist_secret_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ connection_id: &str,
+ key: &str,
+ secret: &str,
+) -> Result<(), String> {
+ if secret.is_empty() {
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2", params![connection_id, key])
+ .map_err(|e| e.to_string())?;
+ } else {
+ let encrypted = codec.encrypt(connection_id, key, secret)?;
+ tx.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES (?, ?, '', ?)",
+ params![connection_id, key, encrypted],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
+
+fn apply_sync_connections_in_tx(
+ tx: &Transaction<'_>,
+ codec: &SecretCodec,
+ configs: &[ConnectionConfig],
+) -> Result<(), String> {
+ let replacement_ids = configs.iter().map(|config| config.id.clone()).collect::<HashSet<_>>();
+ let mut retained_ids = preserve_unreadable_connections_for_replacement(tx, &replacement_ids)?;
+ for config in configs {
+ let config = config.canonicalized();
+ if !config.save_password {
+ persist_secret_in_tx(tx, codec, &config.id, "password", "")?;
+ delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
+ }
+ if let Some(url_params) = &config.url_params {
+ if !connection_secret_in_tx_exists(tx, &config.id, URL_PARAMS_SECRET_KEY)? {
+ persist_secret_in_tx(tx, codec, &config.id, URL_PARAMS_SECRET_KEY, url_params)?;
+ }
+ }
+ let sanitized = sanitized_connection_config(&config);
+ let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
+ tx.execute("INSERT INTO connections (id, config_json) VALUES (?1, ?2)", params![config.id, json])
+ .map_err(|e| e.to_string())?;
+ }
+ retained_ids.extend(configs.iter().map(|config| config.id.clone()));
+ delete_unreferenced_connection_secrets_in_tx(tx, &retained_ids)
+}
+
+fn clear_sync_connection_secrets_in_tx(
+ tx: &Transaction<'_>,
+ configs: &[ConnectionConfig],
+ preserve_plugin_secrets: bool,
+) -> Result<(), String> {
+ for config in configs {
+ if preserve_plugin_secrets {
+ tx.execute(
+ "DELETE FROM connection_secrets
+ WHERE connection_id = ?1
+ AND key NOT LIKE 'plugin_connection.%'",
+ [&config.id],
+ )
+ .map_err(|e| e.to_string())?;
+ } else {
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1", [&config.id])
+ .map_err(|e| e.to_string())?;
+ }
+ }
+ Ok(())
+}
+
+fn apply_sync_tunnel_profiles_in_tx(
+ tx: &Transaction<'_>,
+ codec: &SecretCodec,
+ profiles: &[TransportLayerConfig],
+ secret_profiles: Option<&[TransportLayerConfig]>,
+) -> Result<(), String> {
+ let mut existing = HashMap::<String, TransportLayerConfig>::new();
+ let mut statement = tx.prepare("SELECT id, config_json FROM tunnel_profiles").map_err(|e| e.to_string())?;
+ let rows = statement
+ .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
+ .map_err(|e| e.to_string())?;
+ for row in rows {
+ let (id, json) = row.map_err(|e| e.to_string())?;
+ let mut profile: TransportLayerConfig = serde_json::from_str(&json).map_err(|e| e.to_string())?;
+ let namespace = format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{id}");
+ if let Some(blob) = get_secret_in_tx(tx, codec, &namespace, CONFIG_SECRET_BLOB_KEY)? {
+ let stored: TransportLayerConfig = serde_json::from_str(&blob).map_err(|e| e.to_string())?;
+ merge_missing_tunnel_profile_secrets(&mut profile, &stored);
+ }
+ existing.insert(id, profile);
+ }
+ drop(statement);
+
+ let mut full_by_id = HashMap::new();
+ if let Some(secret_profiles) = secret_profiles {
+ for profile in secret_profiles {
+ full_by_id.insert(profile.id().to_string(), profile.clone());
+ }
+ }
+ let mut effective = Vec::with_capacity(profiles.len());
+ for profile in profiles {
+ let (mut profile, has_synced_secrets) = match full_by_id.remove(profile.id()) {
+ Some(profile) => (profile, true),
+ None => (profile.clone(), false),
+ };
+ if !has_synced_secrets {
+ if let Some(previous) = existing.get(profile.id()) {
+ merge_missing_tunnel_profile_secrets(&mut profile, previous);
+ }
+ }
+ effective.push(profile);
+ }
+
+ tx.execute("DELETE FROM tunnel_profiles", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'tunnel_profile.%'", [])
+ .map_err(|e| e.to_string())?;
+ for profile in effective {
+ let mut sanitized = profile.clone();
+ sanitized.scrub_secrets();
+ let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
+ tx.execute("INSERT INTO tunnel_profiles (id, config_json) VALUES (?1, ?2)", params![profile.id(), json])
+ .map_err(|e| e.to_string())?;
+ if sanitized != profile {
+ persist_secret_in_tx(
+ tx,
+ codec,
+ &format!("{TUNNEL_SECRET_NAMESPACE_PREFIX}{}", profile.id()),
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&profile).map_err(|e| e.to_string())?,
+ )?;
+ }
+ }
+ Ok(())
+}
+
+fn apply_ai_configs_in_tx(tx: &Transaction<'_>, codec: &SecretCodec, configs: &[AiConfigItem]) -> Result<(), String> {
+ tx.execute("DELETE FROM ai_configs", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_config", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_provider_configs", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id LIKE 'ai_config.%'", [])
+ .map_err(|e| e.to_string())?;
+ for item in configs {
+ let (sanitized, secrets) = split_ai_config_secrets(&item.config)?;
+ let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
+ let models_json = serde_json::to_string(&sanitized.models).map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT OR REPLACE INTO ai_configs (id, name, model, models, config_json, is_default) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ params![item.id, item.name, sanitized.model, models_json, json, item.is_default as i32],
+ )
+ .map_err(|e| e.to_string())?;
+ if secrets.as_object().is_some_and(|object| !object.is_empty()) {
+ persist_secret_in_tx(
+ tx,
+ codec,
+ &format!("{AI_SECRET_NAMESPACE_PREFIX}{}", item.id),
+ CONFIG_SECRET_BLOB_KEY,
+ &serde_json::to_string(&secrets).map_err(|e| e.to_string())?,
+ )?;
+ }
}
+ Ok(())
+}
- async fn migrate_sidebar_layout_json(&self, data_dir: &Path) -> Result<(), String> {
- let path = data_dir.join("sidebar_layout.json");
- if tokio::fs::metadata(&path).await.is_err() {
- return Ok(());
- }
- let json = tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string())?;
- let count: i64 = self
- .with_conn(|conn| {
- conn.query_row("SELECT COUNT(*) FROM sidebar_layout", [], |row| row.get(0)).map_err(|e| e.to_string())
- })
- .await?;
- if count == 0 {
- self.with_conn(move |conn| {
- conn.execute("INSERT OR IGNORE INTO sidebar_layout (id, layout_json) VALUES (1, ?1)", [json])
- .map(|_| ())
- .map_err(|e| e.to_string())
- })
- .await?;
+fn update_app_settings_key_in_tx(tx: &Transaction<'_>, key: &str, value: serde_json::Value) -> Result<(), String> {
+ let current: Option<String> = tx
+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
+ .optional()
+ .map_err(|e| e.to_string())?;
+ let mut settings = current
+ .map(|json| {
+ serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json).map_err(|e| e.to_string())
+ })
+ .transpose()?
+ .unwrap_or_default();
+ settings.insert(key.to_string(), value);
+ tx.execute(
+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",
+ [serde_json::Value::Object(settings).to_string()],
+ )
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+}
+
+fn apply_desktop_settings_in_tx(tx: &Transaction<'_>, settings: &DesktopSettings) -> Result<(), String> {
+ let mut values = serde_json::Map::new();
+ values.insert("show_tray_icon".to_string(), serde_json::Value::Bool(settings.show_tray_icon));
+ values.insert("icon_theme".to_string(), serde_json::to_value(settings.icon_theme).map_err(|e| e.to_string())?);
+ values.insert("quit_on_close".to_string(), serde_json::Value::Bool(settings.quit_on_close));
+ values.insert("close_action_prompted".to_string(), serde_json::Value::Bool(settings.close_action_prompted));
+ values.insert("debug_logging_enabled".to_string(), serde_json::Value::Bool(settings.debug_logging_enabled));
+ values.insert(
+ "metadata_cache_max_memory_mb".to_string(),
+ serde_json::Value::Number(serde_json::Number::from(normalize_metadata_cache_max_memory_mb(
+ settings.metadata_cache_max_memory_mb,
+ ))),
+ );
+ values.insert(
+ "duckdb_worker_process_isolation".to_string(),
+ serde_json::Value::Bool(settings.duckdb_worker_process_isolation),
+ );
+ values.insert(
+ "duckdb_worker_max_processes".to_string(),
+ serde_json::Value::Number(serde_json::Number::from(normalize_duckdb_worker_max_processes(
+ settings.duckdb_worker_max_processes,
+ ))),
+ );
+ values.insert(
+ "sidebar_table_page_size".to_string(),
+ serde_json::Value::Number(serde_json::Number::from(settings.sidebar_table_page_size)),
+ );
+ let optional_dirs = [
+ ("saved_sql_sync_dir", settings.saved_sql_sync_dir.as_ref()),
+ ("driver_store_dir", settings.driver_store_dir.as_ref()),
+ ("plugin_store_dir", settings.plugin_store_dir.as_ref()),
+ ("agent_store_dir", settings.agent_store_dir.as_ref()),
+ ];
+ for (key, value) in optional_dirs {
+ if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
+ values.insert(key.to_string(), serde_json::Value::String(value.clone()));
+ } else {
+ values.insert(key.to_string(), serde_json::Value::Null);
}
- let _ = tokio::fs::rename(&path, data_dir.join("sidebar_layout.json.bak")).await;
- Ok(())
}
+ let current: Option<String> = tx
+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
+ .optional()
+ .map_err(|e| e.to_string())?;
+ let mut merged = current
+ .map(|json| {
+ serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json).map_err(|e| e.to_string())
+ })
+ .transpose()?
+ .unwrap_or_default();
+ for (key, value) in values {
+ merged.insert(key, value);
+ }
+ tx.execute(
+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",
+ [serde_json::Value::Object(merged).to_string()],
+ )
+ .map(|_| ())
+ .map_err(|e| e.to_string())
}
-fn persist_secret_in_tx(
- tx: &rusqlite::Transaction<'_>,
- connection_id: &str,
- key: &str,
- secret: &str,
-) -> Result<(), String> {
- if secret.is_empty() {
- tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2", params![connection_id, key])
- .map_err(|e| e.to_string())?;
- } else {
+fn apply_saved_sql_in_tx(tx: &Transaction<'_>, library: &SavedSqlLibrary) -> Result<(), String> {
+ tx.execute("DELETE FROM saved_sql_files", []).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM saved_sql_folders", []).map_err(|e| e.to_string())?;
+ for folder in &library.folders {
+ tx.execute(
+ "INSERT INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ params![folder.id, folder.connection_id, folder.parent_folder_id, folder.name, folder.order_index, folder.created_at, folder.updated_at],
+ )
+ .map_err(|e| e.to_string())?;
+ }
+ for file in &library.files {
tx.execute(
- "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret) VALUES (?, ?, ?)",
- params![connection_id, key, secret],
+ "INSERT INTO saved_sql_files (id, connection_id, folder_id, name, database_name, catalog_name, schema_name, sql_text, order_index, open_count, opened_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ params![file.id, file.connection_id, file.folder_id, file.name, file.database, file.catalog, file.schema, file.sql, file.order_index, file.open_count, file.opened_at, file.created_at, file.updated_at],
)
.map_err(|e| e.to_string())?;
}
Ok(())
}
-fn persist_mq_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionConfig) -> Result<(), String> {
+fn persist_mq_auth_secrets_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ config: &ConnectionConfig,
+) -> Result<(), String> {
if config.db_type != DatabaseType::MessageQueue {
delete_secret_prefix_in_tx(tx, &config.id, MQ_AUTH_SECRET_PREFIX)?;
return Ok(());
@@ -5291,13 +7566,13 @@ fn persist_mq_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &Connec
match mq_auth_kind(auth) {
Some("none") => delete_secret_prefix_in_tx(tx, &config.id, MQ_AUTH_SECRET_PREFIX)?,
- Some("token") => replace_mq_auth_secret_in_tx(tx, &config.id, MQ_AUTH_TOKEN_KEY, auth, "token")?,
- Some("basic") => replace_mq_auth_secret_in_tx(tx, &config.id, MQ_AUTH_PASSWORD_KEY, auth, "password")?,
+ Some("token") => replace_mq_auth_secret_in_tx(tx, codec, &config.id, MQ_AUTH_TOKEN_KEY, auth, "token")?,
+ Some("basic") => replace_mq_auth_secret_in_tx(tx, codec, &config.id, MQ_AUTH_PASSWORD_KEY, auth, "password")?,
Some(kind) if is_api_key_auth_kind(kind) => {
- replace_mq_auth_secret_in_tx(tx, &config.id, MQ_AUTH_API_KEY_VALUE_KEY, auth, "value")?
+ replace_mq_auth_secret_in_tx(tx, codec, &config.id, MQ_AUTH_API_KEY_VALUE_KEY, auth, "value")?
}
Some("oauth2") => {
- replace_mq_auth_secret_in_tx(tx, &config.id, MQ_AUTH_CLIENT_SECRET_KEY, auth, "clientSecret")?
+ replace_mq_auth_secret_in_tx(tx, codec, &config.id, MQ_AUTH_CLIENT_SECRET_KEY, auth, "clientSecret")?
}
_ => delete_secret_prefix_in_tx(tx, &config.id, MQ_AUTH_SECRET_PREFIX)?,
}
@@ -5305,37 +7580,83 @@ fn persist_mq_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &Connec
Ok(())
}
+fn persist_mqtt_auth_secrets_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ config: &ConnectionConfig,
+) -> Result<(), String> {
+ if config.db_type != DatabaseType::Mqtt {
+ delete_secret_prefix_in_tx(tx, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ }
+ let Some(auth) = config.external_config.as_ref().and_then(|external| external.get("auth")) else {
+ delete_secret_prefix_in_tx(tx, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ };
+ let Some(auth) = auth.as_object() else {
+ delete_secret_prefix_in_tx(tx, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ };
+ if auth.get("kind").and_then(serde_json::Value::as_str) != Some("password") {
+ delete_secret_prefix_in_tx(tx, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ }
+ let current = auth.get("password").and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty());
+ let existing =
+ if current.is_none() { get_secret_in_tx(tx, codec, &config.id, MQTT_AUTH_PASSWORD_KEY)? } else { None };
+ delete_secret_prefix_in_tx(tx, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
+ if let Some(secret) = current.or(existing.as_deref()) {
+ persist_secret_in_tx(tx, codec, &config.id, MQTT_AUTH_PASSWORD_KEY, secret)?;
+ }
+ Ok(())
+}
+
fn replace_mq_auth_secret_in_tx(
tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
connection_id: &str,
key: &str,
auth: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> Result<(), String> {
let current = auth.get(field).and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty());
- let existing = if current.is_none() { get_secret_in_tx(tx, connection_id, key)? } else { None };
+ let existing = if current.is_none() { get_secret_in_tx(tx, codec, connection_id, key)? } else { None };
delete_secret_prefix_in_tx(tx, connection_id, MQ_AUTH_SECRET_PREFIX)?;
match current {
- Some(secret) => persist_secret_in_tx(tx, connection_id, key, secret),
+ Some(secret) => persist_secret_in_tx(tx, codec, connection_id, key, secret),
None => match existing {
- Some(secret) => persist_secret_in_tx(tx, connection_id, key, &secret),
+ Some(secret) => persist_secret_in_tx(tx, codec, connection_id, key, &secret),
None => Ok(()),
},
}
}
-fn get_secret_in_tx(tx: &rusqlite::Transaction<'_>, connection_id: &str, key: &str) -> Result<Option<String>, String> {
- tx.query_row(
- "SELECT secret FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
- params![connection_id, key],
- |row| row.get(0),
- )
- .optional()
- .map_err(|e| e.to_string())
+fn get_secret_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ connection_id: &str,
+ key: &str,
+) -> Result<Option<String>, String> {
+ let row = tx
+ .query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = ?1 AND key = ?2",
+ params![connection_id, key],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .optional()
+ .map_err(|e| e.to_string())?;
+ let Some((legacy, encrypted)) = row else {
+ return Ok(None);
+ };
+ if let Some(encrypted) = encrypted.filter(|value| !value.is_empty()) {
+ return codec.decrypt(connection_id, key, &encrypted).map(Some);
+ }
+ Ok((!legacy.is_empty()).then_some(legacy))
}
fn persist_mq_token_signing_secret_in_tx(
tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
config: &ConnectionConfig,
) -> Result<(), String> {
if config.db_type != DatabaseType::MessageQueue {
@@ -5348,10 +7669,14 @@ fn persist_mq_token_signing_secret_in_tx(
return Ok(());
};
- persist_json_secret_if_present_in_tx(tx, &config.id, MQ_TOKEN_SIGNING_KEY, signing, "key")
+ persist_json_secret_if_present_in_tx(tx, codec, &config.id, MQ_TOKEN_SIGNING_KEY, signing, "key")
}
-fn persist_nacos_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &ConnectionConfig) -> Result<(), String> {
+fn persist_nacos_auth_secrets_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ config: &ConnectionConfig,
+) -> Result<(), String> {
if config.db_type != DatabaseType::Nacos || !config.save_password {
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
return Ok(());
@@ -5368,21 +7693,21 @@ fn persist_nacos_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &Con
.and_then(|auth| auth.get("password").and_then(serde_json::Value::as_str))
.filter(|secret| !secret.is_empty());
let existing_primary = if primary.is_none() && primary_auth.is_some() {
- get_secret_in_tx(tx, &config.id, NACOS_AUTH_PASSWORD_KEY)?
+ get_secret_in_tx(tx, codec, &config.id, NACOS_AUTH_PASSWORD_KEY)?
} else {
None
};
let existing_console = if console.is_none() && console_auth.is_some() {
- get_secret_in_tx(tx, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY)?
+ get_secret_in_tx(tx, codec, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY)?
} else {
None
};
delete_secret_prefix_in_tx(tx, &config.id, NACOS_AUTH_SECRET_PREFIX)?;
if let Some(secret) = primary.or(existing_primary.as_deref()) {
- persist_secret_in_tx(tx, &config.id, NACOS_AUTH_PASSWORD_KEY, secret)?;
+ persist_secret_in_tx(tx, codec, &config.id, NACOS_AUTH_PASSWORD_KEY, secret)?;
}
if let Some(secret) = console.or(existing_console.as_deref()) {
- persist_secret_in_tx(tx, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, secret)?;
+ persist_secret_in_tx(tx, codec, &config.id, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, secret)?;
}
Ok(())
@@ -5390,6 +7715,7 @@ fn persist_nacos_auth_secrets_in_tx(tx: &rusqlite::Transaction<'_>, config: &Con
fn persist_cassandra_tls_secrets_in_tx(
tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
config: &ConnectionConfig,
) -> Result<(), String> {
if config.db_type != DatabaseType::Cassandra {
@@ -5402,12 +7728,14 @@ fn persist_cassandra_tls_secrets_in_tx(
};
persist_secret_in_tx(
tx,
+ codec,
&config.id,
CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
tls.get("truststore_password").and_then(serde_json::Value::as_str).unwrap_or(""),
)?;
persist_secret_in_tx(
tx,
+ codec,
&config.id,
CASSANDRA_KEYSTORE_PASSWORD_KEY,
tls.get("keystore_password").and_then(serde_json::Value::as_str).unwrap_or(""),
@@ -5416,13 +7744,14 @@ fn persist_cassandra_tls_secrets_in_tx(
fn persist_json_secret_if_present_in_tx(
tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
connection_id: &str,
key: &str,
auth: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> Result<(), String> {
if let Some(secret) = auth.get(field).and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty()) {
- persist_secret_in_tx(tx, connection_id, key, secret)?;
+ persist_secret_in_tx(tx, codec, connection_id, key, secret)?;
}
Ok(())
}
@@ -5536,7 +7865,7 @@ fn map_from_sql_err(err: serde_json::Error) -> rusqlite::Error {
mod tests {
use super::{
maybe_import_user_data_db, DataDbImportResult, DesktopIconTheme, DesktopSettings, McpGlobalPolicy,
- McpGlobalPolicyState, Storage, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION, MCP_GLOBAL_POLICY_KEY,
+ McpGlobalPolicyState, Storage, SyncImportPlan, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION, MCP_GLOBAL_POLICY_KEY,
};
use crate::ai::{
AiActiveModelSelection, AiAssistantMode, AiChatMessage, AiChatSelectionState, AiConversation,
@@ -5545,23 +7874,350 @@ mod tests {
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
use crate::connection_secrets::{
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
- MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
+ MQTT_AUTH_PASSWORD_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
PLUGIN_CONNECTION_SECRET_PREFIX,
};
use crate::history::{HistoryConnectionFilter, HistoryDatabaseFilter, HistoryEntry, HistorySearchRequest};
use crate::models::connection::{
- ConnectionConfig, DatabaseConnectionInfo, DatabaseType, SshTunnelConfig, TransportLayerConfig,
+ ConnectionConfig, DatabaseConnectionInfo, DatabaseType, HttpTunnelConfig, SshTunnelConfig, TransportLayerConfig,
};
- use crate::saved_sql::SavedSqlFile;
+ use crate::persistence::secret_codec::{managed_key_path, SecretKeyPolicy};
+ use crate::saved_sql::{SavedSqlFile, SavedSqlFolder, SavedSqlLibrary};
use rusqlite::{Connection, TransactionBehavior};
use std::collections::BTreeMap;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+ #[tokio::test]
+ async fn migration_scan_cache_recovers_legacy_success_with_stale_counts() {
+ let dir = temp_data_dir("migration-stale-cache");
+ std::fs::create_dir_all(&dir).unwrap();
+ let storage = Storage::open_unmigrated(&dir.join("dbx.db")).await.unwrap();
+ storage.set_migration_state(super::MigrationState::Succeeded, None, None, None, None).await.unwrap();
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "UPDATE data_migrations SET counts_json=?1",
+ [r#"{"cachedScan":[75,0,65,15,2,0,5],"backupPaths":[]}"#],
+ )
+ .unwrap();
+ Ok(())
+ })
+ .await
+ .unwrap();
+ let status = storage.inspect_data_migration().await.unwrap();
+ assert_eq!(status.state, super::MigrationState::Succeeded);
+ assert!(!status.needs_migration);
+ assert_eq!(status.database_plaintext_count, 0);
+ let again = storage.inspect_data_migration().await.unwrap();
+ assert!(!again.needs_migration);
+ assert_eq!(again.database_plaintext_count, 0);
+ }
+
+ #[tokio::test]
+ async fn migration_preflight_is_read_only() {
+ let dir = temp_data_dir("migration-cache-transition");
+ std::fs::create_dir_all(&dir).unwrap();
+ let storage = Storage::open_unmigrated(&dir.join("dbx.db")).await.unwrap();
+ storage.inspect_data_migration().await.unwrap();
+ let before = storage.load_migration_state().await.unwrap();
+ assert_eq!(before.state, super::MigrationState::Pending);
+ let before: serde_json::Value = serde_json::from_str(&before.counts_json).unwrap();
+ assert!(before.get("cachedScanFingerprint").is_none());
+ assert!(before.get("cachedScan").is_none());
+ let rows = storage
+ .with_conn(|conn| {
+ conn.query_row("SELECT COUNT(*) FROM data_migrations", [], |row| row.get::<_, i64>(0))
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert_eq!(rows, 0);
+ storage.set_migration_state(super::MigrationState::Succeeded, None, None, None, None).await.unwrap();
+ let after = storage.load_migration_state().await.unwrap();
+ let after: serde_json::Value = serde_json::from_str(&after.counts_json).unwrap();
+ assert!(after.get("cachedScan").is_none());
+ assert!(after.get("cachedScanFingerprint").is_none());
+ assert!(!storage.inspect_data_migration().await.unwrap().needs_migration);
+ }
+
fn temp_db_path(name: &str) -> std::path::PathBuf {
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
std::env::temp_dir().join(format!("dbx-storage-{name}-{}-{stamp}.db", std::process::id()))
}
+ #[tokio::test]
+ async fn managed_data_dir_key_is_created_only_when_plaintext_migration_starts() {
+ let dir = tempfile::tempdir().unwrap();
+ let database_path = dir.path().join("dbx.db");
+ let storage = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "INSERT INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES ('legacy', 'password', 'old-secret', NULL)",
+ [],
+ )
+ .map_err(|error| error.to_string())?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+
+ let key_path = managed_key_path(dir.path());
+ let status = storage.inspect_data_migration().await.unwrap();
+ assert!(status.needs_migration);
+ assert!(status.key_creation_allowed);
+ assert_eq!(status.error_code.as_deref(), Some("MISSING_MANAGED_KEY"));
+ assert!(!key_path.exists());
+
+ storage.start_data_migration().await.unwrap();
+ assert!(key_path.is_file());
+ let row = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'legacy' AND key = 'password'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(row.0.is_empty());
+ assert!(row.1.starts_with("dbxenc1."));
+
+ drop(storage);
+ let reopened = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ assert_eq!(reopened.get_secret("legacy", "password").await.unwrap().as_deref(), Some("old-secret"));
+ }
+
+ #[tokio::test]
+ async fn secret_migration_write_failure_rolls_back_all_rows() {
+ let directory = tempfile::tempdir().unwrap();
+ let storage = Storage::open_unmigrated(&directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage
+ .with_conn(|conn| {
+ conn.execute_batch(
+ "INSERT INTO connection_secrets (connection_id, key, secret) VALUES
+ ('first', 'password', 'first-secret'), ('second', 'password', 'second-secret');
+ CREATE TRIGGER reject_second_encryption BEFORE UPDATE ON connection_secrets
+ WHEN (SELECT COUNT(*) FROM connection_secrets WHERE secret_enc IS NOT NULL) > 0
+ BEGIN SELECT RAISE(ABORT, 'injected write failure'); END;",
+ )
+ .map_err(|error| error.to_string())?;
+ let codec = super::SecretCodec::new([7u8; 32]);
+ let error = super::migrate_legacy_connection_secrets_sync(conn, &codec).unwrap_err();
+ assert!(error.contains("injected write failure"));
+ let unchanged: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM connection_secrets WHERE secret <> '' AND secret_enc IS NULL",
+ [],
+ |row| row.get(0),
+ )
+ .map_err(|error| error.to_string())?;
+ assert_eq!(unchanged, 2);
+ Ok(())
+ })
+ .await
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn secret_migration_late_failure_restores_backup_and_retries_after_reopen() {
+ let directory = tempfile::tempdir().unwrap();
+ let database_path = directory.path().join("dbx.db");
+ let storage = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "INSERT INTO connection_secrets (connection_id, key, secret) VALUES ('legacy', 'password', 'old-secret')",
+ [],
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ let legacy_path = directory.path().join("connections.json");
+ std::fs::write(&legacy_path, "invalid json").unwrap();
+ assert!(storage.start_data_migration().await.unwrap_err().contains("connections.json"));
+ assert_eq!(std::fs::read_to_string(&legacy_path).unwrap(), "invalid json");
+ assert!(!directory.path().join("connections.json.bak").exists());
+ let record = storage.load_migration_state().await.unwrap();
+ assert_eq!(record.state, super::MigrationState::Failed);
+ assert!(std::path::Path::new(record.backup_path.as_ref().unwrap()).join("dbx.db").is_file());
+ storage
+ .with_conn(|conn| {
+ let row: (String, Option<String>) = conn
+ .query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'legacy'",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .map_err(|error| error.to_string())?;
+ assert_eq!(row, ("old-secret".to_string(), None));
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert!(storage.cleanup_migration_backups().await.is_err());
+ drop(storage);
+
+ std::fs::write(&legacy_path, "[]").unwrap();
+ let reopened = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ reopened.retry_data_migration().await.unwrap();
+ assert_eq!(reopened.get_secret("legacy", "password").await.unwrap().as_deref(), Some("old-secret"));
+ assert!(!legacy_path.exists());
+ assert!(directory.path().join("connections.json.bak").exists());
+ assert!(reopened.inspect_data_migration().await.unwrap().is_ready());
+ }
+
+ #[tokio::test]
+ async fn secret_migration_running_state_resumes_after_reopen() {
+ let directory = tempfile::tempdir().unwrap();
+ let database_path = directory.path().join("dbx.db");
+ let storage = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage.set_secret("legacy", "password", "secret").await.unwrap();
+ let backup = storage.create_migration_backup().await.unwrap();
+ storage.set_migration_state(super::MigrationState::Running, Some(&backup), None, None, None).await.unwrap();
+ drop(storage);
+ let reopened = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let status = reopened.inspect_data_migration().await.unwrap();
+ assert_eq!(status.state, super::MigrationState::Running);
+ assert!(!status.is_ready());
+ reopened.retry_data_migration().await.unwrap();
+ assert!(reopened.inspect_data_migration().await.unwrap().is_ready());
+ assert_eq!(reopened.get_secret("legacy", "password").await.unwrap().as_deref(), Some("secret"));
+ }
+
+ #[tokio::test]
+ async fn secret_migration_rejects_wrong_or_invalid_managed_keys_without_replacing_them() {
+ let directory = tempfile::tempdir().unwrap();
+ let storage = Storage::open_unmigrated(&directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage.set_secret("connection", "password", "secret").await.unwrap();
+ let key_path = managed_key_path(directory.path());
+ let original = std::fs::read(&key_path).unwrap();
+ for (material, expected) in [("00".repeat(32), "SECRET_KEY_MISMATCH"), ("\n".to_string(), "SECRET_KEY_INVALID")]
+ {
+ std::fs::write(&key_path, &material).unwrap();
+ let status = storage.inspect_data_migration().await.unwrap();
+ assert!(!status.is_ready());
+ assert!(!status.key_creation_allowed);
+ assert_eq!(status.error_code.as_deref(), Some(expected));
+ assert!(storage.get_secret("connection", "password").await.is_err());
+ assert_eq!(storage.start_data_migration().await.unwrap_err(), expected);
+ assert_eq!(std::fs::read_to_string(&key_path).unwrap(), material);
+ }
+ std::fs::write(&key_path, original).unwrap();
+ assert_eq!(storage.get_secret("connection", "password").await.unwrap().as_deref(), Some("secret"));
+ }
+
+ #[tokio::test]
+ async fn missing_managed_key_for_existing_ciphertext_never_creates_a_replacement() {
+ let dir = tempfile::tempdir().unwrap();
+ let database_path = dir.path().join("dbx.db");
+ let storage = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage.set_secret("connection", "password", "secret").await.unwrap();
+ let key_path = managed_key_path(dir.path());
+ std::fs::remove_file(&key_path).unwrap();
+
+ let status = storage.inspect_data_migration().await.unwrap();
+ assert!(status.needs_migration);
+ assert!(!status.key_creation_allowed);
+ assert_eq!(status.error_code.as_deref(), Some("ENCRYPTED_DATA_KEY_MISSING"));
+ assert!(!key_path.exists());
+ assert_eq!(storage.start_data_migration().await.unwrap_err(), "ENCRYPTED_DATA_KEY_MISSING");
+ assert!(!key_path.exists());
+ }
+
+ #[tokio::test]
+ async fn secret_write_after_managed_key_loss_never_creates_a_replacement() {
+ let directory = tempfile::tempdir().unwrap();
+ let storage = Storage::open_unmigrated(&directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage.set_secret("existing", "password", "original-secret").await.unwrap();
+ let key_path = managed_key_path(directory.path());
+ let original_key = std::fs::read(&key_path).unwrap();
+ std::fs::remove_file(&key_path).unwrap();
+
+ assert_eq!(
+ storage.set_secret("new", "password", "new-secret").await.unwrap_err(),
+ "ENCRYPTED_DATA_KEY_MISSING"
+ );
+ assert!(!key_path.exists());
+ assert_eq!(storage.get_secret("new", "password").await.unwrap(), None);
+
+ std::fs::write(&key_path, original_key).unwrap();
+ assert_eq!(storage.get_secret("existing", "password").await.unwrap().as_deref(), Some("original-secret"));
+ storage.set_secret("new", "password", "new-secret").await.unwrap();
+ assert_eq!(storage.get_secret("new", "password").await.unwrap().as_deref(), Some("new-secret"));
+ }
+
+ #[tokio::test]
+ async fn connection_write_after_managed_key_loss_preserves_existing_ciphertext() {
+ let directory = tempfile::tempdir().unwrap();
+ let storage = Storage::open_unmigrated(&directory.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ let original = plain_connection("existing", "original-secret");
+ storage.save_connections(std::slice::from_ref(&original)).await.unwrap();
+ let key_path = managed_key_path(directory.path());
+ let original_key = std::fs::read(&key_path).unwrap();
+ std::fs::remove_file(&key_path).unwrap();
+
+ let replacement = plain_connection("replacement", "new-secret");
+ assert_eq!(storage.save_connections(&[replacement]).await.unwrap_err(), "ENCRYPTED_DATA_KEY_MISSING");
+ assert!(!key_path.exists());
+
+ std::fs::write(&key_path, original_key).unwrap();
+ let loaded = storage.load_connections().await.unwrap();
+ assert_eq!(loaded.len(), 1);
+ assert_eq!(loaded[0].id, original.id);
+ assert_eq!(loaded[0].password, "original-secret");
+ }
+
+ #[tokio::test]
+ async fn disabled_secret_key_creation_does_not_provision_on_write() {
+ let dir = tempfile::tempdir().unwrap();
+ let database_path = dir.path().join("dbx.db");
+ let storage = Storage::open_unmigrated(&database_path)
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir)
+ .with_secret_key_creation(false);
+
+ assert_eq!(storage.set_secret("connection", "password", "secret").await.unwrap_err(), "MISSING_MANAGED_KEY");
+ assert!(!managed_key_path(dir.path()).exists());
+ }
+
/// Data directory with an explicit mode. The process temp directory is
/// group-writable on Linux (`/tmp` is 1777), which would otherwise be read
/// as the shared-directory sharing model.
@@ -6367,6 +9023,46 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ #[tokio::test]
+ async fn tunnel_profile_secret_fields_are_not_written_to_config_json() {
+ let path = temp_db_path("tunnel-secret-at-rest");
+ let storage = Storage::open(&path).await.unwrap();
+ let profile = TransportLayerConfig::HttpTunnel(HttpTunnelConfig {
+ id: "http-secret".to_string(),
+ name: "HTTP".to_string(),
+ enabled: true,
+ url: "https://bastion.example.com".to_string(),
+ token: "tunnel-token".to_string(),
+ connect_timeout_secs: 5,
+ profile_id: String::new(),
+ });
+ storage.save_tunnel_profiles(std::slice::from_ref(&profile)).await.unwrap();
+ let raw = storage
+ .with_conn(|conn| {
+ conn.query_row("SELECT config_json FROM tunnel_profiles WHERE id = 'http-secret'", [], |row| {
+ row.get::<_, String>(0)
+ })
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(!raw.contains("tunnel-token"));
+ let encrypted = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret_enc FROM connection_secrets WHERE connection_id = 'tunnel_profile.http-secret' AND key = 'config'",
+ [],
+ |row| row.get::<_, Option<String>>(0),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(encrypted.is_some_and(|value| value.starts_with("dbxenc1.")));
+ assert_eq!(storage.load_tunnel_profiles().await.unwrap(), vec![profile]);
+ let _ = std::fs::remove_file(path);
+ }
+
#[tokio::test]
async fn tunnel_profiles_reject_empty_ids() {
let path = temp_db_path("tunnel-profiles-empty-id");
@@ -6503,6 +9199,31 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ #[tokio::test]
+ async fn plugin_secret_reads_require_a_key_only_for_ciphertext() {
+ let dir = tempfile::tempdir().unwrap();
+ let storage = Storage::open_unmigrated(&dir.path().join("dbx.db"))
+ .await
+ .unwrap()
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ assert!(storage.secret_codec(false).is_err());
+ assert!(super::load_plugin_connection_secrets(&storage, "conn").await.unwrap().is_empty());
+ let codec = super::SecretCodec::new([7; 32]);
+ let key = format!("{PLUGIN_CONNECTION_SECRET_PREFIX}token");
+ let encrypted = codec.encrypt("conn", &key, "secret").unwrap();
+ storage
+ .with_conn(move |conn| {
+ conn.execute(
+ "INSERT INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES ('conn', ?1, '', ?2)",
+ rusqlite::params![key, encrypted],
+ ).map_err(|error| error.to_string())?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert!(super::load_plugin_connection_secrets(&storage, "conn").await.is_err());
+ }
+
#[tokio::test]
async fn save_connections_moves_plugin_secrets_to_secret_table_and_clears_removed_values() {
let path = temp_db_path("plugin-secrets");
@@ -8594,6 +11315,72 @@ mod tests {
std::fs::remove_file(&db).ok();
}
+ #[tokio::test]
+ async fn legacy_ai_and_tunnel_inline_secrets_are_migrated_on_reopen() {
+ let db = temp_db_path("legacy-config-secret-migration");
+ let storage = Storage::open(&db).await.unwrap();
+
+ let mut ai = make_ai_config("legacy", true);
+ storage.save_ai_config_item(&ai).await.unwrap();
+ ai.config.api_key = "legacy-ai-key".to_string();
+ let ai_json = serde_json::to_string(&ai.config).unwrap();
+ let tunnel = ssh_profile("legacy-tunnel", "legacy-tunnel-password");
+ storage.save_tunnel_profiles(std::slice::from_ref(&tunnel)).await.unwrap();
+ let tunnel_json = serde_json::to_string(&tunnel).unwrap();
+ storage
+ .with_conn(move |conn| {
+ conn.execute("UPDATE ai_configs SET config_json = ?1 WHERE id = 'cfg-legacy'", [&ai_json])
+ .map_err(|error| error.to_string())?;
+ conn.execute("DELETE FROM connection_secrets WHERE connection_id = 'ai_config.cfg-legacy'", [])
+ .map_err(|error| error.to_string())?;
+ conn.execute("UPDATE tunnel_profiles SET config_json = ?1 WHERE id = 'legacy-tunnel'", [&tunnel_json])
+ .map_err(|error| error.to_string())?;
+ conn.execute("DELETE FROM connection_secrets WHERE connection_id = 'tunnel_profile.legacy-tunnel'", [])
+ .map_err(|error| error.to_string())?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ drop(storage);
+
+ let reopened = Storage::open(&db).await.unwrap();
+ let raw_ai = reopened
+ .with_conn(|conn| {
+ conn.query_row("SELECT config_json FROM ai_configs WHERE id = 'cfg-legacy'", [], |row| {
+ row.get::<_, String>(0)
+ })
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ let raw_tunnel = reopened
+ .with_conn(|conn| {
+ conn.query_row("SELECT config_json FROM tunnel_profiles WHERE id = 'legacy-tunnel'", [], |row| {
+ row.get::<_, String>(0)
+ })
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(!raw_ai.contains("legacy-ai-key"));
+ assert!(!raw_tunnel.contains("legacy-tunnel-password"));
+ assert_eq!(reopened.load_ai_configs().await.unwrap()[0].config.api_key, "legacy-ai-key");
+ assert_eq!(reopened.load_tunnel_profiles().await.unwrap(), vec![tunnel]);
+ let encrypted = reopened
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT COUNT(*) FROM connection_secrets WHERE secret_enc LIKE 'dbxenc1.%' AND secret = ''",
+ [],
+ |row| row.get::<_, i64>(0),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(encrypted >= 2);
+ std::fs::remove_file(&db).ok();
+ }
+
#[tokio::test]
async fn opencode_cli_ai_config_roundtrip() {
let db = temp_db_path("opencode-cli-ai-roundtrip");
@@ -8867,6 +11654,38 @@ mod tests {
std::fs::remove_file(&db).ok();
}
+ #[tokio::test]
+ async fn ai_config_secret_fields_are_not_written_to_config_json() {
+ let db = temp_db_path("ai-secret-at-rest");
+ let storage = Storage::open(&db).await.unwrap();
+ let config = make_ai_config("secret-config", true);
+ storage.save_ai_configs(std::slice::from_ref(&config)).await.unwrap();
+ let raw = storage
+ .with_conn(|conn| {
+ conn.query_row("SELECT config_json FROM ai_configs WHERE id = 'cfg-secret-config'", [], |row| {
+ row.get::<_, String>(0)
+ })
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(!raw.contains("sk-test"));
+ let encrypted = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret_enc FROM connection_secrets WHERE connection_id = 'ai_config.cfg-secret-config' AND key = 'config'",
+ [],
+ |row| row.get::<_, Option<String>>(0),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(encrypted.is_some_and(|value| value.starts_with("dbxenc1.")));
+ assert_eq!(storage.load_ai_configs().await.unwrap()[0].config.api_key, "sk-test");
+ std::fs::remove_file(&db).ok();
+ }
+
#[tokio::test]
async fn ai_config_save_configs_clears_old_tables() {
let db = temp_db_path("ai-clear-old");
@@ -9192,4 +12011,346 @@ mod tests {
std::fs::remove_file(&db).ok();
}
+
+ #[tokio::test]
+ async fn connection_secrets_are_encrypted_at_rest_and_legacy_rows_migrate() {
+ let db = temp_db_path("secret-store-at-rest");
+ let storage = Storage::open(&db).await.unwrap();
+ let mut url_config = plain_connection("url-params", "url-password");
+ url_config.url_params = Some("applicationName=dbx&PASSWORD=url-password&sslmode=require".to_string());
+ storage.save_connections(std::slice::from_ref(&url_config)).await.unwrap();
+ let raw_url_config = raw_connection_json(&storage, "url-params").await;
+ assert!(!raw_url_config.contains("url-password"));
+ assert_eq!(
+ storage.load_connections().await.unwrap()[0].url_params.as_deref(),
+ Some("applicationName=dbx&PASSWORD=url-password&sslmode=require")
+ );
+ let url_secret = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'url-params' AND key = 'url_params'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(url_secret.0.is_empty());
+ assert!(url_secret.1.as_deref().is_some_and(|value| value.starts_with("dbxenc1.")));
+ storage.set_secret("connection-1", "password", "super-secret").await.unwrap();
+ assert_eq!(storage.get_secret("connection-1", "password").await.unwrap().as_deref(), Some("super-secret"));
+ let row = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'connection-1' AND key = 'password'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(row.0.is_empty());
+ assert!(row.1.as_deref().is_some_and(|value| value.starts_with("dbxenc1.")));
+
+ // An old plaintext row remains readable and is rewritten on access.
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES ('legacy', 'password', 'old-secret', NULL)",
+ [],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert_eq!(storage.get_secret("legacy", "password").await.unwrap().as_deref(), Some("old-secret"));
+ let migrated = storage
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'legacy' AND key = 'password'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(migrated.0.is_empty());
+ assert!(migrated.1.as_deref().is_some_and(|value| value.starts_with("dbxenc1.")));
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn legacy_connection_config_migration_keeps_externalized_password() {
+ // Regression: re-saving a legacy inline config wrote the config's empty
+ // `password` field straight back into `connection_secrets`, which the
+ // persistence path turns into a DELETE. A connection whose password
+ // already lived in the secret store therefore lost it on upgrade.
+ let id = "legacy-inline-url-params";
+ let db = temp_db_path("legacy-connection-config-keeps-password");
+ let storage = Storage::open(&db).await.unwrap();
+ let mut config = plain_connection(id, "saved-password");
+ config.url_params = Some("authSource=dbx_test".to_string());
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ // Restore the shape an older release persisted: `url_params` is still
+ // inline in config_json while the password only exists as a secret.
+ let mut inline = config.clone();
+ inline.password = String::new();
+ let inline_json = serde_json::to_string(&inline).unwrap();
+ storage
+ .with_conn(move |conn| {
+ conn.execute(
+ "UPDATE connections SET config_json = ?1 WHERE id = ?2",
+ rusqlite::params![inline_json, id],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ drop(storage);
+
+ let reopened = Storage::open(&db).await.unwrap();
+ let raw = raw_connection_json(&reopened, id).await;
+ assert!(!raw.contains("authSource=dbx_test"));
+ assert_eq!(reopened.get_secret(id, "password").await.unwrap().as_deref(), Some("saved-password"));
+ let loaded = reopened.load_connections().await.unwrap();
+ assert_eq!(loaded.len(), 1);
+ assert_eq!(loaded[0].password, "saved-password");
+ assert_eq!(loaded[0].url_params.as_deref(), Some("authSource=dbx_test"));
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn legacy_connection_config_migration_still_drops_password_when_not_saved() {
+ let id = "legacy-inline-url-params-unsaved";
+ let db = temp_db_path("legacy-connection-config-drops-unsaved-password");
+ let storage = Storage::open(&db).await.unwrap();
+ let mut config = plain_connection(id, "saved-password");
+ config.url_params = Some("authSource=dbx_test".to_string());
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let mut inline = config.clone();
+ inline.password = String::new();
+ inline.save_password = false;
+ let inline_json = serde_json::to_string(&inline).unwrap();
+ storage
+ .with_conn(move |conn| {
+ conn.execute(
+ "UPDATE connections SET config_json = ?1 WHERE id = ?2",
+ rusqlite::params![inline_json, id],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ drop(storage);
+
+ // "Don't save password" must keep winning: the restore path must not
+ // resurrect a credential this connection is configured not to keep.
+ let reopened = Storage::open(&db).await.unwrap();
+ assert!(reopened.get_secret(id, "password").await.unwrap().is_none());
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn mqtt_password_is_encrypted_at_rest_and_hydrated_on_load() {
+ let path = temp_db_path("mqtt-password-secret");
+ let storage = Storage::open(&path).await.unwrap();
+ let mut config = plain_connection("mqtt-password", "");
+ config.db_type = DatabaseType::Mqtt;
+ config.external_config = Some(serde_json::json!({
+ "auth": { "kind": "password", "username": "mqtt-user", "password": "mqtt-secret" }
+ }));
+ storage.save_connections(std::slice::from_ref(&config)).await.unwrap();
+
+ let raw = raw_connection_json(&storage, "mqtt-password").await;
+ assert!(!raw.contains("mqtt-secret"));
+ assert!(storage
+ .get_secret("mqtt-password", MQTT_AUTH_PASSWORD_KEY)
+ .await
+ .unwrap()
+ .is_some_and(|secret| secret == "mqtt-secret"));
+ assert_eq!(storage.load_connections().await.unwrap()[0], config);
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn legacy_plaintext_secrets_are_migrated_during_reopen() {
+ let db = temp_db_path("secret-store-startup-migration");
+ let storage = Storage::open(&db).await.unwrap();
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret, secret_enc) VALUES ('legacy-startup', 'password', 'old-secret', NULL)",
+ [],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ drop(storage);
+
+ let reopened = Storage::open(&db).await.unwrap();
+ let row = reopened
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'legacy-startup' AND key = 'password'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(row.0.is_empty());
+ assert!(row.1.as_deref().is_some_and(|value| value.starts_with("dbxenc1.")));
+
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn legacy_sync_credentials_are_migrated_from_app_settings_on_reopen() {
+ let db = temp_db_path("legacy-app-settings-secrets");
+ let storage = Storage::open(&db).await.unwrap();
+ storage
+ .with_conn(|conn| {
+ conn.execute(
+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",
+ [serde_json::json!({
+ "local_device_secret": "legacy-device-secret",
+ "webdav_sync_secrets_passphrase": "legacy-sync-passphrase",
+ "webdav_passwords": {"webdav:https://example.test": {"ciphertext": "legacy-blob"}}
+ })
+ .to_string()],
+ )
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ drop(storage);
+
+ let reopened = Storage::open(&db).await.unwrap();
+ let settings = reopened.load_app_settings_json().await.unwrap();
+ assert!(!settings.contains_key("local_device_secret"));
+ assert!(!settings.contains_key("webdav_sync_secrets_passphrase"));
+ assert!(!settings.contains_key("webdav_passwords"));
+ assert_eq!(
+ reopened.get_secret(super::GLOBAL_SECRET_NAMESPACE, "local_device_secret").await.unwrap().as_deref(),
+ Some("legacy-device-secret")
+ );
+ assert_eq!(
+ reopened
+ .get_secret(super::GLOBAL_SECRET_NAMESPACE, "webdav_sync_secrets_passphrase")
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("legacy-sync-passphrase")
+ );
+ assert_eq!(
+ reopened
+ .get_secret(super::GLOBAL_SECRET_NAMESPACE, "webdav_password.webdav:https://example.test")
+ .await
+ .unwrap()
+ .as_deref(),
+ Some(r#"{"ciphertext":"legacy-blob"}"#)
+ );
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn legacy_inline_connection_secrets_are_migrated_during_reopen() {
+ let db = temp_db_path("inline-secret-startup-migration");
+ let storage = Storage::open(&db).await.unwrap();
+ insert_raw_connection(&storage, &plain_connection("legacy-inline", "old-inline-secret")).await;
+ drop(storage);
+
+ let reopened = Storage::open(&db).await.unwrap();
+ let raw = raw_connection_json(&reopened, "legacy-inline").await;
+ assert!(!raw.contains("old-inline-secret"));
+ assert_eq!(reopened.load_connections().await.unwrap()[0].password, "old-inline-secret");
+ let row = reopened
+ .with_conn(|conn| {
+ conn.query_row(
+ "SELECT secret, secret_enc FROM connection_secrets WHERE connection_id = 'legacy-inline' AND key = 'password'",
+ [],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
+ )
+ .map_err(|error| error.to_string())
+ })
+ .await
+ .unwrap();
+ assert!(row.0.is_empty());
+ assert!(row.1.as_deref().is_some_and(|value| value.starts_with("dbxenc1.")));
+ std::fs::remove_file(&db).ok();
+ }
+
+ #[tokio::test]
+ async fn sync_import_transaction_rolls_back_metadata_when_later_write_fails() {
+ let directory = tempfile::tempdir().unwrap();
+ let db = directory.path().join("dbx.db");
+ let storage =
+ Storage::open_unmigrated(&db).await.unwrap().with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
+ storage.save_connections(&[plain_connection("existing", "old-secret")]).await.unwrap();
+ let settings = storage.load_desktop_settings().await.unwrap();
+ let mut incoming = plain_connection("incoming", "new-secret");
+ incoming.url_params = Some("applicationName=dbx&sslmode=require".to_string());
+ let plan = SyncImportPlan {
+ connections: vec![incoming],
+ tunnel_profiles: Some(Vec::new()),
+ tunnel_secret_profiles: None,
+ sidebar_layout: None,
+ pinned_tree_node_ids: Vec::new(),
+ saved_sql: SavedSqlLibrary {
+ folders: vec![
+ SavedSqlFolder {
+ id: "duplicate-folder".to_string(),
+ connection_id: "incoming".to_string(),
+ parent_folder_id: None,
+ name: "one".to_string(),
+ order_index: 0,
+ created_at: String::new(),
+ updated_at: String::new(),
+ },
+ SavedSqlFolder {
+ id: "duplicate-folder".to_string(),
+ connection_id: "incoming".to_string(),
+ parent_folder_id: None,
+ name: "two".to_string(),
+ order_index: 1,
+ created_at: String::new(),
+ updated_at: String::new(),
+ },
+ ],
+ files: Vec::new(),
+ },
+ desktop_settings: settings,
+ editor_settings: None,
+ connection_secrets: None,
+ preserve_plugin_secrets: false,
+ sync_credentials: None,
+ ai_configs: None,
+ };
+ assert!(storage.apply_sync_import_transaction(plan).await.is_err());
+ let connections = storage.load_connections().await.unwrap();
+ assert_eq!(connections.len(), 1);
+ assert_eq!(connections[0].id, "existing");
+ assert_eq!(storage.get_secret("existing", "password").await.unwrap().as_deref(), Some("old-secret"));
+ assert_eq!(storage.get_secret("incoming", "url_params").await.unwrap(), None);
+ }
+
+ #[test]
+ fn migration_backup_manifest_rejects_invalid_paths() {
+ let invalid = serde_json::json!({"backupPaths": "not-a-list"});
+ assert!(super::migration_backup_paths(&invalid).is_err());
+ let valid = serde_json::json!({"backupPaths": ["/tmp/dbx-secret-migration-a"]});
+ assert_eq!(super::migration_backup_paths(&valid).unwrap(), vec!["/tmp/dbx-secret-migration-a"]);
+ }
}
diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs
index 7dbc2da51c..be51cceb49 100644
--- a/crates/dbx-mcp/src/backend.rs
+++ b/crates/dbx-mcp/src/backend.rs
@@ -691,7 +691,14 @@ impl LocalBackend {
/// Same as [`open`], but lets tests and embedded callers pin the app version
/// used for plugin compatibility checks instead of the compile-time version.
pub async fn open_with_app_version(path: &Path, app_version: &str) -> Result<Self, String> {
- let storage = Storage::open(path).await?;
+ // A local CLI/MCP process may share an already provisioned desktop
+ // Keychain/credential-store key. Preflight only reads that provider;
+ // it never provisions a key or migrates legacy credentials.
+ let storage = Storage::open_unmigrated(path).await?.with_secret_key_creation(false);
+ let migration = storage.inspect_data_migration().await?;
+ if !migration.is_ready() {
+ return Err("DATA_MIGRATION_REQUIRED: open DBX Desktop or Web to complete the data security upgrade".into());
+ }
let configs = storage.load_connections().await?;
let desktop_settings = storage.load_desktop_settings().await.unwrap_or_default();
let data_dir = path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf();
@@ -4012,6 +4019,29 @@ mod tests {
assert!(connections.is_empty());
}
+ #[tokio::test]
+ async fn local_backend_rejects_legacy_data_without_migrating_it() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let database_path = data_dir.path().join("dbx.db");
+ let legacy_path = data_dir.path().join("secrets.json");
+ let legacy_contents = br#"{"legacy-connection":{"password":"legacy-test-password"}}"#;
+ std::fs::write(&legacy_path, legacy_contents).unwrap();
+
+ let error = match LocalBackend::open(&database_path).await {
+ Ok(_) => panic!("legacy data must not be opened by CLI/MCP"),
+ Err(error) => error,
+ };
+ assert!(error.starts_with("DATA_MIGRATION_REQUIRED"));
+ assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_contents);
+ assert!(!data_dir.path().join("secrets.json.bak").exists());
+ assert!(std::fs::read_dir(data_dir.path())
+ .unwrap()
+ .all(|entry| { !entry.unwrap().file_name().to_string_lossy().starts_with("dbx-secret-migration-") }));
+ let storage = Storage::open_unmigrated(&database_path).await.unwrap();
+ assert!(storage.inspect_data_migration().await.unwrap().needs_migration);
+ assert!(storage.load_connections().await.unwrap().is_empty());
+ }
+
#[tokio::test]
async fn local_backend_uses_desktop_plugin_directory() {
let data_dir = tempfile::tempdir().unwrap();
diff --git a/crates/dbx-web/src/auth.rs b/crates/dbx-web/src/auth.rs
index 39122902fd..685a0e2641 100644
--- a/crates/dbx-web/src/auth.rs
+++ b/crates/dbx-web/src/auth.rs
@@ -48,7 +48,7 @@ fn api_path_suffix<'a>(path: &'a str, public_base_path: &str) -> Option<&'a str>
path.strip_prefix(base)?.strip_prefix("/api/")
}
-fn middleware_api_path_suffix<'a>(path: &'a str, public_base_path: &str) -> Option<&'a str> {
+pub(crate) fn middleware_api_path_suffix<'a>(path: &'a str, public_base_path: &str) -> Option<&'a str> {
if let Some(suffix) = api_path_suffix(path, public_base_path) {
return Some(suffix);
}
@@ -281,7 +281,7 @@ mod tests {
}
#[test]
- fn middleware_api_path_suffix_handles_nested_router_paths() {
+ pub(crate) fn middleware_api_path_suffix_handles_nested_router_paths() {
assert_eq!(middleware_api_path_suffix("/auth/check", "/"), Some("auth/check"));
assert_eq!(middleware_api_path_suffix("/connection/list", "/"), Some("connection/list"));
assert_eq!(middleware_api_path_suffix("/api/connection/list", "/"), Some("connection/list"));
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index a58d8efe07..408a142530 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -13,17 +13,19 @@ use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::{Argon2, PasswordHasher};
use axum::extract::DefaultBodyLimit;
-use axum::http::Uri;
+use axum::http::{Request, StatusCode, Uri};
use axum::middleware;
-use axum::response::Redirect;
+use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::{delete, get, post};
use axum::Router;
use dbx_core::connection::AppState;
+use dbx_core::persistence::secret_codec::SecretKeyPolicy;
use dbx_core::sql_dialect::dialect_loader::{register_core_dialects, DialectPluginLoader, DialectRegistry};
use dbx_core::sql_dialect::hot_reload::DialectHotReload;
use dbx_core::storage::Storage;
use dbx_mcp::{streamable_http_router, DbxBackend, HttpAuth, LocalBackend};
use state::WebState;
+use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::RwLock;
use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
use tower_http::compression::CompressionLayer;
@@ -78,6 +80,35 @@ fn web_body_limit_bytes_from_value(value: Option<&str>) -> usize {
mb.saturating_mul(1024 * 1024)
}
+async fn migration_gate(
+ state: axum::extract::State<Arc<WebState>>,
+ request: Request<axum::body::Body>,
+ next: axum::middleware::Next,
+) -> Response {
+ let suffix = auth::middleware_api_path_suffix(request.uri().path(), &state.public_base_path);
+ let allowed = suffix.is_some_and(|path| {
+ matches!(
+ path,
+ "migration/status" | "migration/start" | "migration/retry" | "migration/cleanup-backups" | "ping"
+ ) || path.starts_with("auth/")
+ });
+ if !allowed && !state.migration_ready.load(Ordering::Acquire) {
+ return (
+ StatusCode::LOCKED,
+ axum::Json(serde_json::json!({
+ "code": "DATA_MIGRATION_REQUIRED",
+ "message": "Complete the data security migration before using DBX"
+ })),
+ )
+ .into_response();
+ }
+ next.run(request).await
+}
+
+async fn storage_migration_ready(app: &Arc<AppState>) -> bool {
+ app.storage.inspect_data_migration().await.map(|status| status.is_ready()).unwrap_or(false)
+}
+
fn web_agent_dir(data_dir: &std::path::Path) -> std::path::PathBuf {
web_agent_dir_from_env(data_dir, std::env::var("DBX_AGENT_DIR").ok())
}
@@ -301,8 +332,10 @@ async fn main() {
let app_state = {
let db_path = data_dir.join("dbx.db");
- let storage = Storage::open(&db_path).await.expect("Failed to open storage");
- storage.migrate_from_json(&data_dir).await.expect("Failed to migrate JSON data");
+ let storage = Storage::open_unmigrated(&db_path)
+ .await
+ .expect("Failed to open storage")
+ .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir);
// Initialize core dialect registry and load external plugin dialects
register_core_dialects();
@@ -349,6 +382,7 @@ async fn main() {
let public_base_path = normalize_public_base_path(std::env::var("DBX_PUBLIC_BASE_PATH").ok());
+ let migration_ready = storage_migration_ready(&app_state).await;
let web_state = Arc::new(WebState {
app: app_state,
data_dir,
@@ -364,12 +398,17 @@ async fn main() {
login_rate_limit: tokio::sync::Mutex::new(state::LoginRateLimit { fail_count: 0, locked_until: None }),
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(ssh_prompt::SshPromptHub::new()),
+ migration_ready: Arc::new(AtomicBool::new(migration_ready)),
});
ssh_prompt::install_web_ssh_prompt_bridge(web_state.ssh_prompts.clone());
// API routes
let api = Router::new()
+ .route("/migration/status", get(routes::migration::status))
+ .route("/migration/start", post(routes::migration::start))
+ .route("/migration/retry", post(routes::migration::retry))
+ .route("/migration/cleanup-backups", post(routes::migration::cleanup_backups))
// Auth
.route("/auth/login", post(auth::login))
.route("/auth/check", get(auth::check))
@@ -1188,6 +1227,7 @@ async fn main() {
api.route("/query/build-duckdb-attach-database-sql", post(routes::query::build_duckdb_attach_database_sql));
let api = add_mq_routes(api)
+ .layer(middleware::from_fn_with_state(web_state.clone(), migration_gate))
.layer(middleware::from_fn_with_state(web_state.clone(), auth::auth_middleware))
.with_state(web_state.clone());
@@ -1199,7 +1239,7 @@ async fn main() {
.layer(tower_http::trace::TraceLayer::new_for_http());
if let Some(mcp_router) = web_mcp_router(&web_state).expect("Invalid DBX Web MCP configuration") {
- app = app.merge(mcp_router);
+ app = app.merge(mcp_router.layer(middleware::from_fn_with_state(web_state.clone(), migration_gate)));
tracing::info!("DBX Web MCP is enabled at /mcp");
}
@@ -1248,6 +1288,45 @@ mod tests {
use axum::Router;
use tower_http::compression::predicate::Predicate;
+ #[tokio::test]
+ async fn migration_http_gate_blocks_business_until_ready_but_allows_cleanup_handler() {
+ use std::sync::{atomic::Ordering, Arc};
+ let directory = tempfile::tempdir().unwrap();
+ let storage = dbx_core::storage::Storage::open_unmigrated(&directory.path().join("dbx.db")).await.unwrap();
+ let app = Arc::new(dbx_core::connection::AppState::new(storage));
+ let state = Arc::new(crate::state::WebState::for_tests(app, directory.path().to_path_buf()));
+ state.migration_ready.store(false, Ordering::Release);
+ let router = Router::new()
+ .route("/api/migration/status", get(|| async { "status" }))
+ .route("/api/migration/cleanup-backups", post(|| async { "cleanup" }))
+ .route("/api/connection/list", get(|| async { "connections" }))
+ .route("/mcp", post(|| async { "mcp" }))
+ .layer(axum::middleware::from_fn_with_state(state.clone(), super::migration_gate));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
+ let client = reqwest::Client::new();
+ assert_eq!(
+ client.get(format!("http://{address}/api/migration/status")).send().await.unwrap().status(),
+ StatusCode::OK
+ );
+ for (method, path) in [(reqwest::Method::GET, "/api/connection/list"), (reqwest::Method::POST, "/mcp")] {
+ let response = client.request(method, format!("http://{address}{path}")).send().await.unwrap();
+ assert_eq!(response.status(), StatusCode::LOCKED);
+ assert_eq!(response.json::<serde_json::Value>().await.unwrap()["code"], "DATA_MIGRATION_REQUIRED");
+ }
+ assert_eq!(
+ client.post(format!("http://{address}/api/migration/cleanup-backups")).send().await.unwrap().status(),
+ StatusCode::OK
+ );
+ state.migration_ready.store(true, Ordering::Release);
+ assert_eq!(
+ client.get(format!("http://{address}/api/connection/list")).send().await.unwrap().status(),
+ StatusCode::OK
+ );
+ server.abort();
+ }
+
fn compression_response(content_type: &str) -> Response<Body> {
Response::builder().header(CONTENT_TYPE, content_type).body(Body::from(vec![b'x'; 64])).unwrap()
}
diff --git a/crates/dbx-web/src/routes/cloud_sync.rs b/crates/dbx-web/src/routes/cloud_sync.rs
index ab2af79558..d17b82b810 100644
--- a/crates/dbx-web/src/routes/cloud_sync.rs
+++ b/crates/dbx-web/src/routes/cloud_sync.rs
@@ -3,16 +3,16 @@ use std::sync::Arc;
use axum::extract::State;
use axum::Json;
use dbx_core::cloud_sync::{
- apply_sync_snapshot, build_sync_snapshot, build_sync_snapshot_with_saved_secrets, finalize_snippet_migration,
- forget_snippet_token, forget_webdav_password,
- forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
- resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
- save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
- save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
- snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
- webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
- SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
- WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus, WebDavSyncSummary,
+ apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
+ forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
+ resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
+ retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
+ save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
+ snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
+ webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
+ ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
+ SnippetSyncSummary, SnippetTokenStatus, WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus,
+ WebDavSyncSummary,
};
use dbx_core::storage::DesktopSettings;
use serde::{Deserialize, Serialize};
@@ -57,6 +57,9 @@ pub struct WebDavUploadRequest {
pub config: WebDavConfig,
pub editor_settings: Option<serde_json::Value>,
pub secrets_passphrase: Option<String>,
+ /// Explicit opt-in for exporting credentials.
+ #[serde(default)]
+ pub include_secrets: bool,
}
#[derive(Debug, Clone, Deserialize)]
@@ -64,6 +67,15 @@ pub struct WebDavUploadRequest {
pub struct WebDavDownloadRequest {
pub config: WebDavConfig,
pub secrets_passphrase: Option<String>,
+ /// Explicitly controls whether encrypted or legacy plaintext secrets may
+ /// be restored. Older clients omitted this field and retain the historical
+ /// restore behavior.
+ #[serde(default = "default_restore_secrets")]
+ pub restore_secrets: bool,
+}
+
+fn default_restore_secrets() -> bool {
+ true
}
#[derive(Debug, Clone, Deserialize)]
@@ -180,11 +192,27 @@ pub async fn webdav_sync_upload(
Json(mut req): Json<WebDavUploadRequest>,
) -> Result<Json<WebDavSyncSummary>, AppError> {
resolve_webdav_password(&state.app.storage, &mut req.config).await.map_err(AppError::from)?;
- let snapshot = build_sync_snapshot_with_saved_secrets(
+ let explicit_passphrase = req.secrets_passphrase.as_deref().and_then(|value| {
+ let value = value.trim();
+ (!value.is_empty()).then_some(value)
+ });
+ let saved_passphrase = if explicit_passphrase.is_none() {
+ resolve_webdav_sync_secrets_passphrase(&state.app.storage).await.map_err(AppError::from)?
+ } else {
+ None
+ };
+ let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
+ let snapshot = build_sync_snapshot_with_options(
&state.app.storage,
env!("CARGO_PKG_VERSION"),
req.editor_settings,
- req.secrets_passphrase.as_deref(),
+ dbx_core::cloud_sync::SyncExportOptions {
+ include_secrets: req.include_secrets,
+ sync_passphrase: passphrase,
+ include_ai_secrets: req.include_secrets,
+ include_tunnel_secrets: req.include_secrets,
+ include_plugin_secrets: req.include_secrets,
+ },
)
.await
.map_err(AppError::from)?;
@@ -208,7 +236,7 @@ pub async fn webdav_sync_download(
&snapshot,
ApplySnapshotOptions {
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
- restore_secrets: true,
+ restore_secrets: req.restore_secrets,
},
)
.await
@@ -299,10 +327,21 @@ pub async fn snippet_sync_upload(
} else {
None
};
- let snapshot =
- build_sync_snapshot(&state.app.storage, env!("CARGO_PKG_VERSION"), req.editor_settings, secrets_passphrase)
- .await
- .map_err(AppError::from)?;
+ let include_secrets = req.include_secrets;
+ let snapshot = build_sync_snapshot_with_options(
+ &state.app.storage,
+ env!("CARGO_PKG_VERSION"),
+ req.editor_settings,
+ dbx_core::cloud_sync::SyncExportOptions {
+ include_secrets,
+ sync_passphrase: secrets_passphrase,
+ include_ai_secrets: include_secrets,
+ include_tunnel_secrets: include_secrets,
+ include_plugin_secrets: include_secrets,
+ },
+ )
+ .await
+ .map_err(AppError::from)?;
let client = SnippetSyncClient::new(req.config).map_err(AppError::from)?;
let mut summary = client
.put_snapshot(&snapshot, req.snippet_passphrase.as_deref(), secrets_passphrase)
diff --git a/crates/dbx-web/src/routes/migration.rs b/crates/dbx-web/src/routes/migration.rs
new file mode 100644
index 0000000000..173240d5ff
--- /dev/null
+++ b/crates/dbx-web/src/routes/migration.rs
@@ -0,0 +1,47 @@
+use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
+use dbx_core::storage::{MigrationPreflight, MigrationReport};
+use serde_json::json;
+use std::sync::Arc;
+
+use crate::state::WebState;
+
+pub async fn status(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<MigrationPreflight>, (StatusCode, Json<serde_json::Value>)> {
+ state.app.storage.inspect_data_migration().await.map(Json).map_err(error_response)
+}
+
+pub async fn start(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<MigrationReport>, (StatusCode, Json<serde_json::Value>)> {
+ state.migration_ready.store(false, std::sync::atomic::Ordering::Release);
+ match state.app.storage.start_data_migration().await {
+ Ok(report) => {
+ let ready =
+ state.app.storage.inspect_data_migration().await.map(|status| status.is_ready()).unwrap_or(false);
+ state.migration_ready.store(ready, std::sync::atomic::Ordering::Release);
+ Ok(Json(report))
+ }
+ Err(error) => {
+ state.migration_ready.store(false, std::sync::atomic::Ordering::Release);
+ Err(error_response(error))
+ }
+ }
+}
+
+pub async fn retry(
+ State(state): State<Arc<WebState>>,
+) -> Result<Json<MigrationReport>, (StatusCode, Json<serde_json::Value>)> {
+ start(State(state)).await
+}
+
+pub async fn cleanup_backups(
+ State(state): State<Arc<WebState>>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ state.app.storage.cleanup_migration_backups().await.map_err(error_response)?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+fn error_response(error: String) -> (StatusCode, Json<serde_json::Value>) {
+ (StatusCode::BAD_REQUEST, Json(json!({"error": error})))
+}
diff --git a/crates/dbx-web/src/routes/mod.rs b/crates/dbx-web/src/routes/mod.rs
index 6e30fa4954..44ce656281 100644
--- a/crates/dbx-web/src/routes/mod.rs
+++ b/crates/dbx-web/src/routes/mod.rs
@@ -16,6 +16,7 @@ pub mod history;
pub mod jdbc;
pub mod layout;
pub mod mcp_policy;
+pub mod migration;
pub mod mongo;
pub mod mongodb_dump;
pub mod mongodb_import_export;
diff --git a/crates/dbx-web/src/routes/mq.rs b/crates/dbx-web/src/routes/mq.rs
index f9947f7490..f99a07a7d0 100644
--- a/crates/dbx-web/src/routes/mq.rs
+++ b/crates/dbx-web/src/routes/mq.rs
@@ -1571,6 +1571,7 @@ mod tests {
login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),
+ migration_ready: Arc::new(std::sync::atomic::AtomicBool::new(true)),
});
(state, dir)
}
diff --git a/crates/dbx-web/src/state.rs b/crates/dbx-web/src/state.rs
index 3083632db0..1e728def52 100644
--- a/crates/dbx-web/src/state.rs
+++ b/crates/dbx-web/src/state.rs
@@ -1,6 +1,7 @@
use dbx_core::connection::AppState;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
+use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use tokio::sync::{broadcast, watch, Mutex, RwLock};
use tokio_util::sync::CancellationToken;
@@ -43,6 +44,7 @@ pub struct WebState {
/// Completed Web export temp files waiting for the browser download.
pub export_files: RwLock<HashMap<String, WebExportFile>>,
pub ssh_prompts: Arc<crate::ssh_prompt::SshPromptHub>,
+ pub migration_ready: Arc<AtomicBool>,
}
impl WebState {
@@ -68,6 +70,7 @@ impl WebState {
login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),
+ migration_ready: Arc::new(AtomicBool::new(true)),
}
}
}
diff --git a/deploy/docker-compose.release.yml b/deploy/docker-compose.release.yml
index 1e8430cadc..ca1d6d584f 100644
--- a/deploy/docker-compose.release.yml
+++ b/deploy/docker-compose.release.yml
@@ -8,7 +8,15 @@ services:
- "4224:4224"
volumes:
- dbx-data:/app/data
+ # environment:
+ # DBX_SECRET_KEY_FILE: /run/secrets/dbx_secret_key
+ # secrets:
+ # - dbx_secret_key
restart: unless-stopped
volumes:
dbx-data:
+
+# secrets:
+# dbx_secret_key:
+# file: ./dbx_secret_key
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 25dfc6b1f8..0db5dc6fb4 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -15,9 +15,17 @@ services:
# - DBX_WEB_MCP_ALLOWED_ORIGINS=https://mcp-client.example.com
# Uncomment when publishing DBX under a reverse-proxy subpath, e.g. https://example.com/dbx/
# - DBX_PUBLIC_BASE_PATH=/dbx
+ # Optional production override. The default key is /app/data/.dbx/secret.key.
+ # - DBX_SECRET_KEY_FILE=/run/secrets/dbx_secret_key
+ # secrets:
+ # - dbx_secret_key
volumes:
- dbx-data:/app/data
restart: unless-stopped
volumes:
dbx-data:
+
+# secrets:
+# dbx_secret_key:
+# file: ./dbx_secret_key
diff --git a/deploy/dockerhub/README.md b/deploy/dockerhub/README.md
index 27212cfd09..fd63ff1f80 100644
--- a/deploy/dockerhub/README.md
+++ b/deploy/dockerhub/README.md
@@ -58,6 +58,8 @@ docker compose up -d --pull always
| `DBX_PASSWORD` | Not set | Access password for the DBX Web login page. Set a strong value for server deployments. |
| `DBX_DISABLE_PASSWORD` | `false` | Disables login protection when set to `true`. Do not use this on an untrusted network. |
| `DBX_DATA_DIR` | `/app/data` | Directory containing the DBX database, plugins, drivers, and other persistent data. |
+| `DBX_SECRET_KEY_FILE` | Not set | Optional external key file. Takes precedence over the managed data-directory key. |
+| `DBX_SECRET_KEY` | Not set | Optional key supplied by a secret manager. Used when no key file is configured. |
| `DBX_PORT` | `4224` | HTTP port inside the container. |
| `DBX_PUBLIC_BASE_PATH` | `/` | URL prefix for reverse-proxy deployments, for example `/dbx`. |
| `DBX_WEB_MCP_TOKEN` | Not set | Enables native Streamable HTTP MCP with this bearer token. Keep it secret. |
@@ -65,7 +67,27 @@ docker compose up -d --pull always
| `DBX_WEB_MCP_ALLOWED_HOSTS` | Not set | Required when native MCP is enabled. Comma-separated public Host authorities, including ports when present. |
| `DBX_WEB_MCP_ALLOWED_ORIGINS` | Not set | Comma-separated browser Origins allowed to call native MCP. Optional for non-browser MCP clients. |
-Persist `/app/data` with a named volume or bind mount. Removing this data removes saved connections and other DBX application data.
+Persist `/app/data` with a named volume or bind mount. DBX creates `/app/data/.dbx/secret.key` on the first sensitive write or data migration. Back up this file together with `/app/data/dbx.db`; losing it makes existing encrypted credentials unreadable. A key stored in the same volume does not protect against disclosure of the entire volume.
+
+For production, an external Docker Secret can replace the managed key:
+
+```yaml
+services:
+ dbx:
+ image: t8y2/dbx:latest
+ environment:
+ DBX_SECRET_KEY_FILE: /run/secrets/dbx_secret_key
+ secrets:
+ - dbx_secret_key
+ volumes:
+ - dbx-data:/app/data
+
+secrets:
+ dbx_secret_key:
+ file: ./dbx_secret_key
+```
+
+Create the external key once, keep it stable across upgrades, and never replace it while encrypted data exists.
## Native HTTP MCP
diff --git a/docs/content/docs/data-security-migration.cn.mdx b/docs/content/docs/data-security-migration.cn.mdx
new file mode 100644
index 0000000000..037a405016
--- /dev/null
+++ b/docs/content/docs/data-security-migration.cn.mdx
@@ -0,0 +1,212 @@
+---
+title: 数据安全升级与迁移
+description: 将已有 DBX 数据升级到加密 Secret Store 的完整指南。
+---
+
+<Callout type="warn">如果当前安装已经保存连接、密码、插件凭据、AI 提供商密钥、Tunnel 凭据或同步凭据,请先完成数据安全升级再使用 DBX。升级前请备份完整数据目录,并保留原有加密密钥。</Callout>
+
+本版本会把历史明文字段和 JSON 配置中的敏感值迁移到 DBX 加密 Secret Store。每个数据目录只需执行一次。向导会展示迁移范围,创建可回滚备份,执行迁移和验证,并在你明确删除前保留备份。
+
+## 本次升级会改变什么
+
+迁移覆盖以下敏感数据:
+
+- 数据库连接密码、SSH 凭据、私钥口令和 HTTP Tunnel 密钥;
+- 标记为 secret 的插件连接字段;
+- AI 提供商凭据;
+- SSH 和其他 Tunnel 配置;
+- WebDAV 及其他同步凭据;
+- 历史 `connections.json`、`secrets.json` 和相关 JSON 文件。
+
+连接和提供商的公开配置仍保留在普通配置中。敏感值改为加密字段,只能通过本机 Secret Store 解密。原始值不会上传、写入日志或出现在迁移诊断中。
+
+迁移使用固定 ID `secret-store-v1`,并记录以下状态:
+
+| 状态 | 含义 | 处理方式 |
+| -------------- | ------------------------ | ---------------------------------- |
+| `pending` | 需要迁移,或环境仍需修复 | 查看向导并处理密钥或文件问题 |
+| `running` | 正在备份或迁移 | 等待完成,不要替换数据目录 |
+| `failed` | 检查、写入或验证失败 | 查看脱敏错误,修复后点击“重试迁移” |
+| `succeeded` | 迁移和验证完成 | 测试 DBX,之后可选择删除迁移备份 |
+| `not_required` | 没有需要转换的历史数据 | 直接进入 DBX |
+
+## 升级前准备
+
+1. 退出 DBX,复制完整数据目录,包括 `dbx.db`、WAL 文件、JSON 配置文件和 `.dbx` 目录。
+2. 确认当前部署使用的密钥来源。已有密文时绝对不要轮换、删除或替换密钥。
+3. 确认运行 DBX 的账户可以读写数据目录,并能访问系统凭据库或外部密钥。
+4. 如果数据目录位于挂载卷,升级前先确保该卷会持久化。
+5. 不要只复制 `dbx.db` 到另一种操作系统。跨设备请使用 DBX 加密导出/导入。
+
+迁移备份是额外的回滚副本,不能替代正常备份策略。
+
+## 按部署方式升级
+
+### 桌面端应用
+
+桌面版使用操作系统凭据库:
+
+| 平台 | 密钥来源 |
+| ------- | ---------------------------------------------- |
+| macOS | Keychain,以及构建版本支持的平台兼容密钥 |
+| Windows | Credential Manager |
+| Linux | Secret Service;没有可用提供者时配置持久化密钥 |
+
+升级步骤:
+
+1. 安装新版本,不要删除已有配置目录。
+2. 启动 DBX,并在提示时允许访问 Keychain、Credential Manager 或 Secret Service。
+3. 在“数据安全升级”向导中查看统计和历史文件列表。
+4. 点击“开始迁移”,等待备份、迁移和验证完成。
+5. 完成页出现后,打开代表性的连接,并验证插件、AI 提供商、Tunnel 和同步功能。
+6. 验证通过前保留备份;确认不再需要回滚后再点击“删除迁移备份”。
+
+迁移期间主界面和普通业务命令会保持阻塞。状态、开始、重试、诊断和备份清理请求仍可用,向导才能恢复未完成的升级。
+
+### Docker 和 `dbx-web`
+
+数据库、历史文件和托管密钥必须使用同一个持久化数据卷。默认托管密钥位置是:
+
+```text
+${DBX_DATA_DIR}/.dbx/secret.key
+```
+
+Docker 升级步骤:
+
+1. 停止旧容器,备份命名卷或绑定的 `DBX_DATA_DIR`。
+2. 新容器继续把同一个卷挂载到同一个路径。
+3. 如果使用生产环境密钥,在启动新镜像前挂载密钥并设置 `DBX_SECRET_KEY_FILE`:
+
+```yaml
+services:
+ dbx:
+ image: t8y2/dbx:latest
+ environment:
+ DBX_DATA_DIR: /app/data
+ DBX_SECRET_KEY_FILE: /run/secrets/dbx_secret_key
+ secrets:
+ - dbx_secret_key
+ volumes:
+ - dbx-data:/app/data
+
+secrets:
+ dbx_secret_key:
+ file: ./dbx_secret_key
+```
+
+4. 启动新容器并打开 Web UI。业务 API 开放前会先显示迁移向导。
+5. 执行迁移,等待成功页出现,并通过 Web UI 验证代表性连接。
+6. 始终把数据卷和密钥一起保留;验证通过后再删除迁移备份。
+
+也可以由密钥管理系统提供 `DBX_SECRET_KEY`,不使用 `DBX_SECRET_KEY_FILE`。显式配置优先于数据目录托管密钥;如果显式密钥不可读或格式错误,DBX 不会静默回退到其他密钥。
+
+迁移未完成时,Web API 只允许迁移状态、开始、重试、ping、认证和备份清理。其他 API、MCP 路由和业务操作会返回 `423 DATA_MIGRATION_REQUIRED`。
+
+### 直接运行二进制或 systemd 服务
+
+1. 停止服务,备份 `DBX_DATA_DIR` 指向的目录。
+2. 确认服务账户能保留 `${DBX_DATA_DIR}/.dbx/secret.key`,或配置稳定的 `DBX_SECRET_KEY_FILE`/`DBX_SECRET_KEY`。
+3. 替换二进制并重启服务。
+4. 打开 `dbx-web` 提供的 Web UI,完成迁移向导。
+5. 使用 systemd 时,把密钥环境放在受保护的环境文件或凭据机制中,不要把生产密钥放在所有用户可读的 unit 文件里。
+6. 删除迁移备份前,先验证连接和相关集成。
+
+### CLI 和 MCP
+
+CLI 与独立 MCP 只检查迁移状态和已有密钥,不会创建密钥,也不会执行历史数据迁移。将 `DBX_DATA_DIR` 指向原数据目录,先通过桌面端或 `dbx-web` 完成迁移;在此之前,依赖业务数据的命令会返回 `DATA_MIGRATION_REQUIRED`。
+
+## 密钥管理规则
+
+DBX 有两条相互独立的密钥边界:
+
+| 密钥 | 用途 | 存放位置 | 是否通过同步复制 |
+| ---------------------- | ------------------------------- | ------------------------------------------ | -------------------------------- |
+| 本地 Secret Store 密钥 | 加密本机 `dbx.db` 中的敏感值 | 系统凭据库、数据目录托管密钥或环境变量密钥 | 否 |
+| 同步口令 | 加密导出/导入包中的敏感 payload | 用户为该同步包输入的口令 | 只作为同步包保护,不作为本地密钥 |
+
+数据目录托管密钥只有在迁移或首次写入敏感值时才会创建。它必须与 `dbx.db` 一起备份。密钥和数据库在同一卷中,只能保护静态数据内容,不能防止整个数据卷被复制后泄露。
+
+已有密文时使用新密钥会导致数据无法解密。正确做法是恢复原密钥,不要生成替代密钥。
+
+## 迁移内部流程
+
+存储层把迁移分成三个阶段:
+
+```text
+open_unmigrated()
+ -> 打开 SQLite 并初始化必要 schema,不修改历史数据
+inspect_data_migration()
+ -> 只读扫描数据库行、JSON 文件和密钥可用性
+start_data_migration()/retry_data_migration()
+ -> 创建备份、迁移、验证并记录最终状态
+```
+
+写入数据前,DBX 会创建权限受限的 `dbx-secret-migration-<uuid>/` 目录,存放一致性 SQLite 备份和存在的历史 JSON 文件。SQLite 使用备份 API 以保留 WAL 状态;备份失败时不会开始迁移。
+
+迁移把敏感字段写入本地 Secret Store,公开 JSON 只保留非敏感配置,并验证旧明文列为空且所有密文都能解密。历史 JSON 遵循“导入、验证、最后改名”顺序;只有成功后才改成 `.bak`。解析或验证失败时原文件仍保留,方便修复和重试。后续步骤失败时会先恢复 SQLite 备份,再记录 `failed`。
+
+预检查只返回数量、状态、非敏感提供商名称和文件名,不返回密码、Token、私钥、密钥内容或密钥路径。扫描统计带有源数据指纹,避免旧缓存让成功迁移再次显示为未完成。
+
+## 迁移成功后
+
+1. 测试你使用的每种数据库至少一个连接。
+2. 测试插件连接、AI 提供商、SSH/Tunnel 配置和包含凭据的同步操作。
+3. 重启 DBX 或容器,确认下一次启动直接进入主界面。
+4. 这些检查通过前保留迁移备份。
+5. 确认不再需要回滚后,点击“删除迁移备份”。启动门禁允许发送清理请求,但存储层仍会强制要求记录状态为 `succeeded`。
+
+保留备份不会阻塞后续启动。删除备份不可逆;如果仍需要恢复迁移前状态,请保留普通数据备份。
+
+## 失败处理
+
+### 向导显示迁移失败
+
+原始数据和迁移备份会保留。阅读向导错误,修复环境后点击“重试迁移”。常见原因包括:
+
+- 没有允许访问 Keychain、Credential Manager 或 Secret Service;
+- `.dbx/secret.key` 缺失或不可读;
+- `DBX_SECRET_KEY_FILE` 或 `DBX_SECRET_KEY` 已更换;
+- 历史 JSON 格式错误;
+- 没有足够权限或磁盘空间创建备份;
+- 历史值无法通过验证。
+
+排查期间不要删除 `dbx.db`、WAL、历史 JSON 或迁移目录。
+
+### 重启后向导再次出现
+
+导出脱敏诊断,检查 `state`、`needsMigration`、`errorCode`、`backupPath` 和统计字段。成功迁移应为 `succeeded` 或 `not_required`。如果启动之间更换了密钥或数据目录,先恢复原来的配对关系再重试。
+
+### 密钥不可用
+
+桌面端请允许 DBX 访问系统凭据库。Web、Docker 或二进制服务请确认数据目录挂载正确,且显式密钥配置可读。已有加密配置不能通过创建新密钥解决。
+
+### 连接密码消失
+
+确认应用使用的是升级前相同的数据目录和密钥。如果连接设置为 `save_password=false`,迁移会按设计不恢复主密码。确认配置目录和密钥正确后,再通过连接编辑器重新输入密码。
+
+### 删除备份失败
+
+保留备份并重试,同时检查迁移状态是否为 `succeeded`、数据目录是否可写,以及备份文件是否被手动修改。清理过程会在删除前校验清单路径和文件摘要。
+
+## 跨设备迁移不是本次升级
+
+不要通过复制 `dbx.db` 在不同操作系统之间搬迁配置。本地密钥属于源设备,请使用加密配置导出/导入:
+
+1. 分离导出公开配置和敏感值。
+2. 使用用户提供的同步口令保护敏感 payload。
+3. 在目标设备导入。
+4. 使用目标设备自己的本地 Secret Store 密钥重新加密。
+
+同步口令错误、ID 冲突或任一字段失败时,不会提交半成品导入结果。
+
+## 验证清单
+
+- [ ] 已创建完整的升级前数据目录备份。
+- [ ] 原有本地密钥或外部托管密钥仍然保留。
+- [ ] 向导以 `succeeded` 完成,或状态为 `not_required`。
+- [ ] 代表性连接和相关集成均可用。
+- [ ] 重启后不再阻塞在迁移向导。
+- [ ] 已保留迁移备份,或在验证后明确删除。
+- [ ] 跨设备迁移使用加密导出/导入,没有直接复制数据库。
+
+状态机、存储实现和开发者测试矩阵请参阅 [DBX 数据安全升级与迁移参考](https://github.com/t8y2/dbx/blob/main/docs/data-security-migration.zh-CN.md)。
diff --git a/docs/content/docs/data-security-migration.mdx b/docs/content/docs/data-security-migration.mdx
new file mode 100644
index 0000000000..ad1cd92736
--- /dev/null
+++ b/docs/content/docs/data-security-migration.mdx
@@ -0,0 +1,212 @@
+---
+title: Data Security Upgrade and Migration
+description: A complete guide to upgrading existing DBX data to the encrypted Secret Store.
+---
+
+<Callout type="warn">If the installation already contains connections, saved passwords, plugin credentials, AI provider keys, tunnel credentials, or sync credentials, complete this upgrade before using DBX. Back up the complete data directory and keep the existing encryption key.</Callout>
+
+This release moves sensitive values out of legacy plaintext fields and JSON configuration into DBX's encrypted Secret Store. The upgrade runs once for each data directory. The wizard shows what will be migrated, creates a rollback backup, migrates and verifies the data, and keeps the backup until you explicitly remove it.
+
+## What changes during the upgrade
+
+The migration covers sensitive values associated with:
+
+- database connections, including passwords, SSH credentials, private key passphrases, and HTTP tunnel secrets;
+- plugin connection fields marked as secrets;
+- AI provider credentials;
+- SSH and other tunnel profiles;
+- WebDAV and other synchronization credentials;
+- legacy `connections.json`, `secrets.json`, and related JSON files.
+
+Public connection and provider settings remain in the normal configuration. Secret values are stored as encrypted fields and are decrypted only through the local Secret Store. Existing values are not uploaded, logged, or placed in the migration diagnostic.
+
+The migration uses the fixed ID `secret-store-v1` and records one of these states:
+
+| State | Meaning | What you should do |
+| -------------- | ------------------------------------------------------- | ----------------------------------------------------------------------- |
+| `pending` | Data needs migration or the environment needs attention | Review the wizard and fix any key or file issue |
+| `running` | Backup or migration is in progress | Wait for the operation to finish; do not replace the data directory |
+| `failed` | A check, write, or verification step failed | Read the redacted error, fix the cause, then choose **Retry migration** |
+| `succeeded` | Migration and verification completed | Test DBX, then optionally delete the migration backup |
+| `not_required` | No legacy data needs conversion | Continue to DBX |
+
+## Before you upgrade
+
+1. Stop DBX and make a copy of the complete data directory, including `dbx.db`, any WAL files, JSON configuration files, and the `.dbx` directory.
+2. Identify the key source used by the deployment. Never rotate, delete, or replace a key while encrypted values exist.
+3. Make sure the account running DBX can read and write the data directory and can access its platform credential store or configured external key.
+4. If the data directory is on a mounted volume, make the volume persistent before restarting the new version.
+5. Do not copy only `dbx.db` to another operating system. Use DBX encrypted export/import for cross-device moves.
+
+The migration backup is an additional rollback copy. It does not replace your normal backup policy.
+
+## Choose the instructions for your deployment
+
+### Desktop application
+
+The desktop build uses the operating system credential store:
+
+| Platform | Key source |
+| -------- | ----------------------------------------------------------------------------- |
+| macOS | Keychain (and the platform-specific fallback described by the build) |
+| Windows | Credential Manager |
+| Linux | Secret Service; configure a persistent key if no usable provider is available |
+
+Upgrade procedure:
+
+1. Install the new DBX version without deleting the existing profile.
+2. Start DBX and allow Keychain, Credential Manager, or Secret Service access when prompted.
+3. Review the counts and the list of legacy files in **Data Security Upgrade**.
+4. Select **Start migration**. Keep DBX open while the backup, migration, and verification run.
+5. On the completion page, open representative connections and verify plugins, AI providers, tunnels, and sync features.
+6. Keep the backup until those checks pass. Use **Delete migration backups** only when you no longer need rollback.
+
+During this process the main DBX window and normal business commands remain blocked. Status, start, retry, diagnostics, and backup cleanup remain available so the wizard can recover from an incomplete upgrade.
+
+### Docker and `dbx-web`
+
+Use one persistent data volume for the database, legacy files, and managed key. The default managed key is:
+
+```text
+${DBX_DATA_DIR}/.dbx/secret.key
+```
+
+For Docker:
+
+1. Stop the old container and back up the named volume or bind-mounted `DBX_DATA_DIR`.
+2. Keep the same volume mounted at the same path in the new container.
+3. If you use a production key, mount it and set `DBX_SECRET_KEY_FILE` before starting the new image:
+
+```yaml
+services:
+ dbx:
+ image: t8y2/dbx:latest
+ environment:
+ DBX_DATA_DIR: /app/data
+ DBX_SECRET_KEY_FILE: /run/secrets/dbx_secret_key
+ secrets:
+ - dbx_secret_key
+ volumes:
+ - dbx-data:/app/data
+
+secrets:
+ dbx_secret_key:
+ file: ./dbx_secret_key
+```
+
+4. Start the new container and open the Web UI. The migration wizard is served before normal business APIs are enabled.
+5. Start the migration, wait for the success page, and verify representative connections through the Web UI.
+6. Keep the volume and key together. Remove migration backups only after verification.
+
+`DBX_SECRET_KEY` can be supplied by a secret manager instead of `DBX_SECRET_KEY_FILE`. Explicit key configuration takes precedence over the managed data-directory key. If an explicit key is unreadable or invalid, DBX does not silently fall back to another key.
+
+The Web API allows only migration status, start, retry, ping, authentication, and backup cleanup before migration is ready. Other API calls, MCP routes, and business operations return `423 DATA_MIGRATION_REQUIRED`.
+
+### Standalone binary or systemd service
+
+1. Stop the service and back up the directory named by `DBX_DATA_DIR`.
+2. Confirm that the service account can preserve `${DBX_DATA_DIR}/.dbx/secret.key`, or provide a stable `DBX_SECRET_KEY_FILE`/`DBX_SECRET_KEY`.
+3. Upgrade the binary and restart the service.
+4. Open the Web UI exposed by `dbx-web` and complete the wizard.
+5. For systemd, place the key environment in the service's protected environment or credentials mechanism. Do not put a production key in a world-readable unit file.
+6. Verify connections and integrations before deleting migration backups.
+
+### CLI and MCP
+
+CLI and standalone MCP commands inspect migration state and existing key material, but they do not create a key or run the legacy-data migration. Point `DBX_DATA_DIR` at the existing profile and complete the migration first with Desktop or `dbx-web`. Until then, commands that need business data fail with `DATA_MIGRATION_REQUIRED`.
+
+## Key management rules
+
+DBX has two separate key boundaries:
+
+| Key | Used for | Where it lives | Can it be copied through sync? |
+| ---------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------ |
+| Local Secret Store key | Encrypts secrets in the local `dbx.db` | Platform credential store, managed data-dir key, or explicit environment key | No |
+| Sync passphrase | Encrypts the sensitive part of an export/import package | Entered by the user for that package | Only as the package protection, never as the local key |
+
+The managed data-directory key is created only when migration or a sensitive write needs it. Back up it with `dbx.db`. A key stored in the same volume protects the database contents at rest, but it does not protect a stolen copy of the entire volume.
+
+If the database already contains encrypted values, using a new key makes them unreadable. Restore the original key instead of creating another one.
+
+## What the migration does internally
+
+The storage layer separates the operation into three phases:
+
+```text
+open_unmigrated()
+ -> open SQLite and initialize the required schema without changing legacy data
+inspect_data_migration()
+ -> read-only scan of database rows, JSON files, and key availability
+start_data_migration()/retry_data_migration()
+ -> create backup, migrate, verify, and record the final state
+```
+
+Before writing data, DBX creates a restricted `dbx-secret-migration-<uuid>/` directory containing a consistent SQLite backup and existing legacy JSON files. SQLite backup APIs preserve WAL state. If backup creation fails, migration does not proceed.
+
+Migration writes secret fields to the local Secret Store, leaves only non-sensitive configuration in public JSON, and verifies that old plaintext columns are empty and all encrypted values can be decrypted. Legacy JSON files are imported and verified before they are renamed to `.bak`; parse or verification failures leave the original source file available for repair and retry. Later failures restore the SQLite backup before reporting `failed`.
+
+The preflight response contains counts, states, non-sensitive provider names, and file names. It does not expose passwords, tokens, private keys, key contents, or key paths. Scan counts carry a source fingerprint so stale pre-migration counts cannot make a completed migration appear incomplete.
+
+## After a successful migration
+
+1. Test at least one connection from every database family you use.
+2. Test plugin connections, AI providers, SSH/tunnel profiles, and sync operations that contain credentials.
+3. Restart DBX or the container and confirm that the next start goes directly to the application.
+4. Keep the migration backup until these checks pass.
+5. Use **Delete migration backups** to remove the rollback copy. Cleanup is allowed through the startup gate, but the storage layer still refuses cleanup unless the recorded migration state is `succeeded`.
+
+Keeping the backup does not block future starts. Deleting it is irreversible; retain your normal data backup if you may need to restore the pre-migration state.
+
+## Failure recovery
+
+### The wizard reports a failed migration
+
+The original data and migration backup are retained. Read the error shown in the wizard, fix the environment, and choose **Retry migration**. Typical causes include:
+
+- a denied Keychain, Credential Manager, or Secret Service request;
+- a missing or unreadable `.dbx/secret.key`;
+- a changed `DBX_SECRET_KEY_FILE` or `DBX_SECRET_KEY`;
+- malformed legacy JSON;
+- insufficient permission or disk space for the backup;
+- a legacy value that cannot be validated.
+
+Do not delete `dbx.db`, WAL files, legacy JSON, or the migration directory while diagnosing the problem.
+
+### The wizard appears again after a restart
+
+Export the redacted diagnostic and check `state`, `needsMigration`, `errorCode`, `backupPath`, and the count fields. A successful migration should report `succeeded` or `not_required`. If the key or data directory changed between launches, restore the original pairing before retrying.
+
+### A key is unavailable
+
+For Desktop, grant access to the platform credential store. For Web, Docker, or a binary service, verify the mounted data directory and the explicit key configuration. Do not create a replacement key for an existing encrypted profile.
+
+### A connection loses its password
+
+Check that the application is using the same data directory and key as before the upgrade. If `save_password=false` was set, the migration intentionally does not recreate a password. Re-enter it through the normal connection editor only after confirming the correct profile and key.
+
+### Backup cleanup fails
+
+Keep the backup and retry after checking that the migration state is `succeeded`, the data directory is writable, and no backup file was manually changed. The cleanup validates manifest paths and file digests before removing files.
+
+## Cross-device moves are separate from this upgrade
+
+Never move a profile by copying `dbx.db` between operating systems. Local keys belong to the source device. Use encrypted Config Export/Import instead:
+
+1. Export public configuration and sensitive values separately.
+2. Protect the sensitive payload with the user-provided sync passphrase.
+3. Import it on the destination device.
+4. Re-encrypt imported values with the destination's local Secret Store key.
+
+Wrong passphrases, ID conflicts, or field-level failures do not commit a partial import.
+
+## Verification checklist
+
+- [ ] A complete pre-upgrade data-directory backup exists.
+- [ ] The original local or externally managed key is preserved.
+- [ ] The migration wizard completed with `succeeded` or the profile reported `not_required`.
+- [ ] Representative connections and integrations work.
+- [ ] A restart no longer blocks on migration.
+- [ ] The migration backup is retained or deliberately deleted after verification.
+- [ ] Cross-device moves use encrypted export/import rather than database copying.
+
+For the state machine, storage implementation, and developer test matrix, see [DBX Data Security Upgrade and Migration reference](https://github.com/t8y2/dbx/blob/main/docs/data-security-migration.md).
diff --git a/docs/content/docs/faq.cn.mdx b/docs/content/docs/faq.cn.mdx
index 1337d5331b..251639e082 100644
--- a/docs/content/docs/faq.cn.mdx
+++ b/docs/content/docs/faq.cn.mdx
@@ -30,4 +30,5 @@ description: DBX 常见问题:连接数据保存在哪里、如何备份、如
`portable.dbx` 标记仅对 Windows 生效,且当 exe 旁存在 `uninstall.exe`(安装版)时会被忽略;解压版目录中手动创建该标记同样可以启用便携模式。应用内没有切换数据目录的设置项。
</Accordion>
+ <p>升级已有安装前,请先阅读[数据安全升级与迁移说明](/cn/docs/data-security-migration)。</p>
</Accordions>
diff --git a/docs/content/docs/faq.mdx b/docs/content/docs/faq.mdx
index d5f2b4fda3..4fec2cf71c 100644
--- a/docs/content/docs/faq.mdx
+++ b/docs/content/docs/faq.mdx
@@ -30,4 +30,5 @@ description: Frequently asked questions about DBX, including where connection da
The `portable.dbx` marker only works on Windows, and it is ignored when `uninstall.exe` sits next to the executable (installed builds). There is no in-app setting for the data directory.
</Accordion>
+ <p>See the [Data Security Upgrade and Migration guide](/en/docs/data-security-migration) before upgrading an existing installation.</p>
</Accordions>
diff --git a/docs/data-security-migration.md b/docs/data-security-migration.md
new file mode 100644
index 0000000000..cc98d28fcc
--- /dev/null
+++ b/docs/data-security-migration.md
@@ -0,0 +1,149 @@
+# DBX Data Security Upgrade and Migration
+
+This document records the DBX Secret Store, legacy-data migration, cross-device synchronization, and startup wizard design. It is intended for users troubleshooting an upgrade and for developers maintaining the implementation.
+
+## Upgrade behavior
+
+New DBX releases protect connection, plugin, AI, tunnel, and synchronization secrets through the Secret Store. On the first launch after an upgrade, DBX checks the active data directory. If data still requires conversion, the **Data Security Upgrade** wizard is shown before the main application.
+
+This is a one-time operation. After a successful migration, later launches go directly to DBX. The migration backup remains available until the user confirms that connections work and explicitly deletes it.
+
+## Key boundaries
+
+DBX uses two independent key systems:
+
+| Purpose | Source | Scope | Cross-device |
+| --- | --- | --- | --- |
+| Local storage key | Desktop platform store, Web managed data-dir key, or `DBX_SECRET_KEY(_FILE)` | Protects Secret Store values in the local `dbx.db` | Never copied by sync |
+| Sync passphrase | Entered by the user during export/import | Protects sensitive fields in an encrypted sync package | Used with that package |
+
+Local keys are never written to a sync file. Copying `dbx.db` to another computer is not a supported cross-device migration method; use encrypted export/import instead. Local values use the `dbxenc1` envelope, AES-256-GCM, and authenticated data bound to the namespace and field name. Sync packages use a separate crypto format and passphrase.
+
+## Supported environments
+
+Desktop builds use the platform credential store on macOS, Windows, and Linux.
+
+`dbx-web` uses `${DBX_DATA_DIR}/.dbx/secret.key` by default, whether it runs in Docker, under systemd, or directly from the binary. The key is created with restricted permissions only when migration starts or the first sensitive value is written. It is part of the same recovery unit as `dbx.db`; back up and restore both files together. A key stored in the data directory does not protect against disclosure of the entire data volume.
+
+Production deployments can require an externally managed key instead:
+
+```text
+DBX_SECRET_KEY_FILE=/run/secrets/dbx_secret_key
+```
+
+`DBX_SECRET_KEY` may also be supplied by a secret manager. Explicit configuration takes precedence over the managed data-dir key and never falls back when it is unreadable or invalid. Do not replace the key across restarts or upgrades while encrypted data exists.
+
+Web, Docker, CLI, and MCP business operations remain blocked until migration is complete. CLI and standalone MCP only inspect existing key material; they do not create keys or migrate legacy data. `DATA_MIGRATION_REQUIRED` means the same data directory must first be opened in Desktop or Web and completed through the wizard.
+
+## Migration state machine
+
+Storage startup is split into three phases:
+
+```text
+open_unmigrated()
+ -> open SQLite and initialize required schema without migrating data
+inspect_data_migration()
+ -> read-only scan of database, JSON files, and key providers
+start_data_migration()/retry_data_migration()
+ -> backup, migrate, verify, and record the final state
+```
+
+The `data_migrations` table uses the fixed migration ID `secret-store-v1`:
+
+- `pending`: waiting for the user or an environment fix.
+- `running`: backup or migration is in progress.
+- `failed`: migration failed; source data and backup remain available for retry.
+- `succeeded`: migration completed; later starts go directly to DBX.
+- `not_required`: no legacy data needs migration.
+
+Scan counts have an independent source fingerprint. State transitions invalidate old scan caches so pre-migration counts cannot make a successful migration appear pending.
+
+## Migration workflow
+
+### Preflight and backup
+
+Preflight returns counts, statuses, non-sensitive key-source names, and file names only. It does not return passwords, tokens, private keys, or key paths. It checks connection, plugin, AI, tunnel, sync, and legacy JSON data plus key availability. If ciphertext already exists, preflight verifies that the selected key can decrypt it; it never creates a replacement key.
+
+Before changing data DBX creates a restricted `dbx-secret-migration-<uuid>/` directory. It contains a consistent SQLite backup and any legacy JSON files that exist. SQLite backup APIs are used so WAL state is not lost. If backup creation fails, migration does not start.
+
+### Migration and verification
+
+Sensitive connection, plugin, AI, tunnel, WebDAV, and source-control fields are written through the target device's Secret Store. Public configuration JSON keeps only non-sensitive fields. Database changes are transactional; if a later JSON parse, write, or verification step fails, the database backup is restored.
+
+Legacy JSON follows an import, verify, then rename sequence. A source file is renamed to `.bak` only after successful verification. Parse failures leave the original file untouched for repair and retry.
+
+Verification confirms that legacy plaintext columns are empty, all encrypted values can be decrypted with the current device key, public JSON contains no sensitive fields, `save_password=false` connections do not regain passwords, and legacy JSON is renamed only after success.
+
+## Wizard and restart behavior
+
+The wizard has three steps: **Review and confirm**, **Migrate data**, and **Complete and backup**. It explains the upgrade, creates a restricted backup, verifies the result, and provides retry, redacted diagnostics, and explicit backup cleanup.
+
+The current session shows the completion page after a successful migration. After closing and reopening DBX, a `succeeded` or `not_required` state goes directly to the main application. Keeping a backup does not block later starts. The wizard includes a language selector for all currently supported locales.
+
+## Cross-device synchronization
+
+Cross-device sync never copies DPAPI, Keychain, Secret Service, or a local DEK. A Windows-to-Mac flow is:
+
+1. Read secrets from the source device's local Secret Store.
+2. Separate public configuration from sensitive payload.
+3. Derive a transport key from the user-provided sync passphrase using Argon2id.
+4. Encrypt the sensitive payload with AES-256-GCM.
+5. Decrypt it on the destination device with the same passphrase.
+6. Re-encrypt each secret with the destination device's local Secret Store.
+
+Import can restore metadata only or restore secrets as well. Wrong passphrases, ID conflicts, and field failures do not commit a partial import.
+
+## Compatibility and recovery
+
+- New users perform only a lightweight scan and receive no migration backup.
+- Older databases and JSON files can be upgraded without installing an intermediate version.
+- Older sync package versions remain readable according to their compatibility rules.
+- Failed migrations keep the original data and backup and can be retried.
+- Successful migration backups remain until the user explicitly cleans them up.
+- Direct `dbx.db` copying is not a supported cross-platform migration path.
+
+## Troubleshooting
+
+### The wizard appears again
+
+Confirm that the installed build includes the migration-cache fix. Export the redacted diagnostic and inspect `state`, `needsMigration`, `errorCode`, `backupPath`, and `counts`. If the state is `succeeded` but counts still show legacy values, the next status scan invalidates the stale cache.
+
+### Key unavailable
+
+Allow DBX Desktop to access the platform credential store. For Web/Docker, confirm that `${DBX_DATA_DIR}/.dbx/secret.key` is present with the data volume, or that an explicitly configured `DBX_SECRET_KEY_FILE` is readable. Do not delete or replace the key used to encrypt an existing database.
+
+### Migration failed
+
+The source data is retained. Fix the issue shown by the wizard and choose **Retry migration**. Export only the redacted diagnostic; do not upload `dbx.db`, WAL files, or migration backup directories.
+
+## Implementation map
+
+| Module | Responsibility |
+| --- | --- |
+| `crates/dbx-core/src/persistence/secret_codec.rs` | Local encryption, key providers, and key parsing |
+| `crates/dbx-core/src/persistence/storage.rs` | Migration state, preflight, backup, migration, and verification |
+| `crates/dbx-core/src/persistence/cloud_sync.rs` | Encrypted cross-device export/import |
+| `src-tauri/src/migration_gate.rs` | Desktop business-command gate |
+| `crates/dbx-web/src/routes/migration.rs` | Web/Docker migration API |
+| `crates/dbx-web/src/main.rs` | Web migration gate |
+| `apps/desktop/src/StartupGate.vue` | Desktop startup routing and blocking |
+| `apps/desktop/src/components/migration/SecurityMigrationWizard.vue` | Wizard UI, locale switch, and diagnostics |
+| `apps/desktop/src/stores/migrationStore.ts` | Wizard state and action orchestration |
+
+## Testing and acceptance
+
+Migration frontend tests cover successful restart behavior, migration failure and retry, status failures, backup cleanup failures, diagnostic export fallback, and locale resources.
+
+Recommended checks:
+
+```bash
+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
+pnpm exec vitest run apps/desktop/src/stores/migrationStore.spec.ts apps/desktop/src/components/migration/SecurityMigrationWizard.spec.ts
+git diff --check
+```
+
+Rust tests should cover authenticated encryption, migration-cache invalidation, transaction rollback, JSON rename ordering, safe backup cleanup, and Tauri/Web startup gates. Manual smoke testing should include macOS, Windows, Linux, Docker restarts with a fixed key, failed migrations, and Windows-to-Mac encrypted sync.
+
+## Maintenance policy
+
+The wizard UI may be reduced in later releases, but the `secret-store-v1` engine, legacy schema detection, old ciphertext reading, old sync-package compatibility, and failure recovery must remain. Users may upgrade directly from a much older release.
diff --git a/docs/data-security-migration.zh-CN.md b/docs/data-security-migration.zh-CN.md
new file mode 100644
index 0000000000..9badc760dc
--- /dev/null
+++ b/docs/data-security-migration.zh-CN.md
@@ -0,0 +1,232 @@
+# DBX 数据安全升级与迁移
+
+本文档记录 DBX Secret Store、历史数据迁移、跨平台同步和启动向导的设计与实现,供用户排障和后续开发维护使用。
+
+## 1. 为什么需要这次升级
+
+新版本将连接、插件、AI、Tunnel 和同步相关的敏感配置统一交给 Secret Store 保护。升级后的第一次启动会检查当前数据目录:如果发现仍有需要处理的数据,DBX 会在进入主界面前显示“数据安全升级”向导。
+
+这不是每次启动都要执行的操作。迁移成功后,后续启动会直接进入 DBX;迁移备份可以在确认连接正常后由用户主动清理。
+
+## 2. 密钥边界
+
+DBX 使用两套互相独立的密钥体系:
+
+| 用途 | 密钥来源 | 作用 | 是否跨设备 |
+| --- | --- | --- | --- |
+| 本地存储密钥 | 桌面系统凭据库、Web 数据目录托管密钥,或 `DBX_SECRET_KEY(_FILE)` | 保护当前设备 `dbx.db` 中的 Secret Store 密文 | 不通过同步传输 |
+| 同步口令 | 用户在导出/导入时主动输入 | 保护跨平台同步包中的敏感 payload | 随加密同步包使用 |
+
+本地密钥不会写入同步文件,也不能通过复制 `dbx.db` 迁移到另一台设备。跨平台迁移必须使用加密导出/导入。
+
+本地 Secret Store 使用 `dbxenc1` 密文封装、AES-256-GCM 和绑定命名空间/字段名的 AAD。同步包使用独立的同步加密格式和同步口令,不能直接复用本地密文。
+
+## 3. 支持范围
+
+### 桌面端
+
+- macOS:使用 Keychain;必要时使用受限权限的兼容密钥文件。
+- Windows:使用 Credential Manager。
+- Linux:使用 Secret Service;无可用平台存储时,迁移向导会提示配置持久化密钥。
+- 向导阻止进入主界面,直到迁移完成或确认当前数据不需要迁移。
+
+### Web、Docker、CLI 和 MCP
+
+`dbx-web` 无论通过 Docker、systemd 还是直接运行二进制,默认都使用 `${DBX_DATA_DIR}/.dbx/secret.key`。只有在开始迁移或第一次写入敏感字段时才创建该密钥,并使用受限权限。它与 `dbx.db` 属于同一恢复单元,必须一起备份和恢复;数据目录内密钥不能防护整个数据卷被复制或泄露。
+
+生产环境可以改用外部托管密钥:
+
+```text
+DBX_SECRET_KEY_FILE=/run/secrets/dbx_secret_key
+```
+
+也可以由密钥管理系统提供 `DBX_SECRET_KEY`。显式配置优先;显式密钥不可读或格式错误时不会回退到数据目录密钥。已有密文使用期间不能更换密钥。
+
+CLI/MCP 启动检查只读取现有密钥,不自动生成密钥,也不自动迁移历史数据。返回 `DATA_MIGRATION_REQUIRED` 时,应先使用桌面端或 Web 向导完成迁移。
+
+## 4. 启动与迁移状态机
+
+存储启动拆分为三个阶段:
+
+```text
+open_unmigrated()
+ -> 打开 SQLite、初始化必要 schema,不迁移历史数据
+
+inspect_data_migration()
+ -> 只读扫描数据库、JSON 文件和密钥提供者
+
+start_data_migration()/retry_data_migration()
+ -> 备份、迁移、验证、记录最终状态
+```
+
+状态记录在 `data_migrations` 表中,固定迁移 ID 为 `secret-store-v1`:
+
+- `pending`:等待用户开始或等待修复环境。
+- `running`:正在备份或迁移。
+- `failed`:迁移失败,原始数据和备份保留,可以重试。
+- `succeeded`:迁移成功,后续启动直接进入主界面。
+- `not_required`:没有需要迁移的数据。
+
+扫描统计带有独立的源数据指纹。迁移状态变化时旧扫描缓存会失效,避免把迁移前的敏感项数量误用于迁移后的状态判断。
+
+## 5. 迁移流程
+
+### 5.1 预检查
+
+预检查只返回数量、状态、非敏感的密钥来源名称和文件名,不返回密码、Token、私钥、密钥内容或密钥路径。已有密文时会验证当前密钥能否解密,绝不会生成替代密钥。检查内容包括:
+
+- 连接和 `connection_secrets` 中的待处理项。
+- 插件 secret、AI secret、Tunnel secret 和同步凭据。
+- 历史 JSON 文件是否存在。
+- 本机或外部密钥是否可用。
+- 是否需要创建备份。
+
+### 5.2 创建备份
+
+迁移前创建权限受限的目录:
+
+```text
+dbx-secret-migration-<uuid>/
+```
+
+目录中包含 SQLite 一致性备份以及存在的历史 JSON 文件。SQLite 使用备份 API,避免只复制主数据库而遗漏 WAL 状态。备份创建失败时不会开始迁移。
+
+### 5.3 数据迁移
+
+迁移在目标设备的本地 Secret Store 下执行:
+
+1. 连接密码、SSH 密码和私钥口令写入对应 Secret Store 命名空间。
+2. 插件 `binding: "secret"` 字段写入 `plugin_connection.<field>` 命名空间。
+3. AI、Tunnel、WebDAV 和代码托管凭据写入对应全局命名空间。
+4. 公开配置 JSON 只保留非敏感字段。
+5. 数据库写入使用事务;后续 JSON 解析或验证失败时恢复数据库备份。
+
+历史 JSON 遵循“导入、验证、最后改名”顺序。成功后才改名为 `.bak`;解析失败时原文件保持不变,方便修复后重试。
+
+### 5.4 验证
+
+提交后验证:
+
+- 旧明文列为空。
+- 敏感字段具备 `dbxenc1` 密文。
+- 所有密文可以使用当前设备密钥解密。
+- 连接、AI、Tunnel 和插件公开 JSON 不含敏感字段。
+- `save_password=false` 的连接不会重新获得主密码。
+- 历史 JSON 只有在验证成功后才改名。
+
+任一验证失败都会保留原始备份并将状态记录为 `failed`。
+
+## 6. 向导行为
+
+向导包含三个步骤:
+
+1. **检查与确认**:说明升级目的、备份和验证行为,展示脱敏统计。
+2. **执行迁移**:显示执行状态;失败时提供重试、脱敏诊断导出和退出入口。
+3. **完成与备份**:显示备份位置。刚完成迁移的当前会话可以进入 DBX,也可以在确认连接正常后删除备份。
+
+重启行为有明确区分:
+
+- 迁移刚完成的当前会话显示完成页。
+- 之后再次启动,如果状态为 `succeeded` 或 `not_required`,直接进入主界面。
+- 保留备份不会再次阻塞启动。
+
+向导右上角可以临时切换语言。迁移文案覆盖当前支持的语言,未单独覆盖的字段仍通过项目的英文回退机制解析。
+
+## 7. 跨平台同步
+
+跨平台同步不复制 Windows DPAPI、macOS Keychain、Linux Secret Service 或本地 DEK。
+
+Windows 到 Mac 的流程是:
+
+1. 源设备读取本地 Secret Store 中的明文值。
+2. 公开配置与敏感 payload 分离。
+3. 用户输入同步口令,通过 Argon2id 派生同步密钥。
+4. 使用 AES-256-GCM 加密敏感 payload。
+5. 目标设备输入相同同步口令并解密。
+6. 目标设备使用自己的本地 Secret Store 重新加密保存。
+
+导入支持只导入元数据或同时恢复 secrets。错误同步口令、ID 冲突和任一字段失败时,不提交半成品数据。
+
+## 8. 兼容与回滚
+
+- 新用户只执行轻量扫描,不创建迁移备份。
+- 旧数据库和旧 JSON 可以直接升级,不要求用户先安装中间版本。
+- 旧同步包继续按版本兼容规则读取;新同步包使用独立的 crypto version。
+- 迁移失败保留原数据库和迁移备份,可以反复重试。
+- 迁移成功后备份默认保留,用户确认连接正常后才清理。
+- 直接复制 `dbx.db` 不属于受支持的跨平台迁移方式。
+
+## 9. 用户排障
+
+### 向导重复出现
+
+确认使用的是包含迁移状态缓存修复的版本。向导成功后重启应直接进入主界面;如果仍显示向导,导出脱敏诊断,重点查看:
+
+- `state`
+- `needsMigration`
+- `errorCode`
+- `backupPath`
+- `counts`
+
+如果 `state` 为 `succeeded` 但统计仍显示旧数据,通常是旧版本扫描缓存,升级后的版本会自动重新扫描。
+
+### 密钥不可用
+
+- 桌面端:允许 DBX 访问系统钥匙串/凭据存储。
+- Web/Docker:确认 `${DBX_DATA_DIR}/.dbx/secret.key` 与数据卷一起保留,或显式配置的 `DBX_SECRET_KEY_FILE` 可读。
+- 不要删除或更换已经用于加密数据库的密钥文件。
+
+### 迁移失败
+
+原始数据不会被直接删除。修复向导提示的问题后点击 **重试迁移**。如果需要提交问题报告,只导出向导提供的脱敏诊断,不要上传 `dbx.db`、WAL 文件或迁移备份目录。
+
+## 10. 实现位置
+
+| 模块 | 主要职责 |
+| --- | --- |
+| `crates/dbx-core/src/persistence/secret_codec.rs` | 本地密文、密钥提供者和密钥材料解析 |
+| `crates/dbx-core/src/persistence/storage.rs` | 迁移状态、预检查、备份、迁移和验证 |
+| `crates/dbx-core/src/persistence/cloud_sync.rs` | 跨设备同步 payload 和导入导出事务 |
+| `src-tauri/src/migration_gate.rs` | 桌面端业务 API 启动门禁 |
+| `crates/dbx-web/src/routes/migration.rs` | Web/Docker 迁移 API |
+| `crates/dbx-web/src/main.rs` | Web 端迁移门禁 |
+| `apps/desktop/src/StartupGate.vue` | 桌面端启动路由和向导阻塞 |
+| `apps/desktop/src/components/migration/SecurityMigrationWizard.vue` | 向导 UI、语言切换和诊断导出 |
+| `apps/desktop/src/stores/migrationStore.ts` | 向导状态和动作编排 |
+
+## 11. 测试与验收
+
+### 自动化测试
+
+迁移相关前端测试覆盖:
+
+- 成功迁移后的启动行为。
+- 迁移失败和重试。
+- 状态检查失败。
+- 备份清理失败和重试。
+- 诊断导出失败时的页面内报告。
+- 多语言资源和回退。
+
+推荐命令:
+
+```bash
+pnpm exec vue-tsc --noEmit --project apps/desktop/tsconfig.json
+pnpm exec vitest run apps/desktop/src/stores/migrationStore.spec.ts apps/desktop/src/components/migration/SecurityMigrationWizard.spec.ts
+git diff --check
+```
+
+Rust 侧应覆盖密文 AAD、迁移缓存失效、数据库事务回滚、JSON 改名顺序、备份清理安全校验和 Web/Tauri 启动门禁。
+
+### 手工冒烟
+
+至少验证以下环境:
+
+1. macOS、Windows、Linux 桌面端各完成一次旧数据迁移。
+2. Docker 命名卷与直接运行 `dbx-web` 都能保留数据目录密钥,重启后仍可读取密文。
+3. 迁移成功后关闭并重新打开,直接进入主界面。
+4. 错误密钥、错误同步口令和损坏 JSON 不会破坏原始数据。
+5. Windows 导出、Mac 导入后,连接和插件 secret 可以正常使用。
+
+## 12. 维护约定
+
+迁移向导 UI 可以在后续版本弱化,但 `secret-store-v1` 引擎、旧 schema 识别、旧密文读取、旧同步包兼容和失败恢复能力必须长期保留。用户可能从很旧的版本直接升级,不能依赖连续升级路径。
diff --git a/packages/app-tests/webdavAutoUpload.test.ts b/packages/app-tests/webdavAutoUpload.test.ts
index a55a25c1e0..38bc4997cb 100644
--- a/packages/app-tests/webdavAutoUpload.test.ts
+++ b/packages/app-tests/webdavAutoUpload.test.ts
@@ -4,7 +4,8 @@ import { createPinia, setActivePinia } from "pinia";
import { useWebDavAutoUpload } from "@/composables/useWebDavAutoUpload";
import { readWebDavAutoUploadConfig } from "@/lib/webdav/webdavAutoUploadConfig";
-const { webdavSyncUploadMock } = vi.hoisted(() => ({
+const { webdavSyncSecretsStatusMock, webdavSyncUploadMock } = vi.hoisted(() => ({
+ webdavSyncSecretsStatusMock: vi.fn(),
webdavSyncUploadMock: vi.fn(),
}));
@@ -18,6 +19,7 @@ vi.mock("vue", async (importOriginal) => {
});
vi.mock("@/lib/backend/api", () => ({
+ webdavSyncSecretsStatus: webdavSyncSecretsStatusMock,
webdavSyncUpload: webdavSyncUploadMock,
}));
@@ -78,6 +80,7 @@ function installWindow() {
beforeEach(() => {
vi.useFakeTimers();
+ webdavSyncSecretsStatusMock.mockResolvedValue({ enabled: false, hasSavedPassphrase: false });
webdavSyncUploadMock.mockResolvedValue({ bytes: 42, remotePath: "DBX/sync/snapshot.json" });
restoreLocalStorage = installLocalStorage();
restoreWindow = installWindow();
@@ -125,6 +128,7 @@ test("keeps WebDAV auto-upload running outside the settings dialog", async () =>
username: undefined,
remotePath: "DBX/sync/snapshot.json",
});
+ assert.equal(webdavSyncUploadMock.mock.calls[0][3], false);
localStorage.setItem("dbx-webdav-auto-upload-enabled", "false");
window.dispatchEvent(new Event("dbx:webdav-auto-upload-config-changed"));
diff --git a/src-tauri/src/commands/cloud_sync.rs b/src-tauri/src/commands/cloud_sync.rs
index 47af23d96f..62ae9382c7 100644
--- a/src-tauri/src/commands/cloud_sync.rs
+++ b/src-tauri/src/commands/cloud_sync.rs
@@ -1,18 +1,19 @@
use std::sync::Arc;
use dbx_core::cloud_sync::{
- apply_sync_snapshot, build_sync_snapshot, build_sync_snapshot_with_saved_secrets, finalize_snippet_migration,
- forget_snippet_token, forget_webdav_password,
- forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase, resolve_snippet_token,
- resolve_webdav_password, resolve_webdav_sync_secrets_passphrase, retry_pending_snippet_cleanup,
- save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token, save_webdav_password,
- save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference, snippet_saved_token_status,
- snippet_sync_settings_for_instance as core_snippet_sync_settings, webdav_saved_password_status,
- webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions, ApplySnapshotSummary,
- SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings, SnippetSyncSummary, SnippetTokenStatus,
- WebDavClient, WebDavConfig, WebDavPasswordStatus, WebDavSyncSecretsStatus, WebDavSyncSummary,
+ apply_sync_snapshot, build_sync_snapshot_with_options, finalize_snippet_migration, forget_snippet_token,
+ forget_webdav_password, forget_webdav_sync_secrets_passphrase as core_forget_webdav_sync_secrets_passphrase,
+ resolve_snippet_token, resolve_webdav_password, resolve_webdav_sync_secrets_passphrase,
+ retry_pending_snippet_cleanup, save_snippet_sync_id_for_instance as core_save_snippet_sync_id, save_snippet_token,
+ save_webdav_password, save_webdav_sync_secrets_preference as core_save_webdav_sync_secrets_preference,
+ snippet_saved_token_status, snippet_sync_settings_for_instance as core_snippet_sync_settings,
+ webdav_saved_password_status, webdav_sync_secrets_status as core_webdav_sync_secrets_status, ApplySnapshotOptions,
+ ApplySnapshotSummary, SnippetProvider, SnippetSyncClient, SnippetSyncConfig, SnippetSyncSettings,
+ SnippetSyncSummary, SnippetTokenStatus, SyncExportOptions, WebDavClient, WebDavConfig, WebDavPasswordStatus,
+ WebDavSyncSecretsStatus, WebDavSyncSummary,
};
use dbx_core::storage::DesktopSettings;
+use dbx_core::storage::{MigrationPreflight, MigrationReport};
use serde::{Deserialize, Serialize};
use tauri::State;
@@ -36,6 +37,36 @@ pub struct SnippetDownloadResult {
pub apply_summary: ApplySnapshotSummary,
}
+#[tauri::command]
+pub async fn migration_status(state: State<'_, Arc<AppState>>) -> Result<MigrationPreflight, String> {
+ state.storage.inspect_data_migration().await
+}
+
+#[tauri::command]
+pub async fn migration_start(
+ state: State<'_, Arc<AppState>>,
+ gate: State<'_, Arc<crate::migration_gate::MigrationGate>>,
+) -> Result<MigrationReport, String> {
+ gate.set_ready(false);
+ let result = state.storage.start_data_migration().await;
+ let ready = state.storage.inspect_data_migration().await.map(|status| status.is_ready()).unwrap_or(false);
+ gate.set_ready(ready);
+ result
+}
+
+#[tauri::command]
+pub async fn migration_retry(
+ state: State<'_, Arc<AppState>>,
+ gate: State<'_, Arc<crate::migration_gate::MigrationGate>>,
+) -> Result<MigrationReport, String> {
+ migration_start(state, gate).await
+}
+
+#[tauri::command]
+pub async fn migration_cleanup_backups(state: State<'_, Arc<AppState>>) -> Result<(), String> {
+ state.storage.cleanup_migration_backups().await
+}
+
#[tauri::command]
pub async fn webdav_sync_test(state: State<'_, Arc<AppState>>, mut config: WebDavConfig) -> Result<(), String> {
resolve_webdav_password(&state.storage, &mut config).await?;
@@ -89,13 +120,30 @@ pub async fn webdav_sync_upload(
mut config: WebDavConfig,
editor_settings: Option<serde_json::Value>,
secrets_passphrase: Option<String>,
+ include_secrets: bool,
) -> Result<WebDavSyncSummary, String> {
resolve_webdav_password(&state.storage, &mut config).await?;
- let snapshot = build_sync_snapshot_with_saved_secrets(
+ let explicit_passphrase = secrets_passphrase.as_deref().and_then(|value| {
+ let value = value.trim();
+ (!value.is_empty()).then_some(value)
+ });
+ let saved_passphrase = if explicit_passphrase.is_none() {
+ resolve_webdav_sync_secrets_passphrase(&state.storage).await?
+ } else {
+ None
+ };
+ let passphrase = explicit_passphrase.or(saved_passphrase.as_deref());
+ let snapshot = build_sync_snapshot_with_options(
&state.storage,
env!("CARGO_PKG_VERSION"),
editor_settings,
- secrets_passphrase.as_deref(),
+ SyncExportOptions {
+ include_secrets,
+ sync_passphrase: passphrase,
+ include_ai_secrets: include_secrets,
+ include_tunnel_secrets: include_secrets,
+ include_plugin_secrets: include_secrets,
+ },
)
.await?;
WebDavClient::new(config).put_snapshot(&snapshot).await
@@ -106,6 +154,7 @@ pub async fn webdav_sync_download(
state: State<'_, Arc<AppState>>,
mut config: WebDavConfig,
secrets_passphrase: Option<String>,
+ restore_secrets: bool,
) -> Result<WebDavDownloadResult, String> {
resolve_webdav_password(&state.storage, &mut config).await?;
let (snapshot, summary) = WebDavClient::new(config).get_snapshot().await?;
@@ -120,7 +169,7 @@ pub async fn webdav_sync_download(
&snapshot,
ApplySnapshotOptions {
secrets_passphrase: explicit_passphrase.or(saved_passphrase.as_deref()),
- restore_secrets: true,
+ restore_secrets,
},
)
.await?;
@@ -214,8 +263,19 @@ pub async fn snippet_sync_upload(
} else {
None
};
- let snapshot =
- build_sync_snapshot(&state.storage, env!("CARGO_PKG_VERSION"), editor_settings, secrets_passphrase).await?;
+ let snapshot = build_sync_snapshot_with_options(
+ &state.storage,
+ env!("CARGO_PKG_VERSION"),
+ editor_settings,
+ SyncExportOptions {
+ include_secrets,
+ sync_passphrase: secrets_passphrase,
+ include_ai_secrets: include_secrets,
+ include_tunnel_secrets: include_secrets,
+ include_plugin_secrets: include_secrets,
+ },
+ )
+ .await?;
let client = SnippetSyncClient::new(config)?;
let mut summary = client.put_snapshot(&snapshot, snippet_passphrase.as_deref(), secrets_passphrase).await?;
finalize_snippet_migration(&state.storage, &client, &mut summary).await?;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0b4741e848..e94225f991 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -5,6 +5,7 @@ mod db;
mod macos_app_delegate;
#[cfg(target_os = "macos")]
mod macos_escape_guard;
+mod migration_gate;
mod models;
mod plugin_ui_protocol;
#[cfg(any(target_os = "windows", test))]
@@ -1577,15 +1578,19 @@ pub fn run() {
let t = Instant::now();
append_startup_probe(format!("opening storage file=dbx.db data_dir_mode={data_dir_mode}"));
let storage = tauri::async_runtime::block_on(async {
- let s = Storage::open(&db_path).await.expect("Failed to open storage");
+ let s = Storage::open_unmigrated(&db_path).await.expect("Failed to open storage");
eprintln!("[STARTUP] Storage::open in {:?}", t.elapsed());
append_startup_probe(format!("storage opened in {:?}", t.elapsed()));
let t2 = Instant::now();
- s.migrate_from_json(&data_dir).await.expect("Failed to migrate JSON data");
- eprintln!("[STARTUP] migrate_from_json in {:?}", t2.elapsed());
- append_startup_probe(format!("json migration completed in {:?}", t2.elapsed()));
+ eprintln!("[STARTUP] migration wizard deferred in {:?}", t2.elapsed());
+ append_startup_probe(format!("migration deferred to security wizard in {:?}", t2.elapsed()));
s
});
+ let migration_ready = tauri::async_runtime::block_on(storage.inspect_data_migration())
+ .map(|status| status.is_ready())
+ .unwrap_or(false);
+ let migration_gate = Arc::new(migration_gate::MigrationGate::new(migration_ready));
+ app.manage(migration_gate.clone());
let desktop_settings = tauri::async_runtime::block_on(storage.load_desktop_settings()).unwrap_or_default();
app.handle().plugin(
tauri_plugin_log::Builder::default()
@@ -1669,7 +1674,9 @@ pub fn run() {
let mcp_http_server = Arc::new(commands::mcp_http_server::McpHttpServerState::new(data_dir.clone()));
app.manage(mcp_http_server.clone());
let mcp_http_state = state.clone();
+ let mcp_gate = migration_gate.clone();
tauri::async_runtime::spawn(async move {
+ mcp_gate.wait().await;
commands::mcp_http_server::start_if_enabled(mcp_http_state, mcp_http_server).await;
});
app.manage(commands::redis_pubsub_server::start_pubsub_server(state.clone()));
@@ -1696,7 +1703,10 @@ pub fn run() {
open_plugin_install_deep_links(app.handle(), startup_plugin_install_links);
let app_handle = app.handle().clone();
- commands::mcp_bridge::start(app_handle, state, data_dir);
+ tauri::async_runtime::spawn(async move {
+ migration_gate.wait().await;
+ commands::mcp_bridge::start(app_handle, state, data_dir);
+ });
eprintln!("[STARTUP] setup complete in {:?} (total {:?})", setup_start.elapsed(), startup_begin.elapsed());
append_startup_probe(format!(
"setup tasks complete in {:?} total {:?}",
@@ -1760,7 +1770,7 @@ pub fn run() {
request_app_close(app, "settings");
}
})
- .invoke_handler(tauri::generate_handler![
+ .invoke_handler(migration_gate::guard_handler(tauri::generate_handler![
commands::ai::ai_complete,
commands::ai::ai_stream,
commands::ai::ai_agent_stream,
@@ -1840,6 +1850,10 @@ pub fn run() {
commands::diagnostics::get_process_memory_info,
commands::support_info::get_app_support_info,
commands::cloud_sync::webdav_sync_test,
+ commands::cloud_sync::migration_status,
+ commands::cloud_sync::migration_start,
+ commands::cloud_sync::migration_retry,
+ commands::cloud_sync::migration_cleanup_backups,
commands::cloud_sync::webdav_password_status,
commands::cloud_sync::save_webdav_saved_password,
commands::cloud_sync::forget_webdav_saved_password,
@@ -2661,7 +2675,7 @@ pub fn run() {
commands::tunnel_profiles::load_tunnel_profiles,
commands::tunnel_profiles::save_tunnel_profiles,
commands::tunnel_profiles::test_tunnel_profile,
- ])
+ ]))
.build(tauri::generate_context!())
.inspect(|app| {
append_startup_probe(format!("tauri application built after {:?}", startup_begin.elapsed()));
@@ -2778,7 +2792,13 @@ pub fn run() {
);
}
let app_handle = app_handle.clone();
+ let migration_gate =
+ app_handle.try_state::<Arc<migration_gate::MigrationGate>>().map(|state| state.inner().clone());
tauri::async_runtime::spawn(async move {
+ let Some(migration_gate) = migration_gate else {
+ return;
+ };
+ migration_gate.wait().await;
if let Some(state) = app_handle.try_state::<AppState>() {
state.refresh_connections().await;
}
@@ -2787,7 +2807,13 @@ pub fn run() {
if let RunEvent::Resumed = &event {
let app_handle = app_handle.clone();
+ let migration_gate =
+ app_handle.try_state::<Arc<migration_gate::MigrationGate>>().map(|state| state.inner().clone());
tauri::async_runtime::spawn(async move {
+ let Some(migration_gate) = migration_gate else {
+ return;
+ };
+ migration_gate.wait().await;
if let Some(state) = app_handle.try_state::<AppState>() {
state.refresh_connections().await;
}
diff --git a/src-tauri/src/migration_gate.rs b/src-tauri/src/migration_gate.rs
new file mode 100644
index 0000000000..051be0a537
--- /dev/null
+++ b/src-tauri/src/migration_gate.rs
@@ -0,0 +1,124 @@
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+
+pub struct MigrationGate {
+ ready: AtomicBool,
+ changed: tokio::sync::Notify,
+}
+impl MigrationGate {
+ pub fn new(ready: bool) -> Self {
+ Self { ready: AtomicBool::new(ready), changed: tokio::sync::Notify::new() }
+ }
+ pub fn is_ready(&self) -> bool {
+ self.ready.load(Ordering::Acquire)
+ }
+ pub fn set_ready(&self, ready: bool) {
+ self.ready.store(ready, Ordering::Release);
+ self.changed.notify_waiters();
+ }
+ pub async fn wait(&self) {
+ loop {
+ let notified = self.changed.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ if self.is_ready() {
+ return;
+ }
+ notified.await;
+ }
+ }
+}
+pub fn allowed_command(command: &str) -> bool {
+ matches!(
+ command,
+ "migration_status"
+ | "migration_start"
+ | "migration_retry"
+ | "migration_cleanup_backups"
+ | "mark_frontend_ready"
+ | "show_main_window"
+ | "quit_app"
+ | "confirm_exit"
+ | "complete_app_close"
+ | "reveal_path_in_file_manager"
+ | "get_platform"
+ | "set_app_locale"
+ )
+}
+/// Wrap the actual invoke dispatcher so direct IPC calls cannot bypass the startup UI.
+/// Missing state is denied as well: no business command can run before setup completes.
+pub fn guard_handler<R: tauri::Runtime>(
+ handler: impl Fn(tauri::ipc::Invoke<R>) -> bool + Send + Sync + 'static,
+) -> impl Fn(tauri::ipc::Invoke<R>) -> bool + Send + Sync + 'static {
+ move |invoke| {
+ let ready = invoke.message.state_ref().try_get::<Arc<MigrationGate>>().is_some_and(|gate| gate.is_ready());
+ if !ready && !allowed_command(invoke.message.command()) {
+ invoke.resolver.reject("DATA_MIGRATION_REQUIRED");
+ return true;
+ }
+ handler(invoke)
+ }
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn gate_denies_business_commands() {
+ for command in ["load_connections", "webdav_sync_upload", "load_ai_config", "plugin_invoke", "migration_fake"] {
+ assert!(!allowed_command(command));
+ }
+ assert!(allowed_command("migration_start"));
+ assert!(allowed_command("reveal_path_in_file_manager"));
+ }
+ #[test]
+ fn invoke_dispatch_rejects_business_commands_until_ready() {
+ use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets};
+ let gate = Arc::new(MigrationGate::new(false));
+ let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let command_calls = calls.clone();
+ let app = mock_builder()
+ .manage(gate.clone())
+ .invoke_handler(guard_handler(move |invoke| {
+ command_calls.fetch_add(1, Ordering::SeqCst);
+ invoke.resolver.resolve("dispatched");
+ true
+ }))
+ .build(mock_context(noop_assets()))
+ .unwrap();
+ let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()).build().unwrap();
+ let request = |command: &str| tauri::webview::InvokeRequest {
+ cmd: command.into(),
+ callback: tauri::ipc::CallbackFn(0),
+ error: tauri::ipc::CallbackFn(1),
+ url: if cfg!(windows) { "http://tauri.localhost" } else { "tauri://localhost" }.parse().unwrap(),
+ body: tauri::ipc::InvokeBody::default(),
+ headers: Default::default(),
+ invoke_key: tauri::test::INVOKE_KEY.into(),
+ };
+ for command in ["load_connections", "plugin_invoke", "webdav_sync_upload"] {
+ assert_eq!(
+ get_ipc_response(&webview, request(command)).unwrap_err(),
+ serde_json::json!("DATA_MIGRATION_REQUIRED")
+ );
+ }
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ assert!(get_ipc_response(&webview, request("migration_status")).is_ok());
+ // Cleanup is guarded by the storage layer (it only succeeds after a
+ // successful migration), so the startup gate must allow the command
+ // through while the wizard is still visible.
+ assert!(get_ipc_response(&webview, request("migration_cleanup_backups")).is_ok());
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ gate.set_ready(true);
+ assert!(get_ipc_response(&webview, request("load_connections")).is_ok());
+ assert_eq!(calls.load(Ordering::SeqCst), 3);
+ }
+ #[tokio::test]
+ async fn wait_releases_only_after_ready() {
+ let gate = MigrationGate::new(false);
+ assert!(!gate.is_ready());
+ gate.set_ready(true);
+ gate.wait().await;
+ }
+}