Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(keyvault): Windows DPAPI, Firefox and Electron secret items (#4463)

ddupontcb685fad7aef
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 34c44cf5a8..47f6f85262 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -29,6 +39,20 @@ dependencies = [
"cpufeatures 0.2.17",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -827,7 +851,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -1085,6 +1109,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1138,6 +1163,15 @@ version = "0.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -1206,9 +1240,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -1710,6 +1747,8 @@ dependencies = [
"serde_json",
"sha1",
"sha2 0.10.9",
+ "snap",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -1721,7 +1760,11 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc",
+ "des",
+ "hmac",
"pbkdf2",
"serde",
"serde_json",
@@ -2047,6 +2090,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -2753,6 +2805,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "gio"
version = "0.18.4"
@@ -4453,6 +4515,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -4812,7 +4880,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -7486,6 +7566,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"
diff --git a/apps/cua-spaces/src-tauri/src/window_drag.rs b/apps/cua-spaces/src-tauri/src/window_drag.rs
index f151d17565..86444617b0 100644
--- a/apps/cua-spaces/src-tauri/src/window_drag.rs
+++ b/apps/cua-spaces/src-tauri/src/window_drag.rs
@@ -316,7 +316,8 @@ mod tests {
assert_eq!(json["windowId"], 42);
assert_eq!(json["appId"], "vscode");
assert_eq!(json["supported"], true);
- assert_eq!(json["capability"], "install_only");
+ // VS Code is Chromium underneath, so its signed-in state teleports too.
+ assert_eq!(json["capability"], "full");
assert_eq!(json["entry"]["launch"]["bin"], "code");
// The frames at mouse down and now, for the core's move/resize test.
assert_eq!(json["startFrame"]["x"], 100.0);
diff --git a/apps/cua-spaces/src-tauri/tests/teleport_app.rs b/apps/cua-spaces/src-tauri/tests/teleport_app.rs
index 4001b79075..bf6f278e9d 100644
--- a/apps/cua-spaces/src-tauri/tests/teleport_app.rs
+++ b/apps/cua-spaces/src-tauri/tests/teleport_app.rs
@@ -42,7 +42,8 @@ async fn the_catalog_classifies_fixture_apps_and_dropped_bundles() {
rows,
[
("firefox", "full"),
- ("vscode", "install_only"),
+ // VS Code is Chromium underneath, so its signed-in state teleports too.
+ ("vscode", "full"),
("com.example.paint", "unsupported")
]
);
diff --git a/docs/content/docs/spaces/guides/keyvault.mdx b/docs/content/docs/spaces/guides/keyvault.mdx
index ec69b76a38..dba9e4d94f 100644
--- a/docs/content/docs/spaces/guides/keyvault.mdx
+++ b/docs/content/docs/spaces/guides/keyvault.mdx
@@ -107,7 +107,9 @@ only used through site login.
## What is an item and what stays a file
-For Chrome and the other Chromium browsers each of these is its own item:
+For Chrome and the other Chromium browsers, for Firefox, and for Chromium-based
+desktop apps (Slack, Discord, Visual Studio Code, Notion) each of these is its
+own item:
- every cookie, with every attribute the browser keeps (creation and update
times, priority, source scheme and port, same-site, a partitioned cookie's
@@ -115,17 +117,25 @@ For Chrome and the other Chromium browsers each of these is its own item:
item from the same name without a partition;
- every localStorage value, read from the browser's own store and written back
into the Space's while its browser is not running;
-- saved passwords, as above.
+- saved passwords, only when you tick them in the review (never by default).
-On Windows, Chrome's app-bound encryption keeps a cookie or password readable
-only by Chrome itself. Those are listed in the review, greyed, with that reason,
-and are never sent; the rest of the site still is.
+A Chromium app's cookies and passwords decrypt the same way on macOS, Linux and
+Windows: macOS through the app's own Keychain item, Linux through its fixed or
+keyring-backed key, Windows through the key `Local State` keeps, itself
+protected by Windows DPAPI for your account. Firefox's cookies and localStorage
+are never encrypted at rest; its saved passwords decrypt with the profile's own
+`key4.db` master key, and a profile protected by a Firefox master password is
+refused rather than guessed at.
+
+Chrome's Windows app-bound encryption (`v20`, Chrome 127+) keeps a cookie or
+password readable only by Chrome itself. Those are listed in the review,
+greyed, with that reason, and are never sent; the rest of the site still is.
Everything else is saved as a file, by its path: preferences, bookmarks, the
-open tabs and session state, session storage, extensions and, for Electron
-apps such as Slack, their own cookie and localStorage files. A cookie or value
-that cannot be read as an item is not silently dropped: it stays a file or is
-listed as unavailable.
+open tabs and session state, session storage, extensions, history and, for
+Firefox, everything under its profile that is not cookies, localStorage or
+logins. A cookie or value that cannot be read as an item is not silently
+dropped: it stays a file or is listed as unavailable.
## Saved sessions (cookies)
diff --git a/docs/content/docs/spaces/guides/teleport-an-app.mdx b/docs/content/docs/spaces/guides/teleport-an-app.mdx
index 446e9d8d36..e8ef994e8d 100644
--- a/docs/content/docs/spaces/guides/teleport-an-app.mdx
+++ b/docs/content/docs/spaces/guides/teleport-an-app.mdx
@@ -15,8 +15,8 @@ teleport can do with each one in a Space:
| Install only | the app is installed from the pinned, checksum-verified install manifest, and opens empty or with your files | the app; the app with files |
| Unsupported | shown disabled, with the reason (for example "not published for aarch64 Linux") | nothing |
-Full today: `firefox`, `chrome`, `slack`, `discord`, `unity-hub`, `steam`,
-`whatsapp` (macOS) and `claude-code`. Install only: Visual Studio Code and
+Full today: `firefox`, `chrome`, `slack`, `discord`, `vscode`, `notion`,
+`unity-hub`, `steam`, `whatsapp` (macOS) and `claude-code`. Install only:
Blender (x86_64). Apps come from `/Applications` and `~/Applications` on
macOS, `.desktop` entries on Linux and the Start Menu on Windows.
@@ -40,14 +40,19 @@ key; the Space re-encrypts them under its own Safe Storage key before Chrome
ever reads them. The source's key never leaves this Mac.
<Callout type="warn">
-**Saved passwords** here still moves Chrome's `Login Data` as an encrypted
+For Chrome, **Saved passwords** here still moves `Login Data` as an encrypted
file, which only a Chrome that already shares this Mac's Safe Storage key can
read -- a Space's Chrome does not, so a password moved this way does not yet
-decrypt there. To actually sign in with a saved password, use the
+decrypt there. (For Firefox, **Saved passwords** decrypts here with the
+profile's own `key4.db` master key and re-encrypts under the destination
+profile's own key, the same way as **Keep me signed in**, so it does decrypt
+there -- unless a master password is set, which is refused rather than
+guessed at.) To actually sign in with a saved Chrome password, use the
[Keyvault](/spaces/guides/keyvault) (`cua keyvault import-passwords`)
instead: it decrypts on import and signs in through [site
login](/spaces/guides/site-login), without ever exposing the password to an
-agent. **Keep me signed in** (cookies) does not have this limitation.
+agent. **Keep me signed in** (cookies) does not have this limitation on
+either browser.
</Callout>
### Choosing sites and sending from the Keyvault
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index 21d41105db..65252f8d34 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -40,6 +50,20 @@ dependencies = [
"cpufeatures 0.3.1",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes 0.8.4",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -898,7 +922,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -1280,6 +1304,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1294,6 +1319,15 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -1310,9 +1344,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -1784,6 +1821,7 @@ dependencies = [
"serde_json",
"sha2 0.10.9",
"tempfile",
+ "zeroize",
]
[[package]]
@@ -1815,7 +1853,11 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes 0.8.4",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc 0.1.2",
+ "des",
+ "hmac 0.12.1",
"pbkdf2",
"serde",
"serde_json",
@@ -1916,6 +1958,15 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -2551,6 +2602,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "glob"
version = "0.3.4"
@@ -4034,6 +4095,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openh264"
version = "0.9.8"
@@ -4479,7 +4546,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -6435,6 +6514,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml b/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
index 057ec03a0e..1fb11259bd 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
@@ -24,6 +24,7 @@ sha2.workspace = true
# cookies (`cookies.rs`): never the source's key, always a fresh one this
# guest generates for itself.
rand.workspace = true
+zeroize = "1"
# Writing the destination's real `Cookies` database (`cookies.rs`).
rusqlite = { version = "0.40.1", default-features = false, features = ["bundled"] }
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
index 499d9ab003..05fe451db8 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
@@ -204,17 +204,98 @@ pub fn install_cookies(
items: &[CookieItem],
record: &mut ImportRecord,
) -> Result<usize> {
- if items.is_empty() {
- return Ok(0);
+ install_cookies_with(
+ host,
+ profile_dir,
+ &default_local_state(profile_dir),
+ service,
+ platform,
+ &cua_chromium_storage::dpapi::SystemDpapi,
+ items,
+ record,
+ )
+}
+
+/// `Local State` for a browser profile: in its `User Data` parent (`Default`
+/// lives inside it). An Electron app passes its own userData instead.
+pub fn default_local_state(profile_dir: &Path) -> std::path::PathBuf {
+ profile_dir
+ .parent()
+ .unwrap_or(profile_dir)
+ .join("Local State")
+}
+
+/// How values are encrypted for the destination: AES-128-CBC under the
+/// Safe Storage key (macOS, Linux) or AES-256-GCM under the `Local State` key
+/// (Windows).
+pub(crate) enum DestCipher {
+ Cbc(zeroize::Zeroizing<[u8; 16]>),
+ Gcm(zeroize::Zeroizing<[u8; 32]>),
+}
+
+impl DestCipher {
+ /// One value, with the `v10` prefix Chromium stores.
+ pub(crate) fn encrypt(&self, plain: &[u8]) -> Vec<u8> {
+ match self {
+ DestCipher::Cbc(k) => chromium_crypto::encrypt_v10(k, plain),
+ DestCipher::Gcm(k) => {
+ let mut nonce = [0u8; 12];
+ rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut nonce);
+ chromium_crypto::gcm::encrypt(k, &nonce, plain)
+ }
+ }
}
+}
+
+/// The destination's own cipher: the Safe Storage key (created on first use)
+/// on macOS and Linux, the `Local State` key (created and wrapped with DPAPI
+/// on first use) on Windows. Never the source's.
+pub(crate) fn destination_cipher(
+ host: &dyn HostEffects,
+ local_state: &Path,
+ service: &'static str,
+ platform: Platform,
+ dpapi: &dyn cua_chromium_storage::dpapi::Dpapi,
+ record: &mut ImportRecord,
+) -> Result<DestCipher> {
if platform == Platform::Windows {
- return Err(TeleportError::Provider(
- "re-encrypting cookies for a Windows destination (DPAPI) is not supported yet".into(),
- ));
+ let existed = local_state.is_file();
+ let mut random = [0u8; 32];
+ rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut random);
+ let (key, created) =
+ cua_chromium_storage::dpapi::ensure_local_state_key(local_state, dpapi, random)
+ .map_err(|e| TeleportError::Provider(format!("Windows browser key: {e}")))?;
+ if created && !existed {
+ // A Local State this import made goes with it on wipe.
+ record.file_written(local_state);
+ }
+ return Ok(DestCipher::Gcm(key));
}
let secret = ensure_safe_storage_secret(host, platform, service, record)
.map_err(|e| TeleportError::Provider(format!("Safe Storage key for {service}: {e}")))?;
- let key = chromium_crypto::derive_key(&secret, pbkdf2_rounds_for(platform));
+ Ok(DestCipher::Cbc(chromium_crypto::derive_key(
+ &secret,
+ pbkdf2_rounds_for(platform),
+ )))
+}
+
+/// [`install_cookies`] with an explicit `Local State` and DPAPI (Electron apps
+/// keep their `Local State` in their userData; tests inject a fake DPAPI).
+#[allow(clippy::too_many_arguments)]
+pub fn install_cookies_with(
+ host: &dyn HostEffects,
+ profile_dir: &Path,
+ local_state: &Path,
+ service: &'static str,
+ platform: Platform,
+ dpapi: &dyn cua_chromium_storage::dpapi::Dpapi,
+ items: &[CookieItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
+ if items.is_empty() {
+ return Ok(0);
+ }
+ let key = destination_cipher(host, local_state, service, platform, dpapi, record)?;
// Which file Chrome reads depends on its version (see
// [`cookies_db_paths`]), and the destination's Chrome may not have run
// yet, so write every location it could use. The unused copy is inert.
@@ -229,7 +310,7 @@ pub fn install_cookies(
/// (created first when absent). Returns how many rows were written.
fn install_into_db(
db: &Path,
- key: &[u8; 16],
+ key: &DestCipher,
items: &[CookieItem],
record: &mut ImportRecord,
) -> Result<usize> {
@@ -275,7 +356,7 @@ fn install_into_db(
let mut written = 0usize;
for item in items {
let plain = plaintext_for(digest_values, &item.host_key, &item.value);
- let encrypted = chromium_crypto::encrypt_v10(key, &plain);
+ let encrypted = key.encrypt(&plain);
let mut args: Vec<rusqlite::types::Value> = Vec::with_capacity(columns.len());
for column in &columns {
args.push(match *column {
@@ -877,4 +958,42 @@ mod tests {
);
assert_eq!(account_for_service("Weird"), "Weird");
}
+
+ /// A Windows destination: cookies are AES-256-GCM (with the host digest)
+ /// under the destination's Local State key, never the source's.
+ #[test]
+ fn a_windows_destination_gets_aes_gcm_cookies_under_its_own_local_state_key() {
+ use cua_chromium_storage::dpapi::{local_state_key, FakeDpapi};
+ use sha2::{Digest, Sha256};
+ let home = tempfile::tempdir().unwrap();
+ let user_data = home.path().join("User Data");
+ let profile = user_data.join("Default");
+ let local_state = user_data.join("Local State");
+ let mut record = ImportRecord::default();
+ let n = install_cookies_with(
+ &FakeHost::new(),
+ &profile,
+ &local_state,
+ "Chrome Safe Storage",
+ Platform::Windows,
+ &FakeDpapi,
+ &[item(".github.com", "user_session", "gh-win")],
+ &mut record,
+ )
+ .unwrap();
+ assert_eq!(n, 1);
+ let conn = rusqlite::Connection::open(profile.join("Network/Cookies")).unwrap();
+ let enc: Vec<u8> = conn
+ .query_row(
+ "SELECT encrypted_value FROM cookies WHERE name = 'user_session'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let key = local_state_key(&local_state, &FakeDpapi).unwrap();
+ let plain = chromium_crypto::gcm::decrypt(&key, &enc).unwrap();
+ assert_eq!(&plain[..32], Sha256::digest(b".github.com").as_slice());
+ assert_eq!(&plain[32..], b"gh-win");
+ assert!(record.files.contains(&local_state));
+ }
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/firefox_items.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/firefox_items.rs
new file mode 100644
index 0000000000..3a6b36c538
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/firefox_items.rs
@@ -0,0 +1,461 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Installing Keyvault items into a Firefox profile: cookies into
+//! `cookies.sqlite` (`moz_cookies`, schema 16), localStorage into
+//! `storage/default/<origin>/ls/data.sqlite`, saved logins into `logins.json`
+//! encrypted under the profile's own `key4.db` master key. Formats:
+//! `~/projects/.cua-work/keyvault-v2/browser-formats.md`.
+//!
+//! The destination Firefox is not running (the import launches it after).
+
+use std::path::Path;
+
+use cua_teleport_bundle::cookies::CookieItem;
+use cua_teleport_bundle::local_storage::LocalStorageItem;
+use cua_teleport_bundle::logins::LoginItem;
+
+use crate::ledger::ImportRecord;
+use crate::{Result, TeleportError};
+
+const CHROME_EPOCH_OFFSET_MICROS: i64 = 11_644_473_600_000_000;
+const COOKIES_SCHEMA_VERSION: i64 = 16;
+
+fn perr(m: impl std::fmt::Display) -> TeleportError {
+ TeleportError::Provider(m.to_string())
+}
+
+/// `https://top.example` as the `originAttributes` Firefox keys a partitioned
+/// cookie by (`^partitionKey=%28https%2Ctop.example%29`).
+fn origin_attributes(partition: Option<&str>) -> String {
+ let Some(p) = partition.filter(|p| !p.is_empty()) else {
+ return String::new();
+ };
+ match p.split_once("://") {
+ Some((scheme, host)) => format!("^partitionKey=%28{scheme}%2C{host}%29"),
+ None => String::new(),
+ }
+}
+
+/// Cookies into `profile/cookies.sqlite` (created at schema 16 when missing).
+pub fn install_cookies(
+ profile: &Path,
+ items: &[CookieItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
+ if items.is_empty() {
+ return Ok(0);
+ }
+ let db = profile.join("cookies.sqlite");
+ let existed = db.is_file();
+ std::fs::create_dir_all(profile).map_err(perr)?;
+ let conn = rusqlite::Connection::open(&db)
+ .map_err(|e| perr(format!("opening cookies.sqlite: {e}")))?;
+ conn.execute_batch(&format!(
+ "PRAGMA user_version = {COOKIES_SCHEMA_VERSION};
+ CREATE TABLE IF NOT EXISTS moz_cookies (id INTEGER PRIMARY KEY, originAttributes TEXT NOT NULL DEFAULT '',
+ name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER,
+ creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, inBrowserElement INTEGER DEFAULT 0,
+ sameSite INTEGER DEFAULT 0, schemeMap INTEGER DEFAULT 0, isPartitionedAttributeSet INTEGER DEFAULT 0,
+ CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes));"
+ ))
+ .map_err(|e| perr(format!("creating moz_cookies: {e}")))?;
+ if !existed {
+ record.file_written(&db);
+ }
+ let now_us = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_micros() as i64)
+ .unwrap_or(0);
+ let mut stmt = conn
+ .prepare(
+ "INSERT OR REPLACE INTO moz_cookies (originAttributes, name, value, host, path, expiry,
+ lastAccessed, creationTime, isSecure, isHttpOnly, sameSite, schemeMap, isPartitionedAttributeSet)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
+ )
+ .map_err(perr)?;
+ let mut n = 0;
+ for c in items {
+ let attrs = origin_attributes(c.extra.partition_key.as_deref());
+ let micros = |chrome: Option<i64>| {
+ chrome
+ .filter(|v| *v > CHROME_EPOCH_OFFSET_MICROS)
+ .map(|v| v - CHROME_EPOCH_OFFSET_MICROS)
+ .unwrap_or(now_us)
+ };
+ // Chromium's microseconds since 1601 to Firefox's milliseconds since
+ // 1970; a session cookie (0) stays 0 and Firefox treats it as one.
+ let expiry_ms = if c.expires_utc > CHROME_EPOCH_OFFSET_MICROS {
+ (c.expires_utc - CHROME_EPOCH_OFFSET_MICROS) / 1000
+ } else {
+ 0
+ };
+ stmt.execute(rusqlite::params![
+ attrs,
+ c.name,
+ String::from_utf8_lossy(&c.value),
+ c.host_key,
+ c.path,
+ expiry_ms,
+ micros(c.extra.last_access_utc),
+ micros(c.extra.creation_utc),
+ c.is_secure as i64,
+ c.is_httponly as i64,
+ c.samesite.clamp(0, 2),
+ if c.is_secure { 2 } else { 1 },
+ (!attrs.is_empty()) as i64,
+ ])
+ .map_err(|e| perr(format!("writing a cookie: {e}")))?;
+ record.cookie_row_written(&db, &c.host_key, &c.name, &c.path);
+ n += 1;
+ }
+ Ok(n)
+}
+
+/// `https://a.example:8443` as Firefox's `storage/default` directory name.
+fn origin_dir(origin: &str) -> String {
+ match origin.split_once("://") {
+ Some((scheme, rest)) => format!("{scheme}+++{}", rest.replace(':', "+")),
+ None => origin.to_string(),
+ }
+}
+
+/// localStorage into `profile/storage/default/<origin>/ls/data.sqlite`. Values
+/// are written UTF-8, uncompressed (a form Firefox reads as it does its own).
+pub fn install_local_storage(
+ profile: &Path,
+ items: &[LocalStorageItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
+ let mut by_origin: std::collections::BTreeMap<&str, Vec<&LocalStorageItem>> =
+ Default::default();
+ for i in items {
+ by_origin.entry(i.origin.as_str()).or_default().push(i);
+ }
+ let mut n = 0;
+ for (origin, rows) in by_origin {
+ let dir = profile
+ .join("storage/default")
+ .join(origin_dir(origin))
+ .join("ls");
+ record.create_dir_all(&dir)?;
+ let db = dir.join("data.sqlite");
+ let existed = db.is_file();
+ let conn = rusqlite::Connection::open(&db)
+ .map_err(|e| perr(format!("opening data.sqlite: {e}")))?;
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS database (origin TEXT NOT NULL, usage INTEGER NOT NULL DEFAULT 0,
+ last_vacuum_time INTEGER NOT NULL DEFAULT 0, last_analyze_time INTEGER NOT NULL DEFAULT 0,
+ last_vacuum_size INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE IF NOT EXISTS data (key TEXT PRIMARY KEY, utf16_length INTEGER NOT NULL,
+ conversion_type INTEGER NOT NULL, compression_type INTEGER NOT NULL,
+ last_access_time INTEGER NOT NULL DEFAULT 0, value BLOB NOT NULL);",
+ )
+ .map_err(perr)?;
+ if !existed {
+ record.file_written(&db);
+ conn.execute("INSERT INTO database (origin) VALUES (?1)", [origin])
+ .map_err(perr)?;
+ }
+ let mut usage = 0i64;
+ for r in rows {
+ usage += (r.key.len() + r.value.len()) as i64;
+ conn.execute(
+ "INSERT OR REPLACE INTO data (key, utf16_length, conversion_type, compression_type, value)
+ VALUES (?1, ?2, 1, 0, ?3)",
+ rusqlite::params![r.key, r.value.encode_utf16().count() as i64, r.value.as_bytes()],
+ )
+ .map_err(perr)?;
+ n += 1;
+ }
+ conn.execute("UPDATE database SET usage = usage + ?1", [usage])
+ .map_err(perr)?;
+ }
+ Ok(n)
+}
+
+fn uuid(rng: &mut impl rand::RngCore) -> String {
+ let mut b = [0u8; 16];
+ rng.fill_bytes(&mut b);
+ b[6] = (b[6] & 0x0f) | 0x40;
+ b[8] = (b[8] & 0x3f) | 0x80;
+ let h = hex::encode(b);
+ format!(
+ "{{{}-{}-{}-{}-{}}}",
+ &h[..8],
+ &h[8..12],
+ &h[12..16],
+ &h[16..20],
+ &h[20..]
+ )
+}
+
+/// Saved logins into `profile/logins.json`, encrypted under the profile's own
+/// `key4.db` master key (empty master password). A profile with no `key4.db`
+/// yet, or with a master password, gets a notice and the logins wait: nothing
+/// is guessed and nothing is written.
+pub fn install_logins(
+ profile: &Path,
+ items: &[LoginItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
+ if items.is_empty() {
+ return Ok(0);
+ }
+ let Some(master) = master_key(profile)? else {
+ record.notices.push(
+ "Saved passwords were not sent: Firefox here has no password key yet. Open it once in \
+ this Space, then send the passwords again."
+ .into(),
+ );
+ return Ok(0);
+ };
+ let key_id = key_id(profile).unwrap_or_else(|| vec![0xf8; 16]);
+ let path = profile.join("logins.json");
+ let existed = path.is_file();
+ let mut doc: serde_json::Value = std::fs::read(&path)
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_else(|| serde_json::json!({"nextId": 1, "logins": [], "version": 3}));
+ let mut next = doc["nextId"].as_i64().unwrap_or(1);
+ let now_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(0);
+ let mut rng = rand::thread_rng();
+ let mut n = 0;
+ for l in items {
+ let mut iv = [0u8; 8];
+ rand::RngCore::fill_bytes(&mut rng, &mut iv);
+ let user = cua_teleport_bundle::firefox_nss::encrypt_sdr(
+ &master,
+ &key_id,
+ &iv,
+ l.username.as_bytes(),
+ )
+ .map_err(perr)?;
+ rand::RngCore::fill_bytes(&mut rng, &mut iv);
+ let pass =
+ cua_teleport_bundle::firefox_nss::encrypt_sdr(&master, &key_id, &iv, &l.password)
+ .map_err(perr)?;
+ let entry = serde_json::json!({
+ "id": next, "hostname": l.origin, "httpRealm": null, "formSubmitURL": l.origin,
+ "usernameField": "", "passwordField": "",
+ "encryptedUsername": user, "encryptedPassword": pass,
+ "guid": uuid(&mut rng), "encType": 1,
+ "timeCreated": now_ms, "timeLastUsed": now_ms, "timePasswordChanged": now_ms, "timesUsed": 1
+ });
+ next += 1;
+ if let Some(arr) = doc["logins"].as_array_mut() {
+ arr.push(entry);
+ }
+ n += 1;
+ }
+ doc["nextId"] = serde_json::json!(next);
+ std::fs::write(&path, serde_json::to_vec(&doc).map_err(perr)?).map_err(perr)?;
+ if !existed {
+ record.file_written(&path);
+ }
+ Ok(n)
+}
+
+fn open_key4(profile: &Path) -> Option<rusqlite::Connection> {
+ let p = profile.join("key4.db");
+ p.is_file().then(|| {
+ rusqlite::Connection::open_with_flags(p, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).ok()
+ })?
+}
+
+fn key_id(profile: &Path) -> Option<Vec<u8>> {
+ open_key4(profile)?
+ .query_row(
+ "SELECT a102 FROM nssPrivate WHERE a102 IS NOT NULL LIMIT 1",
+ [],
+ |r| r.get(0),
+ )
+ .ok()
+}
+
+/// The profile's login master key, `None` when it has no `key4.db`.
+fn master_key(profile: &Path) -> Result<Option<zeroize::Zeroizing<Vec<u8>>>> {
+ let Some(conn) = open_key4(profile) else {
+ return Ok(None);
+ };
+ let (salt, item2): (Vec<u8>, Vec<u8>) = conn
+ .query_row(
+ "SELECT item1, item2 FROM metaData WHERE id = 'password'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .map_err(|e| perr(format!("Firefox key4.db has no password entry: {e}")))?;
+ let a11: Vec<u8> = conn
+ .query_row(
+ "SELECT a11 FROM nssPrivate WHERE a11 IS NOT NULL LIMIT 1",
+ [],
+ |r| r.get(0),
+ )
+ .map_err(|e| perr(format!("Firefox key4.db has no login key: {e}")))?;
+ cua_teleport_bundle::firefox_nss::master_key(&salt, &item2, &a11, b"")
+ .map(Some)
+ .map_err(|e| perr(e.to_string()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_teleport_bundle::cookies::CookieExtra;
+ use cua_teleport_bundle::firefox_nss::testing as nss;
+
+ const MASTER: [u8; 24] = *b"0123456789abcdef01234567";
+
+ fn cookie(host: &str, name: &str, value: &str, partition: Option<&str>) -> CookieItem {
+ CookieItem {
+ host_key: host.into(),
+ name: name.into(),
+ value: value.as_bytes().to_vec(),
+ path: "/".into(),
+ expires_utc: 1_900_000_000_000 * 1000 + CHROME_EPOCH_OFFSET_MICROS,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ extra: CookieExtra {
+ creation_utc: Some(1_690_000_000_000_000 + CHROME_EPOCH_OFFSET_MICROS),
+ partition_key: partition.map(str::to_string),
+ ..Default::default()
+ },
+ }
+ }
+
+ #[test]
+ fn cookies_land_in_moz_cookies_with_units_and_partition_and_wipe_by_row() {
+ let home = tempfile::tempdir().unwrap();
+ let profile = home.path().join("Profiles/cua.default-release");
+ let mut record = ImportRecord::default();
+ let n = install_cookies(
+ &profile,
+ &[
+ cookie(".github.com", "user_session", "abc", None),
+ cookie("example.com", "sid", "p", Some("https://top.example")),
+ ],
+ &mut record,
+ )
+ .unwrap();
+ assert_eq!(n, 2);
+ let conn = rusqlite::Connection::open(profile.join("cookies.sqlite")).unwrap();
+ let (expiry, attrs, partitioned, created): (i64, String, i64, i64) = conn
+ .query_row(
+ "SELECT expiry, originAttributes, isPartitionedAttributeSet, creationTime FROM moz_cookies WHERE name = 'sid'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(expiry, 1_900_000_000_000, "milliseconds since 1970");
+ assert_eq!(attrs, "^partitionKey=%28https%2Ctop.example%29");
+ assert_eq!(partitioned, 1);
+ assert_eq!(created, 1_690_000_000_000_000, "microseconds since 1970");
+ let version: i64 = conn
+ .query_row("PRAGMA user_version", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(version, 16);
+ // Windows cannot delete a file a live connection still holds open.
+ drop(conn);
+ // Wipe deletes exactly those rows (the file was ours, so it goes too).
+ let ledger = crate::ledger::Ledger::new("i", "firefox", &record, 0, 1);
+ let report = crate::ledger::wipe(&ledger, home.path(), &crate::host::FakeHost::new());
+ assert!(report.complete(), "{:?}", report.errors);
+ assert!(!profile.join("cookies.sqlite").exists());
+ }
+
+ #[test]
+ fn local_storage_lands_in_the_origins_ls_database() {
+ let home = tempfile::tempdir().unwrap();
+ let profile = home.path().join("p");
+ let mut record = ImportRecord::default();
+ let items = [LocalStorageItem {
+ origin: "https://app.example:8443".into(),
+ key: "token".into(),
+ value: "caf\u{e9}".into(),
+ key_raw: None,
+ value_raw: None,
+ }];
+ assert_eq!(
+ install_local_storage(&profile, &items, &mut record).unwrap(),
+ 1
+ );
+ let db = profile.join("storage/default/https+++app.example+8443/ls/data.sqlite");
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ let (v, conv): (Vec<u8>, i64) = conn
+ .query_row(
+ "SELECT value, conversion_type FROM data WHERE key = 'token'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!((v.as_slice(), conv), ("caf\u{e9}".as_bytes(), 1));
+ let origin: String = conn
+ .query_row("SELECT origin FROM database", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(origin, "https://app.example:8443");
+ assert!(record.files.contains(&db));
+ }
+
+ #[test]
+ fn logins_are_encrypted_under_the_profiles_own_master_key_or_wait_with_a_notice() {
+ let profile = tempfile::tempdir().unwrap();
+ // No key4.db yet: a notice, nothing written.
+ let mut record = ImportRecord::default();
+ let login = LoginItem {
+ origin: "https://github.com".into(),
+ username: "octo".into(),
+ password: b"gh-pw".to_vec(),
+ signon_realm: "https://github.com/".into(),
+ };
+ assert_eq!(
+ install_logins(profile.path(), std::slice::from_ref(&login), &mut record).unwrap(),
+ 0
+ );
+ assert!(record.notices[0].contains("Open it once"));
+ assert!(!profile.path().join("logins.json").exists());
+ // With its own key4.db the login is written and reads back.
+ let (salt, item2, a11) = nss::key4_blobs(&MASTER, b"", true);
+ let conn = rusqlite::Connection::open(profile.path().join("key4.db")).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE metaData (id PRIMARY KEY, item1, item2); CREATE TABLE nssPrivate (id INTEGER PRIMARY KEY, a11, a102);",
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO metaData VALUES ('password', ?1, ?2)",
+ rusqlite::params![salt, item2],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO nssPrivate (a11, a102) VALUES (?1, ?2)",
+ rusqlite::params![a11, vec![0xf8u8; 16]],
+ )
+ .unwrap();
+ drop(conn);
+ let mut record = ImportRecord::default();
+ assert_eq!(
+ install_logins(profile.path(), &[login], &mut record).unwrap(),
+ 1
+ );
+ let doc: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(profile.path().join("logins.json")).unwrap())
+ .unwrap();
+ let e = &doc["logins"][0];
+ assert_eq!(e["hostname"], "https://github.com");
+ let pw = cua_teleport_bundle::firefox_nss::decrypt_sdr(
+ &MASTER,
+ e["encryptedPassword"].as_str().unwrap(),
+ )
+ .unwrap();
+ assert_eq!(&*pw, b"gh-pw");
+ let user = cua_teleport_bundle::firefox_nss::decrypt_sdr(
+ &MASTER,
+ e["encryptedUsername"].as_str().unwrap(),
+ )
+ .unwrap();
+ assert_eq!(&*user, b"octo");
+ assert!(e["guid"].as_str().unwrap().starts_with('{'));
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
index bf67c03c44..ad2340d18d 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
@@ -63,6 +63,37 @@ impl ChromeImporter {
}
}
+/// Writes localStorage items into `profile_dir`'s `Local State/leveldb`
+/// (`Local Storage/leveldb`), beside what the browser already holds. The
+/// destination browser is not running yet (the import launches it afterwards),
+/// so LevelDB's lock is free. A store this import creates is ledgered with its
+/// files so a wipe removes it.
+pub(crate) fn write_local_storage(
+ profile_dir: &Path,
+ items: &[cua_teleport_bundle::local_storage::LocalStorageItem],
+ record: &mut ImportRecord,
+) -> Result<()> {
+ if items.is_empty() {
+ return Ok(());
+ }
+ let store = cua_chromium_storage::store_dir(profile_dir);
+ let existed = store.is_dir();
+ if !existed {
+ record.create_dir_all(&store)?;
+ }
+ let written = cua_chromium_storage::write(&store, items, crate::cookies::chrome_now_utc())
+ .map_err(|e| crate::TeleportError::Provider(e.to_string()))?;
+ record.local_storage_written(&store, &written);
+ if !existed {
+ if let Ok(entries) = std::fs::read_dir(&store) {
+ for e in entries.flatten() {
+ record.file_written(&e.path());
+ }
+ }
+ }
+ Ok(())
+}
+
impl ImportProvider for ChromeImporter {
fn id(&self) -> &str {
ID
@@ -165,29 +196,8 @@ impl ImportProvider for ChromeImporter {
}
if let Some(bytes) = local_storage_entry {
let items = cua_teleport_bundle::local_storage::parse(&bytes);
- if !items.is_empty() {
- // Same single-profile scope as the cookies above. The
- // destination Chrome is not running yet (this import
- // launches it afterwards), so LevelDB's lock is free.
- let store = cua_chromium_storage::store_dir(&user_data_dir.join("Default"));
- let existed = store.is_dir();
- if !existed {
- record.create_dir_all(&store)?;
- }
- let written =
- cua_chromium_storage::write(&store, &items, crate::cookies::chrome_now_utc())
- .map_err(|e| crate::TeleportError::Provider(e.to_string()))?;
- record.local_storage_written(&store, &written);
- // The database files themselves are new when it did not
- // exist: ledger them so a wipe removes them with the keys.
- if !existed {
- if let Ok(entries) = std::fs::read_dir(&store) {
- for e in entries.flatten() {
- record.file_written(&e.path());
- }
- }
- }
- }
+ // Same single-profile scope as the cookies above.
+ write_local_storage(&user_data_dir.join("Default"), &items, record)?;
}
// Suppress the first-run/onboarding flow: on a freshly-imported profile it
// starts its own new-tab session and discards the transferred session that
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
index 8f7ccc3585..14b07b5a94 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
@@ -13,9 +13,12 @@ use std::path::Path;
use std::sync::Arc;
use cua_teleport_bundle::bundle::{BundleReader, DEFAULT_MAX_TOTAL_BYTES};
+use cua_teleport_bundle::cookies::COOKIES_ENTRY;
use cua_teleport_bundle::layout::electron::{
- launch_spec_for, process_pattern, profile_dir, remap, ElectronApp, DISCORD, SLACK, UNITY_HUB,
+ launch_spec_for, process_pattern, profile_dir, remap, ElectronApp, DISCORD, NOTION, SLACK,
+ UNITY_HUB, VSCODE,
};
+use cua_teleport_bundle::local_storage::LOCAL_STORAGE_ENTRY;
use cua_teleport_bundle::{LaunchSpec, Platform};
use super::write_entry;
@@ -56,6 +59,16 @@ impl ElectronImporter {
Self::new(DISCORD)
}
+ /// Visual Studio Code.
+ pub fn vscode() -> Self {
+ Self::new(VSCODE)
+ }
+
+ /// Notion.
+ pub fn notion() -> Self {
+ Self::new(NOTION)
+ }
+
/// Unity Hub.
pub fn unity_hub() -> Self {
Self::new(UNITY_HUB)
@@ -92,8 +105,21 @@ impl ImportProvider for ElectronImporter {
super::terminate_running(&*self.host, &pattern);
}
- record.create_dir_all(&dest_home.join(profile_dir(&self.app, platform)))?;
+ let user_data = dest_home.join(profile_dir(&self.app, platform));
+ record.create_dir_all(&user_data)?;
+ let mut cookies: Option<Vec<u8>> = None;
+ let mut local_storage: Option<Vec<u8>> = None;
while let Some(entry) = reader.next_entry()? {
+ // Items from the Keyvault: re-encrypted for THIS app's own key
+ // below (never the source's), or written into its own LevelDB.
+ if entry.rel_path == COOKIES_ENTRY {
+ cookies = Some(entry.bytes);
+ continue;
+ }
+ if entry.rel_path == LOCAL_STORAGE_ENTRY {
+ local_storage = Some(entry.bytes);
+ continue;
+ }
if entry.rel_path == keychain::KEYCHAIN_ENTRY {
keychain::install_all_recorded(&*self.host, &entry.bytes, record);
continue;
@@ -102,6 +128,32 @@ impl ImportProvider for ElectronImporter {
write_entry(&dest_home.join(rel), &entry, false, record)?;
}
}
+ // Electron keeps its Chromium profile at the root of userData: the
+ // cookies and Local State sit right there, not under `Default/`.
+ if let Some(bytes) = cookies {
+ let items = cua_teleport_bundle::cookies::parse(&bytes);
+ if let Some(service) = self
+ .app
+ .keychain_services
+ .iter()
+ .find(|s| s.ends_with(" Safe Storage"))
+ {
+ crate::cookies::install_cookies_with(
+ &*self.host,
+ &user_data,
+ &user_data.join("Local State"),
+ service,
+ platform,
+ &cua_chromium_storage::dpapi::SystemDpapi,
+ &items,
+ record,
+ )?;
+ }
+ }
+ if let Some(bytes) = local_storage {
+ let items = cua_teleport_bundle::local_storage::parse(&bytes);
+ crate::importers::chrome::write_local_storage(&user_data, &items, record)?;
+ }
Ok(launch_spec_for(platform, self.app.display))
}
}
@@ -265,4 +317,60 @@ mod tests {
.count();
assert_eq!(adds, usize::from(cfg!(target_os = "macos")));
}
+
+ /// Items from the Keyvault land in the app's own Chromium store at the
+ /// root of its userData: cookies re-encrypted under the destination's key,
+ /// localStorage in its own LevelDB.
+ #[test]
+ fn items_land_in_the_apps_own_userdata_re_encrypted() {
+ use cua_teleport_bundle::chromium_crypto as crypto;
+ use cua_teleport_bundle::cookies::{serialize, CookieItem};
+ use cua_teleport_bundle::local_storage::{serialize as ls_serialize, LocalStorageItem};
+ let dest = tempfile::tempdir().unwrap();
+ let cookies = serialize(&[CookieItem {
+ host_key: ".slack.com".into(),
+ name: "d".into(),
+ value: b"xoxd-session".to_vec(),
+ path: "/".into(),
+ expires_utc: 0,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 0,
+ extra: Default::default(),
+ }]);
+ let ls = ls_serialize(&[LocalStorageItem {
+ origin: "https://app.slack.com".into(),
+ key: "localConfig_v2".into(),
+ value: "{}".into(),
+ key_raw: None,
+ value_raw: None,
+ }]);
+ let b = bundle(
+ "slack",
+ &[
+ ("cookies.json", 0o600, &cookies),
+ ("localstorage.json", 0o600, &ls),
+ ],
+ );
+ ElectronImporter::slack()
+ .with_host(Arc::new(FakeHost::new()))
+ .import_to(&mut Cursor::new(b), dest.path(), Platform::Linux)
+ .unwrap();
+ let user_data = dest.path().join(".config/Slack");
+ let conn = rusqlite::Connection::open(user_data.join("Network/Cookies")).unwrap();
+ let enc: Vec<u8> = conn
+ .query_row(
+ "SELECT encrypted_value FROM cookies WHERE name = 'd'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let key = crypto::derive_key(crypto::LINUX_V10_PASSWORD, crypto::LINUX_V10_PBKDF2_ROUNDS);
+ let plain = crypto::decrypt_prefixed(&key, &enc).unwrap().1;
+ assert!(plain.ends_with(b"xoxd-session"));
+ let got = cua_chromium_storage::read(&cua_chromium_storage::store_dir(&user_data)).unwrap();
+ assert_eq!(got.len(), 1);
+ assert_eq!(got[0].key, "localConfig_v2");
+ assert!(!dest.path().join("cookies.json").exists());
+ }
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/firefox.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/firefox.rs
index 4dc7f2f222..000c908dae 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/firefox.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/firefox.rs
@@ -63,7 +63,24 @@ impl ImportProvider for FirefoxImporter {
let mut reader = BundleReader::open_with_limit(bundle, self.max_total_bytes)?;
let mut tab_urls: Vec<String> = Vec::new();
+ let (mut cookies, mut local_storage, mut logins) = (None, None, None);
while let Some(entry) = reader.next_entry()? {
+ // Items from the Keyvault go into the profile's own stores below.
+ match entry.rel_path.as_str() {
+ cua_teleport_bundle::cookies::COOKIES_ENTRY => {
+ cookies = Some(entry.bytes);
+ continue;
+ }
+ cua_teleport_bundle::local_storage::LOCAL_STORAGE_ENTRY => {
+ local_storage = Some(entry.bytes);
+ continue;
+ }
+ cua_teleport_bundle::logins::LOGINS_ENTRY => {
+ logins = Some(entry.bytes);
+ continue;
+ }
+ _ => {}
+ }
if entry.rel_path == TABS_JSON {
tab_urls = serde_json::from_slice(&entry.bytes).unwrap_or_default();
continue;
@@ -76,6 +93,28 @@ impl ImportProvider for FirefoxImporter {
write_entry(&profile_dir.join(within), &entry, false, record)?;
}
+ if let Some(b) = cookies {
+ crate::firefox_items::install_cookies(
+ &profile_dir,
+ &cua_teleport_bundle::cookies::parse(&b),
+ record,
+ )?;
+ }
+ if let Some(b) = local_storage {
+ crate::firefox_items::install_local_storage(
+ &profile_dir,
+ &cua_teleport_bundle::local_storage::parse(&b),
+ record,
+ )?;
+ }
+ if let Some(b) = logins {
+ crate::firefox_items::install_logins(
+ &profile_dir,
+ &cua_teleport_bundle::logins::parse(&b),
+ record,
+ )?;
+ }
+
// Session-restore fallback: a running source Firefox keeps the live
// session only in `sessionstore-backups/recovery.jsonlz4`, so seed the
// top-level `sessionstore.jsonlz4` from it when it wasn't captured.
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
index 0341e6b964..ae81057294 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
@@ -579,6 +579,10 @@ pub(crate) fn trusted_app_for(service: &str) -> Option<&'static str> {
"Chromium Safe Storage" => Some("/Applications/Chromium.app"),
"Microsoft Edge Safe Storage" => Some("/Applications/Microsoft Edge.app"),
"Brave Safe Storage" => Some("/Applications/Brave Browser.app"),
+ "Slack Safe Storage" => Some("/Applications/Slack.app"),
+ "discord Safe Storage" => Some("/Applications/Discord.app"),
+ "Code Safe Storage" => Some("/Applications/Visual Studio Code.app"),
+ "Notion Safe Storage" => Some("/Applications/Notion.app"),
_ => None,
}
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
index 81cc364bbe..fe35081564 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
@@ -586,6 +586,21 @@ fn probe(dest_home: &Path, rel: &Path) -> Result<Probe, String> {
/// either way.
fn delete_cookie_row(db: &Path, host_key: &str, name: &str, path: &str) -> rusqlite::Result<usize> {
let conn = rusqlite::Connection::open(db)?;
+ // A Firefox `cookies.sqlite` names its table and columns differently.
+ let firefox: bool = conn
+ .query_row(
+ "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'moz_cookies'",
+ [],
+ |r| r.get::<_, i64>(0),
+ )
+ .map(|n| n > 0)
+ .unwrap_or(false);
+ if firefox {
+ return conn.execute(
+ "DELETE FROM moz_cookies WHERE host = ?1 AND name = ?2 AND path = ?3",
+ rusqlite::params![host_key, name, path],
+ );
+ }
conn.execute(
"DELETE FROM cookies WHERE host_key = ?1 AND name = ?2 AND path = ?3",
rusqlite::params![host_key, name, path],
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
index f36ac98011..7d08abb5d8 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
@@ -26,6 +26,7 @@
//! `CUA_ENV_TEST_SANDBOX=1`; tests inject [`FakeHost`]).
pub mod cookies;
+pub mod firefox_items;
pub mod host;
pub mod importers;
pub mod keychain;
@@ -116,6 +117,8 @@ impl ImportRegistry {
registry.register(Box::new(
ElectronImporter::discord().with_host(host.clone()),
));
+ registry.register(Box::new(ElectronImporter::vscode().with_host(host.clone())));
+ registry.register(Box::new(ElectronImporter::notion().with_host(host.clone())));
registry.register(Box::new(ElectronImporter::unity_hub().with_host(host)));
registry.register(Box::new(SteamImporter::new()));
registry.register(Box::new(WhatsAppImporter::new()));
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs
index 676d115171..b61ab312f3 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs
@@ -22,11 +22,10 @@
use std::path::Path;
-use cua_teleport_bundle::chromium_crypto;
use cua_teleport_bundle::logins::LoginItem;
use cua_teleport_bundle::Platform;
-use crate::cookies::{chrome_now_utc, ensure_safe_storage_secret};
+use crate::cookies::chrome_now_utc;
use crate::host::HostEffects;
use crate::ledger::ImportRecord;
use crate::{Result, TeleportError};
@@ -58,16 +57,34 @@ pub fn install_logins(
platform: Platform,
items: &[LoginItem],
record: &mut ImportRecord,
+) -> Result<usize> {
+ install_logins_with(
+ host,
+ profile_dir,
+ &crate::cookies::default_local_state(profile_dir),
+ service,
+ platform,
+ &cua_chromium_storage::dpapi::SystemDpapi,
+ items,
+ record,
+ )
+}
+
+/// [`install_logins`] with an explicit `Local State` and DPAPI.
+#[allow(clippy::too_many_arguments)]
+pub fn install_logins_with(
+ host: &dyn HostEffects,
+ profile_dir: &Path,
+ local_state: &Path,
+ service: &'static str,
+ platform: Platform,
+ dpapi: &dyn cua_chromium_storage::dpapi::Dpapi,
+ items: &[LoginItem],
+ record: &mut ImportRecord,
) -> Result<usize> {
if items.is_empty() {
return Ok(0);
}
- if platform == Platform::Windows {
- return Err(TeleportError::Provider(
- "re-encrypting saved passwords for a Windows destination (DPAPI) is not supported yet"
- .into(),
- ));
- }
let db = profile_dir.join("Login Data");
if !db.is_file() {
// Not a failure of the whole import (the cookies and files still
@@ -79,13 +96,8 @@ pub fn install_logins(
);
return Ok(0);
}
- let secret = ensure_safe_storage_secret(host, platform, service, record)
- .map_err(|e| TeleportError::Provider(format!("Safe Storage key for {service}: {e}")))?;
- let rounds = match platform {
- Platform::Linux => chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
- Platform::MacOS | Platform::Windows => chromium_crypto::MACOS_PBKDF2_ROUNDS,
- };
- let key = chromium_crypto::derive_key(&secret, rounds);
+ let key =
+ crate::cookies::destination_cipher(host, local_state, service, platform, dpapi, record)?;
let conn = rusqlite::Connection::open(&db)
.map_err(|e| TeleportError::Provider(format!("opening Login Data failed: {e}")))?;
let present = columns(&conn)
@@ -120,7 +132,7 @@ pub fn install_logins(
let now = chrome_now_utc();
let mut written = 0;
for item in items {
- let encrypted = chromium_crypto::encrypt_v10(&key, &item.password);
+ let encrypted = key.encrypt(&item.password);
let args: Vec<rusqlite::types::Value> = cols
.iter()
.map(|c| match *c {
@@ -159,6 +171,7 @@ fn columns(conn: &rusqlite::Connection) -> rusqlite::Result<std::collections::Ha
mod tests {
use super::*;
use crate::host::FakeHost;
+ use cua_teleport_bundle::chromium_crypto;
fn login(origin: &str, user: &str, pw: &[u8]) -> LoginItem {
LoginItem {
@@ -268,7 +281,7 @@ mod tests {
}
#[test]
- fn empty_input_and_windows_are_refused_without_touching_anything() {
+ fn empty_input_touches_nothing() {
let dir = tempfile::tempdir().unwrap();
let mut rec = ImportRecord::default();
assert_eq!(
@@ -283,14 +296,50 @@ mod tests {
.unwrap(),
0
);
- assert!(install_logins(
+ assert!(rec.notices.is_empty() && rec.files.is_empty());
+ }
+
+ /// A Windows destination: AES-256-GCM under the destination's own Local
+ /// State key (created and DPAPI-wrapped when it has none), beside the
+ /// browser's own logins.
+ #[test]
+ fn a_windows_destination_gets_aes_gcm_under_its_own_local_state_key() {
+ use cua_chromium_storage::dpapi::{local_state_key, FakeDpapi};
+ let home = tempfile::tempdir().unwrap();
+ let user_data = home.path().join("User Data");
+ let dir = user_data.join("Default");
+ std::fs::create_dir_all(&dir).unwrap();
+ let db = existing(&dir);
+ let local_state = user_data.join("Local State");
+ let mut record = ImportRecord::default();
+ let n = install_logins_with(
&FakeHost::new(),
- dir.path(),
- "x",
+ &dir,
+ &local_state,
+ "Chrome Safe Storage",
Platform::Windows,
- &[login("https://a.test", "u", b"p")],
- &mut rec
+ &FakeDpapi,
+ &[login("https://github.com", "octo", b"gh-pw-1234")],
+ &mut record,
)
- .is_err());
+ .unwrap();
+ assert_eq!(n, 1);
+ let enc: Vec<u8> = rusqlite::Connection::open(&db)
+ .unwrap()
+ .query_row(
+ "SELECT password_value FROM logins WHERE username_value = 'octo'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let key = local_state_key(&local_state, &FakeDpapi).unwrap();
+ assert_eq!(
+ &*chromium_crypto::gcm::decrypt(&key, &enc).unwrap(),
+ b"gh-pw-1234"
+ );
+ assert!(
+ record.files.contains(&local_state),
+ "a Local State we made is ledgered"
+ );
}
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
index 54397721df..4c87ade675 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
@@ -161,7 +161,7 @@ fn app_mismatch_unknown_provider_and_garbage_are_refused() {
receiver.import_bytes(b"not a tar", "", false),
Err(ImportError::InvalidBundle(_))
));
- let unknown = BundleWriter::new(Vec::new(), "vscode", "VS Code", TransferScope::TabsOnly)
+ let unknown = BundleWriter::new(Vec::new(), "blender", "Blender", TransferScope::TabsOnly)
.finish()
.unwrap();
assert!(matches!(
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index a5e6798bcb..117d73066d 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -40,6 +50,20 @@ dependencies = [
"cpufeatures 0.3.1",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes 0.8.4",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -1393,7 +1417,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -1848,6 +1872,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1862,6 +1887,15 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -1955,9 +1989,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -2465,6 +2502,7 @@ dependencies = [
"cua-spacesd-client",
"cua-spacesd-server",
"cua-spacesd-teleport",
+ "cua-teleport",
"futures-util",
"hex",
"prost",
@@ -2636,6 +2674,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
+ "zeroize",
]
[[package]]
@@ -2681,6 +2720,8 @@ dependencies = [
"serde_json",
"sha1",
"sha2 0.10.9",
+ "snap",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -2692,7 +2733,11 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes 0.8.4",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc 0.1.2",
+ "des",
+ "hmac 0.12.1",
"pbkdf2",
"serde",
"serde_json",
@@ -3023,6 +3068,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -3713,6 +3767,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "glob"
version = "0.3.4"
@@ -5473,6 +5537,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl"
version = "0.10.81"
@@ -5970,7 +6040,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -8216,6 +8298,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.toml b/libs/cua-spacesd/tests/spaces-e2e/Cargo.toml
index 9a09a8543d..79ea41226f 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.toml
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.toml
@@ -41,6 +41,7 @@ cua-spacesd-server = { path = "../../crates/cua-spacesd-server" }
cua-spacesd-teleport = { path = "../../crates/cua-spacesd-teleport" }
cua-driver-core = { path = "../../../cua-driver/rust/crates/cua-driver-core" }
cua-keyvault = { path = "../../../cua/crates/cua-keyvault" }
+cua-teleport = { path = "../../../cua/crates/cua-teleport" }
cua-spaces-ext = { path = "../../../cua/crates/cua-spaces-ext" }
async-trait = "0.1"
serde_json = "1"
diff --git a/libs/cua-spacesd/tests/spaces-e2e/src/lib.rs b/libs/cua-spacesd/tests/spaces-e2e/src/lib.rs
index f5ceba705b..e825aa30cd 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/src/lib.rs
+++ b/libs/cua-spacesd/tests/spaces-e2e/src/lib.rs
@@ -223,7 +223,18 @@ pub fn write_firefox_profile(home: &Path) -> PathBuf {
"user_pref(\"cua.test.marker\", \"teleported\");\n",
)
.unwrap();
- std::fs::write(profile.join("cookies.sqlite"), b"not-a-real-db").unwrap();
+ // A real (Firefox schema 16) cookie store: Firefox is sent as items.
+ cua_teleport::firefox_store::testing::write_cookies(
+ &profile,
+ &[(
+ ".example.test",
+ "session",
+ "fixture",
+ "/",
+ 1_900_000_000_000,
+ "",
+ )],
+ );
std::fs::write(profile.join("places.sqlite"), b"history").unwrap();
}
profile
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index 4a4cbdeb0a..1ec32f1fb6 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -40,6 +50,20 @@ dependencies = [
"cpufeatures 0.3.1",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes 0.8.4",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -781,7 +805,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -1167,6 +1191,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1181,6 +1206,15 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -1229,9 +1263,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -1509,6 +1546,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
+ "zeroize",
]
[[package]]
@@ -1554,6 +1592,8 @@ dependencies = [
"serde_json",
"sha1",
"sha2 0.10.9",
+ "snap",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -1565,7 +1605,11 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes 0.8.4",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc 0.1.2",
+ "des",
+ "hmac 0.12.1",
"pbkdf2",
"serde",
"serde_json",
@@ -1647,6 +1691,15 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -2262,6 +2315,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "glob"
version = "0.3.4"
@@ -3688,6 +3751,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl"
version = "0.10.81"
@@ -4105,7 +4174,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -6010,6 +6091,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index dc8023d91e..e030aa2b61 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -24,6 +24,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -45,6 +55,20 @@ dependencies = [
"cpufeatures 0.2.17",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -1503,7 +1527,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -1986,6 +2010,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -2000,6 +2025,15 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -2115,9 +2149,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -2730,6 +2767,7 @@ name = "cua-spaces-ffi"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
+ "cua-chromium-storage",
"cua-daemon",
"cua-fleet",
"cua-host",
@@ -2744,7 +2782,9 @@ dependencies = [
"cua-spacesd-client",
"cua-telemetry",
"cua-teleport",
+ "cua-teleport-bundle",
"futures-util",
+ "rand 0.9.5",
"serde",
"serde_json",
"tempfile",
@@ -2864,6 +2904,7 @@ dependencies = [
"serde_json",
"sha1 0.10.7",
"sha2 0.10.9",
+ "snap",
"tempfile",
"thiserror 2.0.20",
"tokio",
@@ -2876,8 +2917,12 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc",
+ "des",
"hex",
+ "hmac 0.12.1",
"pbkdf2",
"serde",
"serde_json",
@@ -3265,6 +3310,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -3866,6 +3920,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "gl_generator"
version = "0.14.0"
@@ -5696,6 +5760,12 @@ version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openh264"
version = "0.9.8"
@@ -6096,7 +6166,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -8595,6 +8677,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"
diff --git a/libs/cua/crates/cua-chromium-storage/Cargo.toml b/libs/cua/crates/cua-chromium-storage/Cargo.toml
index 1aabaf82f8..91f9091ec6 100644
--- a/libs/cua/crates/cua-chromium-storage/Cargo.toml
+++ b/libs/cua/crates/cua-chromium-storage/Cargo.toml
@@ -15,5 +15,11 @@ base64.workspace = true
thiserror.workspace = true
tempfile.workspace = true
tracing.workspace = true
+zeroize = "1"
+serde_json.workspace = true
# A maintained, pure-Rust LevelDB (reads Chromium's Snappy tables and log).
rusty-leveldb = "4"
+
+[target.'cfg(windows)'.dependencies]
+# DPAPI (`CryptProtectData`/`CryptUnprotectData`) for Chromium's Windows key.
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_System_Memory"] }
diff --git a/libs/cua/crates/cua-chromium-storage/src/dpapi.rs b/libs/cua/crates/cua-chromium-storage/src/dpapi.rs
new file mode 100644
index 0000000000..32f6f99762
--- /dev/null
+++ b/libs/cua/crates/cua-chromium-storage/src/dpapi.rs
@@ -0,0 +1,221 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Windows DPAPI for Chromium's `Local State` key, behind a trait so every
+//! caller is testable on any platform.
+//!
+//! Chromium (components/os_crypt, `DecryptStringWithDPAPI` /
+//! `EncryptStringWithDPAPI`) wraps its random 32-byte AES-256-GCM key with
+//! `CryptProtectData` in the user's scope and stores it in `Local State`
+//! (`os_crypt.encrypted_key`, base64 of `"DPAPI"` + the blob). [`SystemDpapi`]
+//! is the real thing on Windows (`cfg(windows)`); everywhere else it refuses.
+//! [`Local State`](local_state_key) reading and the key bookkeeping around it
+//! are plain code.
+
+use std::path::Path;
+
+use cua_teleport_bundle::chromium_crypto::gcm;
+use zeroize::Zeroizing;
+
+/// DPAPI, user scope, no entropy.
+pub trait Dpapi: Send + Sync {
+ /// `CryptUnprotectData`.
+ fn unprotect(&self, blob: &[u8]) -> Result<Zeroizing<Vec<u8>>, String>;
+ /// `CryptProtectData`.
+ fn protect(&self, plain: &[u8]) -> Result<Vec<u8>, String>;
+}
+
+/// The operating system's DPAPI (Windows only).
+#[derive(Clone, Copy, Debug, Default)]
+pub struct SystemDpapi;
+
+#[cfg(windows)]
+impl Dpapi for SystemDpapi {
+ fn unprotect(&self, blob: &[u8]) -> Result<Zeroizing<Vec<u8>>, String> {
+ use windows_sys::Win32::Foundation::LocalFree;
+ use windows_sys::Win32::Security::Cryptography::{CRYPT_INTEGER_BLOB, CryptUnprotectData};
+ let input = CRYPT_INTEGER_BLOB {
+ cbData: blob.len() as u32,
+ pbData: blob.as_ptr() as *mut u8,
+ };
+ let mut out = CRYPT_INTEGER_BLOB {
+ cbData: 0,
+ pbData: std::ptr::null_mut(),
+ };
+ // SAFETY: `input` borrows `blob` for the call; `out` is written by the
+ // API and freed with `LocalFree` below.
+ let ok = unsafe {
+ CryptUnprotectData(
+ &input,
+ std::ptr::null_mut(),
+ std::ptr::null(),
+ std::ptr::null(),
+ std::ptr::null(),
+ 0,
+ &mut out,
+ )
+ };
+ if ok == 0 {
+ return Err("CryptUnprotectData failed (a different Windows user or machine?)".into());
+ }
+ // SAFETY: on success `pbData` points at `cbData` bytes we now own.
+ let data = unsafe { std::slice::from_raw_parts(out.pbData, out.cbData as usize) }.to_vec();
+ unsafe { LocalFree(out.pbData as _) };
+ Ok(Zeroizing::new(data))
+ }
+
+ fn protect(&self, plain: &[u8]) -> Result<Vec<u8>, String> {
+ use windows_sys::Win32::Foundation::LocalFree;
+ use windows_sys::Win32::Security::Cryptography::{CRYPT_INTEGER_BLOB, CryptProtectData};
+ let input = CRYPT_INTEGER_BLOB {
+ cbData: plain.len() as u32,
+ pbData: plain.as_ptr() as *mut u8,
+ };
+ let mut out = CRYPT_INTEGER_BLOB {
+ cbData: 0,
+ pbData: std::ptr::null_mut(),
+ };
+ // SAFETY: as in `unprotect`.
+ let ok = unsafe {
+ CryptProtectData(
+ &input,
+ std::ptr::null(),
+ std::ptr::null(),
+ std::ptr::null(),
+ std::ptr::null(),
+ 0,
+ &mut out,
+ )
+ };
+ if ok == 0 {
+ return Err("CryptProtectData failed".into());
+ }
+ let data = unsafe { std::slice::from_raw_parts(out.pbData, out.cbData as usize) }.to_vec();
+ unsafe { LocalFree(out.pbData as _) };
+ Ok(data)
+ }
+}
+
+#[cfg(not(windows))]
+impl Dpapi for SystemDpapi {
+ fn unprotect(&self, _blob: &[u8]) -> Result<Zeroizing<Vec<u8>>, String> {
+ Err("DPAPI is only available on Windows".into())
+ }
+ fn protect(&self, _plain: &[u8]) -> Result<Vec<u8>, String> {
+ Err("DPAPI is only available on Windows".into())
+ }
+}
+
+/// The AES-256-GCM key a `Local State` file holds, unwrapped with `dpapi`.
+pub fn local_state_key(
+ local_state: &Path,
+ dpapi: &dyn Dpapi,
+) -> Result<Zeroizing<[u8; gcm::KEY_LEN]>, String> {
+ let json = std::fs::read(local_state)
+ .map_err(|e| format!("reading {}: {e}", local_state.display()))?;
+ let enc = gcm::encrypted_key_of(&json)
+ .ok_or_else(|| "Local State has no os_crypt.encrypted_key".to_string())?;
+ let blob = gcm::dpapi_blob(&enc).map_err(|e| e.to_string())?;
+ let key = dpapi.unprotect(&blob)?;
+ let key: [u8; gcm::KEY_LEN] = key
+ .as_slice()
+ .try_into()
+ .map_err(|_| "the Local State key is not 32 bytes".to_string())?;
+ Ok(Zeroizing::new(key))
+}
+
+/// The destination's key: the one its `Local State` already holds, or a fresh
+/// random one wrapped with `dpapi` and written into `Local State` (creating
+/// the file, keeping every other field of an existing one). Returns the key and
+/// whether it was created.
+pub fn ensure_local_state_key(
+ local_state: &Path,
+ dpapi: &dyn Dpapi,
+ random: [u8; gcm::KEY_LEN],
+) -> Result<(Zeroizing<[u8; gcm::KEY_LEN]>, bool), String> {
+ if local_state.is_file() {
+ let json = std::fs::read(local_state).map_err(|e| e.to_string())?;
+ if gcm::encrypted_key_of(&json).is_some() {
+ return Ok((local_state_key(local_state, dpapi)?, false));
+ }
+ }
+ let blob = dpapi.protect(&random)?;
+ let mut doc: serde_json::Value = std::fs::read(local_state)
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_else(|| serde_json::json!({}));
+ doc["os_crypt"]["encrypted_key"] = serde_json::Value::String(gcm::encrypted_key_value(&blob));
+ if let Some(dir) = local_state.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+ }
+ std::fs::write(
+ local_state,
+ serde_json::to_vec(&doc).map_err(|e| e.to_string())?,
+ )
+ .map_err(|e| e.to_string())?;
+ Ok((Zeroizing::new(random), true))
+}
+
+/// A DPAPI stand-in for tests on every platform: "protection" is a reversible
+/// XOR with a fixed pad, enough to prove the callers wrap and unwrap.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct FakeDpapi;
+
+impl Dpapi for FakeDpapi {
+ fn unprotect(&self, blob: &[u8]) -> Result<Zeroizing<Vec<u8>>, String> {
+ let body = blob.strip_prefix(b"FAKE").ok_or("not a fake DPAPI blob")?;
+ Ok(Zeroizing::new(body.iter().map(|b| b ^ 0x5a).collect()))
+ }
+ fn protect(&self, plain: &[u8]) -> Result<Vec<u8>, String> {
+ let mut out = b"FAKE".to_vec();
+ out.extend(plain.iter().map(|b| b ^ 0x5a));
+ Ok(out)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_local_state_key_unwraps_and_a_missing_one_is_created_keeping_other_fields() {
+ let dir = tempfile::tempdir().unwrap();
+ let ls = dir.path().join("Local State");
+ std::fs::write(&ls, br#"{"profile":{"last_used":"Default"}}"#).unwrap();
+ assert!(local_state_key(&ls, &FakeDpapi).is_err());
+ let (key, created) = ensure_local_state_key(&ls, &FakeDpapi, [9u8; 32]).unwrap();
+ assert!(created && *key == [9u8; 32]);
+ let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&ls).unwrap()).unwrap();
+ assert_eq!(doc["profile"]["last_used"], "Default", "the rest is kept");
+ assert_eq!(*local_state_key(&ls, &FakeDpapi).unwrap(), [9u8; 32]);
+ // An existing key is reused, never replaced.
+ let (again, created) = ensure_local_state_key(&ls, &FakeDpapi, [1u8; 32]).unwrap();
+ assert!(!created && *again == [9u8; 32]);
+ // No Local State at all: created from scratch.
+ let fresh = dir.path().join("new/Local State");
+ assert!(
+ ensure_local_state_key(&fresh, &FakeDpapi, [4u8; 32])
+ .unwrap()
+ .1
+ );
+ }
+
+ #[cfg(not(windows))]
+ #[test]
+ fn the_system_dpapi_refuses_off_windows() {
+ assert!(SystemDpapi.unprotect(b"x").is_err());
+ }
+
+ /// Windows CI: the real DPAPI round trip (user scope).
+ #[cfg(windows)]
+ #[test]
+ fn the_system_dpapi_round_trips_on_windows() {
+ let blob = SystemDpapi
+ .protect(b"0123456789abcdef0123456789abcdef")
+ .unwrap();
+ assert_ne!(&blob[..], b"0123456789abcdef0123456789abcdef");
+ let plain = SystemDpapi.unprotect(&blob).unwrap();
+ assert_eq!(&**plain, b"0123456789abcdef0123456789abcdef");
+ assert!(SystemDpapi.unprotect(b"not a blob").is_err());
+ }
+}
diff --git a/libs/cua/crates/cua-chromium-storage/src/lib.rs b/libs/cua/crates/cua-chromium-storage/src/lib.rs
index e15a00476c..85640efe7b 100644
--- a/libs/cua/crates/cua-chromium-storage/src/lib.rs
+++ b/libs/cua/crates/cua-chromium-storage/src/lib.rs
@@ -26,6 +26,8 @@
use std::path::{Path, PathBuf};
+pub mod dpapi;
+
use base64::Engine as _;
use rusty_leveldb::{DB, LdbIterator, Options};
diff --git a/libs/cua/crates/cua-keyvault/src/record.rs b/libs/cua/crates/cua-keyvault/src/record.rs
index 4abb0d5705..e6a49cdec1 100644
--- a/libs/cua/crates/cua-keyvault/src/record.rs
+++ b/libs/cua/crates/cua-keyvault/src/record.rs
@@ -580,6 +580,19 @@ impl RecordCodec for GenericCodec {
})?);
}
}
+ // Saved logins a provider decrypted because the user ticked them.
+ LOGINS_ENTRY => {
+ let bytes = entry_bytes(e)?;
+ let rows: Vec<LoginRow> = serde_json::from_slice(&bytes)
+ .map_err(|_| Error::Corrupt("logins.json is not valid".into()))?;
+ for r in &rows {
+ out.records.push(password_record(&LoginRecord {
+ origin: r.origin.clone(),
+ username: r.username.clone(),
+ password: String::from_utf8_lossy(&r.password).into_owned(),
+ })?);
+ }
+ }
path => {
let bytes = entry_bytes(e)?;
out.records.push(file_record(path, e.mode, &bytes)?);
@@ -1116,6 +1129,33 @@ mod tests {
);
}
+ /// A provider's decrypted logins (ticked by the user) become password
+ /// items, and delivering them again gives the same rows.
+ #[test]
+ fn logins_entry_round_trips_through_password_items() {
+ let rows = serde_json::json!([
+ {"origin": "https://github.com", "username": "octo", "password": b64().encode(b"gh-pw"),
+ "signon_realm": "https://github.com/"}
+ ]);
+ let exported = GenericCodec
+ .export(
+ vec![entry(LOGINS_ENTRY, rows.to_string().as_bytes())],
+ &ExportOptions::default(),
+ )
+ .unwrap();
+ assert_eq!(exported.records.len(), 1);
+ assert_eq!(exported.records[0].kind, ItemKind::Password);
+ assert_eq!(
+ exported.records[0].domain.as_deref(),
+ Some("https://github.com")
+ );
+ let payloads: Vec<ItemPayload> = exported.records.into_iter().map(payload_of).collect();
+ let entries = GenericCodec.import(&payloads).unwrap();
+ let back: serde_json::Value =
+ serde_json::from_slice(&b64().decode(&entries[0].data).unwrap()).unwrap();
+ assert_eq!(back, rows);
+ }
+
#[test]
fn selective_send_is_filtering_records_and_files_dedupe() {
let mk = |h: &str| payload_of(cookie_record(&cookie(h, "sid", "/", b"v")).unwrap());
diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
index 584ee2bcaf..03de172b52 100644
--- a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
@@ -227,7 +227,65 @@ impl DaemonBackend {
}
}
+/// The inventory row of `site`, created on first use.
+fn site_entry(
+ domains: &mut std::collections::BTreeMap<String, DomainInventory>,
+ site: String,
+) -> &mut DomainInventory {
+ domains
+ .entry(site.clone())
+ .or_insert_with(|| DomainInventory {
+ domain: site.clone(),
+ identity_provider: cua_keyvault::model::is_identity_provider(&site),
+ ..Default::default()
+ })
+}
+
impl DaemonBackend {
+ /// Firefox's sites with counts from its plaintext stores: cookies by host,
+ /// localStorage by origin, saved logins by hostname. Nothing is decrypted.
+ fn firefox_inventory(
+ &self,
+ domains: &mut std::collections::BTreeMap<String, DomainInventory>,
+ notes: &mut Vec<String>,
+ ) {
+ use cua_teleport::firefox_store as ff;
+ let Some(home) = self.host.home_dir() else {
+ return;
+ };
+ let root = home.join(cua_teleport_bundle::layout::firefox::root_for(
+ self.platform,
+ ));
+ let Some(profile) = ff::default_profile(&root) else {
+ notes.push("no Firefox profile was found".into());
+ return;
+ };
+ match ff::read_cookies(&profile.dir) {
+ Ok(cookies) => {
+ for c in cookies {
+ let d = site_entry(domains, record::site_of(&c.host_key));
+ d.cookies += 1;
+ if c.expires_utc == 0 {
+ d.session_cookies += 1;
+ }
+ d.signin |= record::looks_like_signin(&c.name);
+ }
+ }
+ Err(e) => notes.push(format!("Firefox cookies were not listed: {e}")),
+ }
+ match ff::read_local_storage(&profile.dir) {
+ Ok(items) => {
+ for i in items {
+ site_entry(domains, record::site_of(&i.origin)).local_storage += 1;
+ }
+ }
+ Err(e) => notes.push(format!("Firefox localStorage was not listed: {e}")),
+ }
+ for host in ff::login_hosts(&profile.dir) {
+ site_entry(domains, record::site_of(&host)).passwords += 1;
+ }
+ }
+
/// The decrypted saved logins of `sites` (every site when empty).
fn site_logins_for(
&self,
@@ -497,6 +555,9 @@ impl Backend for DaemonBackend {
}
}
}
+ if app == "firefox" {
+ self.firefox_inventory(&mut domains, &mut notes);
+ }
Ok(Inventory {
provider_id: manifest.app.clone(),
app_display: manifest.display_name.clone(),
diff --git a/libs/cua/crates/cua-spaces-ffi/Cargo.toml b/libs/cua/crates/cua-spaces-ffi/Cargo.toml
index f4302a4345..e5c5676031 100644
--- a/libs/cua/crates/cua-spaces-ffi/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-ffi/Cargo.toml
@@ -50,3 +50,9 @@ cua-spacesd-client = { workspace = true, features = ["testing"] }
cua-fleet = { workspace = true, features = ["testing"] }
cua-daemon = { workspace = true, features = ["server", "client", "test-fixtures"] }
tempfile.workspace = true
+# The teleport fixture encrypts a cookie the way a real Chromium Safe
+# Storage item would, to exercise the structured Electron capture path
+# (on Windows, through the real DPAPI-wrapped Local State key).
+cua-teleport-bundle.workspace = true
+cua-chromium-storage.workspace = true
+rand.workspace = true
diff --git a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
index 19ec66e7cc..d22c6383b3 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
@@ -940,7 +940,7 @@ mod tests {
let app = e.app.unwrap();
assert_eq!(
(app.id.as_str(), app.capability),
- ("vscode", TeleportCapability::InstallOnly)
+ ("vscode", TeleportCapability::Full)
);
let mv = window_event(
&registry(),
diff --git a/libs/cua/crates/cua-spaces-ffi/tests/teleport.rs b/libs/cua/crates/cua-spaces-ffi/tests/teleport.rs
index f0d820c82d..d2d0036a2e 100644
--- a/libs/cua/crates/cua-spaces-ffi/tests/teleport.rs
+++ b/libs/cua/crates/cua-spaces-ffi/tests/teleport.rs
@@ -17,11 +17,48 @@ use cua_daemon::server::{self, ServerConfig};
use cua_daemon::{Runtime, RuntimeConfig};
use cua_sdk::{Cua, CuaError, SandboxCreateOptions};
use cua_spaces_ffi::{Teleport, TeleportApproval, TeleportApprovalRequest, TeleportScope};
+use cua_teleport::browser_cookies::{TestCookieRow, write_cookies_db_for_tests};
use cua_teleport::layout::electron::app_support_root;
-use cua_teleport::{FakeHost, Platform};
+use cua_teleport::{FakeHost, HostOutput, Platform};
+use cua_teleport_bundle::chromium_crypto;
const TOKEN: &str = "env-token";
+/// The fake macOS Keychain secret for "Slack Safe Storage" (Slack is sent
+/// structured: its cookies travel as decrypted rows, not the raw file).
+const FAKE_SAFE_STORAGE_SECRET: &[u8] = b"slack-safe-storage-secret";
+
+/// The key Slack's fixture cookie is encrypted under on macOS or Linux,
+/// matching whatever `SafeStorageKeys` derives there: the macOS fixture
+/// secret, or the fixed Linux `v10` password. Windows uses
+/// [`fixture_windows_key`] instead (a real, DPAPI-wrapped Local State key).
+fn fixture_key() -> [u8; 16] {
+ match Platform::current() {
+ Platform::MacOS => *chromium_crypto::derive_key(
+ FAKE_SAFE_STORAGE_SECRET,
+ chromium_crypto::MACOS_PBKDF2_ROUNDS,
+ ),
+ Platform::Linux => *chromium_crypto::derive_key(
+ chromium_crypto::LINUX_V10_PASSWORD,
+ chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ ),
+ Platform::Windows => unreachable!("Windows uses fixture_windows_key instead"),
+ }
+}
+
+/// Windows: a fresh AES-256-GCM key, written into `Local State` next to the
+/// profile and wrapped with the real (user-scope) DPAPI, the way
+/// `cua_chromium_storage::dpapi::ensure_local_state_key` does for a
+/// destination.
+#[cfg(windows)]
+fn fixture_windows_key(local_state: &std::path::Path) -> [u8; 32] {
+ use cua_chromium_storage::dpapi::{SystemDpapi, ensure_local_state_key};
+ let mut random = [0u8; 32];
+ rand::RngCore::fill_bytes(&mut rand::rng(), &mut random);
+ let (key, _) = ensure_local_state_key(local_state, &SystemDpapi, random).unwrap();
+ *key
+}
+
fn fake_home() -> tempfile::TempDir {
let home = tempfile::tempdir().unwrap();
let prof = home
@@ -29,7 +66,32 @@ fn fake_home() -> tempfile::TempDir {
.join(app_support_root(Platform::current()))
.join("Slack");
std::fs::create_dir_all(prof.join("Local Storage/leveldb")).unwrap();
- std::fs::write(prof.join("Cookies"), b"slack-cookies").unwrap();
+ let encrypted = match Platform::current() {
+ Platform::Windows => {
+ #[cfg(windows)]
+ {
+ let key = fixture_windows_key(&prof.join("Local State"));
+ chromium_crypto::gcm::encrypt(&key, &[9u8; 12], b"xoxd-session-value")
+ }
+ #[cfg(not(windows))]
+ unreachable!("Platform::current() reported Windows on a non-Windows build")
+ }
+ _ => chromium_crypto::encrypt_v10(&fixture_key(), b"xoxd-session-value"),
+ };
+ write_cookies_db_for_tests(
+ &prof,
+ &[TestCookieRow {
+ host_key: ".slack.com",
+ name: "d",
+ encrypted_value: encrypted,
+ path: "/",
+ expires_utc: 0,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 0,
+ }],
+ )
+ .unwrap();
std::fs::write(prof.join("Preferences"), b"{}").unwrap();
std::fs::write(
prof.join("Local Storage/leveldb/000003.log"),
@@ -39,6 +101,24 @@ fn fake_home() -> tempfile::TempDir {
home
}
+/// A `FakeHost` that, on macOS, answers a Keychain lookup of "Slack Safe
+/// Storage" with the fixture secret, so the structured capture path can
+/// decrypt the fixture cookie without ever touching the real Keychain. On
+/// Linux and Windows the responder is never consulted (the fixed Linux key
+/// and the real DPAPI-wrapped Local State key need no host command).
+fn fake_keychain_host(home: &std::path::Path) -> Arc<FakeHost> {
+ Arc::new(FakeHost::new().with_home(home).with_responder(|c| {
+ if c.args.iter().any(|a| a == "-w") {
+ Ok(HostOutput::ok([FAKE_SAFE_STORAGE_SECRET, b"\n"].concat()))
+ } else {
+ Ok(HostOutput::ok(
+ b" \"acct\"<blob>=\"Slack\"\n \"svce\"<blob>=\"Slack Safe Storage\"\n"
+ .to_vec(),
+ ))
+ }
+ }))
+}
+
fn direct(url: &str) -> SandboxCreateOptions {
SandboxCreateOptions {
on: Some(format!("direct:{url}")),
@@ -87,7 +167,7 @@ impl TeleportApproval for Record {
async fn run_suite(cua: Arc<Cua>, env: &fixtures::SpacesdFixture) {
let home = fake_home();
- let host = Arc::new(FakeHost::new().with_home(home.path()));
+ let host = fake_keychain_host(home.path());
let teleport = Teleport::with_host(host.clone());
let providers = teleport.providers();
@@ -184,11 +264,18 @@ async fn run_suite(cua: Arc<Cua>, env: &fixtures::SpacesdFixture) {
.unwrap()
.read_all()
.unwrap();
- let cookies = entries
+ // Slack is Chromium underneath, sent structured: the cookie travels
+ // already decrypted in the reserved entry, never as the raw (still
+ // Safe-Storage-encrypted, and so undecryptable on another machine) file.
+ assert!(!entries.iter().any(|e| e.rel_path == "electron/Cookies"));
+ let cookies_entry = entries
.iter()
- .find(|e| e.rel_path == "electron/Cookies")
+ .find(|e| e.rel_path == cua_teleport_bundle::cookies::COOKIES_ENTRY)
.unwrap();
- assert_eq!(cookies.bytes, b"slack-cookies");
+ let cookies = cua_teleport_bundle::cookies::parse(&cookies_entry.bytes);
+ assert_eq!(cookies.len(), 1);
+ assert_eq!(cookies[0].host_key, ".slack.com");
+ assert_eq!(cookies[0].value, b"xoxd-session-value");
// The same upload through an explicit env connection.
let env_client = sb.spacesd(Some(5_000)).await.unwrap();
diff --git a/libs/cua/crates/cua-spaces-ffi/tests/teleport_app.rs b/libs/cua/crates/cua-spaces-ffi/tests/teleport_app.rs
index b009baa426..04efa793b5 100644
--- a/libs/cua/crates/cua-spaces-ffi/tests/teleport_app.rs
+++ b/libs/cua/crates/cua-spaces-ffi/tests/teleport_app.rs
@@ -108,7 +108,7 @@ async fn the_catalog_lists_every_app_with_capabilities_recents_first() {
rows,
[
("firefox", TeleportCapability::Full),
- ("vscode", TeleportCapability::InstallOnly),
+ ("vscode", TeleportCapability::Full),
("blender", TeleportCapability::Unsupported),
(NOTES_ID, TeleportCapability::Unsupported),
]
@@ -116,9 +116,14 @@ async fn the_catalog_lists_every_app_with_capabilities_recents_first() {
let blender = all.iter().find(|e| e.id == "blender").unwrap();
assert!(blender.reason.as_deref().unwrap().contains("aarch64"));
let vs = all.iter().find(|e| e.id == "vscode").unwrap();
+ // VS Code is Chromium underneath, so its signed-in state teleports too.
assert_eq!(
vs.moves,
- [TeleportMove::AppOnly, TeleportMove::AppWithFiles]
+ [
+ TeleportMove::AppOnly,
+ TeleportMove::AppWithFiles,
+ TeleportMove::AppWithState
+ ]
);
assert_eq!(vs.install_source.as_deref(), Some("manifest"));
assert_eq!(vs.install_id.as_deref(), Some("vscode"));
@@ -198,7 +203,7 @@ fn drops_and_dropped_bundles() {
let e = t.catalog_entry_for_path(d.apps[0].clone(), None).unwrap();
assert_eq!(
(e.id.as_str(), e.capability),
- ("vscode", TeleportCapability::InstallOnly)
+ ("vscode", TeleportCapability::Full)
);
assert!(matches!(
t.catalog_entry_for_path("/tmp/a.txt".into(), None),
diff --git a/libs/cua/crates/cua-teleport-bundle/Cargo.toml b/libs/cua/crates/cua-teleport-bundle/Cargo.toml
index 605657e2b9..e7ae889cf8 100644
--- a/libs/cua/crates/cua-teleport-bundle/Cargo.toml
+++ b/libs/cua/crates/cua-teleport-bundle/Cargo.toml
@@ -19,10 +19,16 @@ tar = "0.4"
# destination): PBKDF2-HMAC-SHA1 + AES-128-CBC, RustCrypto crates. Pure: no
# file or Keychain I/O in this crate, so it is usable on every platform.
aes = "0.8"
+# Windows `v10` values: AES-256-GCM under the DPAPI-unwrapped Local State key.
+aes-gcm = "0.10"
cbc = { version = "0.1", features = ["alloc"] }
pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] }
sha1 = "0.10"
+# Firefox's NSS key derivation (key4.db): HMAC-SHA1 legacy PBE and 3DES.
+hmac = "0.12"
+des = "0.8"
zeroize = "1"
+base64.workspace = true
[dev-dependencies]
hex = { workspace = true }
diff --git a/libs/cua/crates/cua-teleport-bundle/src/chromium_crypto.rs b/libs/cua/crates/cua-teleport-bundle/src/chromium_crypto.rs
index da36331334..f337e1c185 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/chromium_crypto.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/chromium_crypto.rs
@@ -14,9 +14,15 @@
//! | Linux | `v10` | PBKDF2-HMAC-SHA1(`peanuts`, `saltysalt`, 1 round, 16 bytes) |
//! | Linux | `v11` | PBKDF2-HMAC-SHA1(the libsecret secret, `saltysalt`, 1 round, 16 bytes) |
//!
-//! then AES-128-CBC with a fixed IV of 16 spaces and PKCS#7 padding. Windows
-//! (DPAPI-wrapped AES-GCM) is a different scheme entirely and is out of
-//! scope here.
+//! then AES-128-CBC with a fixed IV of 16 spaces and PKCS#7 padding.
+//!
+//! Windows is a different scheme, in the [`gcm`] section below: `v10` +
+//! 12-byte nonce + AES-256-GCM ciphertext + 16-byte tag under a random
+//! 32-byte key that Chrome keeps in `Local State` (`os_crypt.encrypted_key`,
+//! base64 of `"DPAPI"` + a DPAPI blob). Unwrapping that blob is an OS call the
+//! sender makes (`cua_teleport::safe_storage`); the cipher and the Local State
+//! encoding live here, pure. `v20` (app-bound) cannot be decrypted by anyone
+//! but Chrome.
//!
//! This module is **pure**: it derives keys and runs the cipher over bytes
//! it is given. It never reads a Keychain, a file, or the network -- every
@@ -252,3 +258,130 @@ mod tests {
assert_eq!(macos_safe_storage_service("safari"), None);
}
}
+
+/// Windows `v10`: AES-256-GCM under the 32-byte key from `Local State`.
+pub mod gcm {
+ use aes_gcm::aead::{Aead, KeyInit};
+ use aes_gcm::{Aes256Gcm, Nonce};
+ use base64::Engine as _;
+ use zeroize::Zeroizing;
+
+ use crate::error::TeleportError;
+
+ /// AES-256 key length.
+ pub const KEY_LEN: usize = 32;
+ /// Nonce length.
+ pub const NONCE_LEN: usize = 12;
+ /// GCM tag length.
+ pub const TAG_LEN: usize = 16;
+ /// `os_crypt.encrypted_key` is `base64("DPAPI" + blob)`.
+ pub const DPAPI_PREFIX: &[u8] = b"DPAPI";
+
+ /// The DPAPI blob inside a Local State `os_crypt.encrypted_key` value
+ /// (base64 decoded, `DPAPI` stripped).
+ pub fn dpapi_blob(encrypted_key_b64: &str) -> Result<Vec<u8>, TeleportError> {
+ let raw = base64::engine::general_purpose::STANDARD
+ .decode(encrypted_key_b64.trim())
+ .map_err(|_| {
+ TeleportError::Provider("Local State encrypted_key is not base64".into())
+ })?;
+ raw.strip_prefix(DPAPI_PREFIX)
+ .map(<[u8]>::to_vec)
+ .ok_or_else(|| {
+ TeleportError::Provider("Local State encrypted_key is not a DPAPI key".into())
+ })
+ }
+
+ /// `os_crypt.encrypted_key` for a DPAPI blob (what a new Local State holds).
+ pub fn encrypted_key_value(dpapi_blob: &[u8]) -> String {
+ let mut raw = DPAPI_PREFIX.to_vec();
+ raw.extend_from_slice(dpapi_blob);
+ base64::engine::general_purpose::STANDARD.encode(raw)
+ }
+
+ /// The `os_crypt.encrypted_key` string of a Local State JSON document.
+ pub fn encrypted_key_of(local_state_json: &[u8]) -> Option<String> {
+ let v: serde_json::Value = serde_json::from_slice(local_state_json).ok()?;
+ v.get("os_crypt")?
+ .get("encrypted_key")?
+ .as_str()
+ .map(str::to_string)
+ }
+
+ /// Whether `value` is a `v10` GCM value (`v10` + nonce + tag at least).
+ pub fn is_v10(value: &[u8]) -> bool {
+ value.starts_with(b"v10") && value.len() >= 3 + NONCE_LEN + TAG_LEN
+ }
+
+ /// Decrypts a `v10` value (prefix included) with `key`.
+ pub fn decrypt(key: &[u8; KEY_LEN], value: &[u8]) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ if !is_v10(value) {
+ return Err(TeleportError::Provider(
+ "a Windows Chromium value is too short to be v10 AES-GCM".into(),
+ ));
+ }
+ let (nonce, ct) = value[3..].split_at(NONCE_LEN);
+ Aes256Gcm::new(key.into())
+ .decrypt(Nonce::from_slice(nonce), ct)
+ .map(Zeroizing::new)
+ .map_err(|_| {
+ TeleportError::Provider(
+ "a Windows Chromium value did not decrypt (wrong key or damaged)".into(),
+ )
+ })
+ }
+
+ /// Encrypts `plaintext` under `key` the way Chromium does: `v10` + nonce +
+ /// ciphertext + tag. The nonce is supplied by the caller (random per value).
+ pub fn encrypt(key: &[u8; KEY_LEN], nonce: &[u8; NONCE_LEN], plaintext: &[u8]) -> Vec<u8> {
+ let ct = Aes256Gcm::new(key.into())
+ .encrypt(Nonce::from_slice(nonce), plaintext)
+ .expect("AES-GCM encryption of an in-memory buffer cannot fail");
+ let mut out = Vec::with_capacity(3 + NONCE_LEN + ct.len());
+ out.extend_from_slice(b"v10");
+ out.extend_from_slice(nonce);
+ out.extend_from_slice(&ct);
+ out
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn v10_round_trips_and_a_wrong_key_or_damage_fails() {
+ let key = [7u8; KEY_LEN];
+ let nonce = [3u8; NONCE_LEN];
+ let enc = encrypt(&key, &nonce, b"session-value");
+ assert!(enc.starts_with(b"v10") && &enc[3..15] == nonce.as_slice());
+ assert_eq!(enc.len(), 3 + 12 + 13 + 16);
+ assert_eq!(&*decrypt(&key, &enc).unwrap(), b"session-value");
+ assert!(decrypt(&[8u8; KEY_LEN], &enc).is_err());
+ let mut bad = enc.clone();
+ *bad.last_mut().unwrap() ^= 1;
+ assert!(decrypt(&key, &bad).is_err());
+ assert!(decrypt(&key, b"v10short").is_err());
+ assert!(!is_v10(b"v20aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ }
+
+ /// A vector computed independently (RFC-style, AES-256-GCM, nonce
+ /// 000000000000000000000000, key of 32 zero bytes, empty plaintext):
+ /// the tag of empty data under the zero key and zero nonce.
+ #[test]
+ fn matches_the_published_aes_256_gcm_zero_vector() {
+ let key = [0u8; KEY_LEN];
+ let enc = encrypt(&key, &[0u8; NONCE_LEN], b"");
+ assert_eq!(hex::encode(&enc[15..]), "530f8afbc74536b9a963b4f1c4cb738b");
+ }
+
+ #[test]
+ fn local_state_key_encoding_round_trips() {
+ let v = encrypted_key_value(&[1, 2, 3]);
+ assert_eq!(dpapi_blob(&v).unwrap(), [1, 2, 3]);
+ assert!(dpapi_blob("AAAA").is_err());
+ let ls = format!(r#"{{"os_crypt":{{"encrypted_key":"{v}"}}}}"#);
+ assert_eq!(encrypted_key_of(ls.as_bytes()).as_deref(), Some(v.as_str()));
+ assert_eq!(encrypted_key_of(b"{}"), None);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-teleport-bundle/src/firefox_nss.rs b/libs/cua/crates/cua-teleport-bundle/src/firefox_nss.rs
new file mode 100644
index 0000000000..e49ef0941f
--- /dev/null
+++ b/libs/cua/crates/cua-teleport-bundle/src/firefox_nss.rs
@@ -0,0 +1,382 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Firefox's saved-login crypto (NSS "secret decoder ring"), pure.
+//!
+//! Firefox keeps logins in `logins.json`: `encryptedUsername` and
+//! `encryptedPassword` are base64 of a DER
+//! `SEQUENCE { OCTET STRING keyId, SEQUENCE { OID cipher, OCTET STRING iv },
+//! OCTET STRING ciphertext }` (NSS `lib/softoken/sdr.c`), under a master key that
+//! `key4.db` (SQLite) holds, itself encrypted with a key derived from the
+//! master password (empty by default):
+//!
+//! * `metaData` row `password`: `item1` = global salt, `item2` = DER
+//! `SEQUENCE { SEQUENCE { OID pbe, params }, OCTET STRING ciphertext }`, which
+//! decrypts to `password-check` (a wrong password fails here);
+//! * `nssPrivate.a11` = the same shape wrapping the master key, `a102` = key id.
+//!
+//! Two PBE schemes (NSS `lib/softoken/lowpbe.c`): the legacy
+//! `pbeWithSha1AndTripleDES-CBC` (1.2.840.113549.1.12.5.1.3: SHA-1 PBKDF1 then
+//! the HMAC-SHA1 extension `nsspkcs5_PFXPBE`, 3DES-CBC, IV = last 8 bytes) and
+//! PBES2 (1.2.840.113549.1.5.13: PBKDF2-HMAC-SHA256 over
+//! `SHA1(globalSalt || password)`, AES-256-CBC, IV = `04 0e` + 14 bytes).
+//!
+//! Nothing here touches a file: callers hand it the bytes.
+
+use aes::cipher::block_padding::Pkcs7;
+use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
+use base64::Engine as _;
+use hmac::{Hmac, Mac};
+use sha1::{Digest, Sha1};
+use zeroize::Zeroizing;
+
+use crate::error::TeleportError;
+
+const OID_PBE_3DES: &[u8] = &[
+ 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x05, 0x01, 0x03,
+];
+const OID_PBES2: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d];
+const OID_DES_EDE3_CBC: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x07];
+const OID_AES256_CBC: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2a];
+const PASSWORD_CHECK: &[u8] = b"password-check";
+
+fn err(m: &str) -> TeleportError {
+ TeleportError::Provider(format!("Firefox key4.db: {m}"))
+}
+
+// ---- a minimal DER reader and writer ----------------------------------------
+
+struct Der<'a>(&'a [u8]);
+
+impl<'a> Der<'a> {
+ /// The next element: its tag and content.
+ fn next(&mut self) -> Result<(u8, &'a [u8]), TeleportError> {
+ let b = self.0;
+ let (&tag, rest) = b.split_first().ok_or_else(|| err("truncated DER"))?;
+ let (&l0, rest) = rest.split_first().ok_or_else(|| err("truncated DER"))?;
+ let (len, rest) = if l0 < 0x80 {
+ (l0 as usize, rest)
+ } else {
+ let n = (l0 & 0x7f) as usize;
+ if n == 0 || n > 4 || rest.len() < n {
+ return Err(err("bad DER length"));
+ }
+ let len = rest[..n].iter().fold(0usize, |a, &x| (a << 8) | x as usize);
+ (len, &rest[n..])
+ };
+ if rest.len() < len {
+ return Err(err("truncated DER"));
+ }
+ self.0 = &rest[len..];
+ Ok((tag, &rest[..len]))
+ }
+
+ fn expect(&mut self, tag: u8) -> Result<&'a [u8], TeleportError> {
+ let (t, c) = self.next()?;
+ if t != tag {
+ return Err(err("unexpected DER structure"));
+ }
+ Ok(c)
+ }
+}
+
+fn der_int(c: &[u8]) -> u32 {
+ c.iter().fold(0u32, |a, &x| (a << 8) | x as u32)
+}
+
+fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
+ let mut out = vec![tag];
+ if content.len() < 0x80 {
+ out.push(content.len() as u8);
+ } else if content.len() < 0x100 {
+ out.extend([0x81, content.len() as u8]);
+ } else {
+ out.extend([0x82, (content.len() >> 8) as u8, content.len() as u8]);
+ }
+ out.extend_from_slice(content);
+ out
+}
+
+// ---- key derivation ---------------------------------------------------------
+
+type HmacSha1 = Hmac<Sha1>;
+
+/// Legacy NSS PBE: PBKDF1 (SHA-1, `iter` rounds) then the HMAC-SHA1 extension
+/// until `need` bytes exist.
+fn legacy_derive(password: &[u8], salt: &[u8], iter: u32, need: usize) -> Vec<u8> {
+ let mut h = Sha1::digest([password, salt].concat()).to_vec();
+ for _ in 1..iter {
+ h = Sha1::digest(&h).to_vec();
+ }
+ if need <= 20 {
+ return h;
+ }
+ let state_len = salt.len().max(20);
+ let mut state = salt.to_vec();
+ state.resize(state_len, 0);
+ let mut out = Vec::new();
+ while out.len() < need {
+ let mut m = <HmacSha1 as Mac>::new_from_slice(&h).expect("HMAC takes any key length");
+ m.update(&state);
+ m.update(salt);
+ out.extend_from_slice(&m.finalize().into_bytes());
+ let mut m = <HmacSha1 as Mac>::new_from_slice(&h).expect("HMAC takes any key length");
+ m.update(&state);
+ state = m.finalize().into_bytes().to_vec();
+ }
+ out
+}
+
+/// Decrypts a `SEQUENCE { SEQUENCE { OID, params }, OCTET STRING ct }` blob
+/// (key4.db `item2`, `a11`) with the password-derived key.
+fn decrypt_pbe_blob(
+ global_salt: &[u8],
+ password: &[u8],
+ blob: &[u8],
+) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ let mut top = Der(Der(blob).expect(0x30)?);
+ let mut alg = Der(top.expect(0x30)?);
+ let ct = top.expect(0x04)?;
+ let oid = alg.expect(0x06)?;
+ let params = alg.expect(0x30)?;
+ let hp = Sha1::digest([global_salt, password].concat()).to_vec();
+ if oid == OID_PBE_3DES {
+ let mut p = Der(params);
+ let salt = p.expect(0x04)?;
+ let iter = der_int(p.expect(0x02)?);
+ let k = legacy_derive(&hp, salt, iter.max(1), 32);
+ decrypt_3des(&k[..24], &k[k.len().min(40) - 8..], ct)
+ } else if oid == OID_PBES2 {
+ let mut p = Der(params);
+ let mut kdf = Der(p.expect(0x30)?);
+ kdf.expect(0x06)?;
+ let mut kp = Der(kdf.expect(0x30)?);
+ let salt = kp.expect(0x04)?;
+ let iter = der_int(kp.expect(0x02)?);
+ let mut enc = Der(p.expect(0x30)?);
+ enc.expect(0x06)?;
+ let iv = enc.expect(0x04)?;
+ let mut key = [0u8; 32];
+ pbkdf2::pbkdf2_hmac::<sha2::Sha256>(&hp, salt, iter.max(1), &mut key);
+ decrypt_aes256(&key, &sdr_iv(iv), ct)
+ } else {
+ Err(err("an unknown password-based encryption scheme"))
+ }
+}
+
+/// NSS keeps a 14-byte IV as its DER (`04 0e` + bytes): that 16-byte string is
+/// the CBC IV.
+fn sdr_iv(iv: &[u8]) -> Vec<u8> {
+ if iv.len() == 14 {
+ let mut v = vec![0x04, 0x0e];
+ v.extend_from_slice(iv);
+ v
+ } else {
+ iv.to_vec()
+ }
+}
+
+fn decrypt_3des(key: &[u8], iv: &[u8], ct: &[u8]) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ type D = cbc::Decryptor<des::TdesEde3>;
+ let mut buf = ct.to_vec();
+ let pt = D::new_from_slices(key, iv)
+ .map_err(|_| err("a bad 3DES key or IV"))?
+ .decrypt_padded_mut::<Pkcs7>(&mut buf)
+ .map_err(|_| err("wrong password or damaged data"))?;
+ Ok(Zeroizing::new(pt.to_vec()))
+}
+
+fn decrypt_aes256(key: &[u8], iv: &[u8], ct: &[u8]) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ type D = cbc::Decryptor<aes::Aes256>;
+ let mut buf = ct.to_vec();
+ let pt = D::new_from_slices(key, iv)
+ .map_err(|_| err("a bad AES key or IV"))?
+ .decrypt_padded_mut::<Pkcs7>(&mut buf)
+ .map_err(|_| err("wrong password or damaged data"))?;
+ Ok(Zeroizing::new(pt.to_vec()))
+}
+
+/// The login master key from `key4.db`: `global_salt` (`metaData.item1`),
+/// `item2` (`metaData.item2`), `a11` (`nssPrivate.a11`) and the master password
+/// (empty unless the user set one; a wrong one is an error here).
+pub fn master_key(
+ global_salt: &[u8],
+ item2: &[u8],
+ a11: &[u8],
+ password: &[u8],
+) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ let check = decrypt_pbe_blob(global_salt, password, item2)
+ .map_err(|_| err("a master password is set (or the key database is damaged)"))?;
+ if !check.starts_with(PASSWORD_CHECK) {
+ return Err(err("a master password is set"));
+ }
+ let key = decrypt_pbe_blob(global_salt, password, a11)?;
+ // 3DES keys are 24 bytes; an AES-256 key 32. PKCS#7 padding is gone.
+ Ok(key)
+}
+
+/// Decrypts one `encryptedUsername`/`encryptedPassword` (base64) with the
+/// master key.
+pub fn decrypt_sdr(master: &[u8], b64: &str) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ let raw = base64::engine::general_purpose::STANDARD
+ .decode(b64.trim())
+ .map_err(|_| err("a login field is not base64"))?;
+ let mut top = Der(Der(&raw).expect(0x30)?);
+ top.expect(0x04)?; // key id
+ let mut alg = Der(top.expect(0x30)?);
+ let ct = top.expect(0x04)?;
+ let oid = alg.expect(0x06)?;
+ let iv = alg.expect(0x04)?;
+ if oid == OID_DES_EDE3_CBC {
+ decrypt_3des(
+ master.get(..24).ok_or_else(|| err("a short master key"))?,
+ iv,
+ ct,
+ )
+ } else if oid == OID_AES256_CBC {
+ decrypt_aes256(
+ master.get(..32).ok_or_else(|| err("a short master key"))?,
+ iv,
+ ct,
+ )
+ } else {
+ Err(err("an unknown login cipher"))
+ }
+}
+
+/// Encrypts `plain` as an SDR blob (base64) the way Firefox does for new logins
+/// under a 3DES master key; `iv` is 8 random bytes supplied by the caller.
+pub fn encrypt_sdr(
+ master: &[u8],
+ key_id: &[u8],
+ iv: &[u8; 8],
+ plain: &[u8],
+) -> Result<String, TeleportError> {
+ type E = cbc::Encryptor<des::TdesEde3>;
+ let key = master
+ .get(..24)
+ .ok_or_else(|| err("only 3DES login keys can be written"))?;
+ let ct = E::new_from_slices(key, iv)
+ .map_err(|_| err("a bad 3DES key"))?
+ .encrypt_padded_vec_mut::<Pkcs7>(plain);
+ let alg = [tlv(0x06, OID_DES_EDE3_CBC), tlv(0x04, iv)].concat();
+ let body = [tlv(0x04, key_id), tlv(0x30, &alg), tlv(0x04, &ct)].concat();
+ Ok(base64::engine::general_purpose::STANDARD.encode(tlv(0x30, &body)))
+}
+
+/// Builders for fixtures and tests: a `key4.db`'s three blobs for a 3DES master
+/// key, in the legacy or the PBES2 scheme, built from the same specification
+/// the readers parse (no real Firefox profile is read to make them).
+pub mod testing {
+ use super::*;
+
+ /// `(global_salt, item2, a11)` for `master` (24 bytes) under `password`.
+ pub fn key4_blobs(
+ master: &[u8; 24],
+ password: &[u8],
+ pbes2: bool,
+ ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
+ let global_salt = vec![0x11u8; 20];
+ let entry_salt = vec![0x22u8; 20];
+ let hp = Sha1::digest([&global_salt[..], password].concat()).to_vec();
+ let seal = |plain: &[u8]| -> Vec<u8> {
+ if pbes2 {
+ let mut key = [0u8; 32];
+ pbkdf2::pbkdf2_hmac::<sha2::Sha256>(&hp, &entry_salt, 10_000, &mut key);
+ let iv14 = [0x33u8; 14];
+ let iv = sdr_iv(&iv14);
+ type E = cbc::Encryptor<aes::Aes256>;
+ let ct = E::new_from_slices(&key, &iv)
+ .unwrap()
+ .encrypt_padded_vec_mut::<Pkcs7>(plain);
+ let kdf_params = [
+ tlv(0x04, &entry_salt),
+ tlv(0x02, &[0x27, 0x10]),
+ tlv(0x02, &[0x20]),
+ ]
+ .concat();
+ let kdf = [
+ tlv(
+ 0x06,
+ &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c],
+ ),
+ tlv(0x30, &kdf_params),
+ ]
+ .concat();
+ let enc = [tlv(0x06, OID_AES256_CBC), tlv(0x04, &iv14)].concat();
+ let params = [tlv(0x30, &kdf), tlv(0x30, &enc)].concat();
+ let alg = [tlv(0x06, OID_PBES2), tlv(0x30, &params)].concat();
+ tlv(0x30, &[tlv(0x30, &alg), tlv(0x04, &ct)].concat())
+ } else {
+ let k = legacy_derive(&hp, &entry_salt, 1, 32);
+ type E = cbc::Encryptor<des::TdesEde3>;
+ let ct = E::new_from_slices(&k[..24], &k[k.len().min(40) - 8..])
+ .unwrap()
+ .encrypt_padded_vec_mut::<Pkcs7>(plain);
+ let params = [tlv(0x04, &entry_salt), tlv(0x02, &[1])].concat();
+ let alg = [tlv(0x06, OID_PBE_3DES), tlv(0x30, &params)].concat();
+ tlv(0x30, &[tlv(0x30, &alg), tlv(0x04, &ct)].concat())
+ }
+ };
+ (global_salt.clone(), seal(PASSWORD_CHECK), seal(master))
+ }
+
+ /// A login field as Firefox stores it (3DES master key, fixed IV).
+ pub fn sealed_field(master: &[u8; 24], key_id: &[u8], plain: &[u8]) -> String {
+ encrypt_sdr(master, key_id, &[0x44u8; 8], plain).expect("a 24-byte key seals")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const MASTER: [u8; 24] = *b"0123456789abcdef01234567";
+
+ #[test]
+ fn both_pbe_schemes_unwrap_the_master_key_and_a_wrong_password_is_refused() {
+ for pbes2 in [false, true] {
+ let (salt, item2, a11) = testing::key4_blobs(&MASTER, b"", pbes2);
+ let key = master_key(&salt, &item2, &a11, b"").unwrap();
+ assert_eq!(&key[..24], &MASTER, "pbes2={pbes2}");
+ assert!(
+ master_key(&salt, &item2, &a11, b"hunter2").is_err(),
+ "pbes2={pbes2}"
+ );
+ let (salt, item2, a11) = testing::key4_blobs(&MASTER, b"hunter2", pbes2);
+ assert!(master_key(&salt, &item2, &a11, b"").is_err());
+ assert!(master_key(&salt, &item2, &a11, b"hunter2").is_ok());
+ }
+ }
+
+ #[test]
+ fn a_login_field_round_trips_under_the_master_key() {
+ let sealed = testing::sealed_field(
+ &MASTER,
+ &[0xf8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ b"s3cret-pw",
+ );
+ assert_eq!(&*decrypt_sdr(&MASTER, &sealed).unwrap(), b"s3cret-pw");
+ assert!(decrypt_sdr(&[9u8; 24], &sealed).is_err());
+ assert!(decrypt_sdr(&MASTER, "bm90IGRlcg==").is_err());
+ }
+
+ /// The legacy derivation follows NSS: with `iter` 1 it is the well-known
+ /// `k1 = HMAC(chp, pes||salt)`, `tk = HMAC(chp, pes)`, `k2 = HMAC(chp, tk||salt)`
+ /// sequence (firepwd); here its first block is recomputed independently.
+ #[test]
+ fn the_legacy_derivation_matches_the_nss_hmac_extension() {
+ let hp = [7u8; 20];
+ let salt = [5u8; 20];
+ let chp = Sha1::digest([&hp[..], &salt[..]].concat());
+ let mut pes = salt.to_vec();
+ pes.resize(20, 0);
+ let mut m = <HmacSha1 as Mac>::new_from_slice(&chp).unwrap();
+ m.update(&pes);
+ m.update(&salt);
+ let k1 = m.finalize().into_bytes();
+ let got = legacy_derive(&hp, &salt, 1, 32);
+ assert_eq!(&got[..20], k1.as_slice());
+ assert_eq!(got.len(), 40);
+ }
+}
diff --git a/libs/cua/crates/cua-teleport-bundle/src/layout.rs b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
index e969a91d78..34acc3ff75 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/layout.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
@@ -25,6 +25,8 @@ pub const PROVIDER_IDS: &[&str] = &[
firefox::ID,
electron::SLACK.id,
electron::DISCORD.id,
+ electron::VSCODE.id,
+ electron::NOTION.id,
electron::UNITY_HUB.id,
steam::ID,
whatsapp::ID,
@@ -382,6 +384,35 @@ pub mod electron {
home_extra: &[],
};
+ /// Visual Studio Code. Its userData is `Code` and its Safe Storage item
+ /// is "Code Safe Storage" (account "Code"), from Electron's
+ /// `app_name + " Safe Storage"` with `productName` "Code".
+ pub const VSCODE: ElectronApp = ElectronApp {
+ id: "vscode",
+ display: "Visual Studio Code",
+ app_ids: &[
+ "com.microsoft.VSCode",
+ "vscode",
+ "code",
+ "Visual Studio Code",
+ ],
+ support_dir: "Code",
+ keychain_services: &["Code Safe Storage"],
+ extra: &[],
+ home_extra: &[],
+ };
+
+ /// Notion.
+ pub const NOTION: ElectronApp = ElectronApp {
+ id: "notion",
+ display: "Notion",
+ app_ids: &["notion.id", "notion", "Notion"],
+ support_dir: "Notion",
+ keychain_services: &["Notion Safe Storage"],
+ extra: &[],
+ home_extra: &[],
+ };
+
/// Unity Hub.
///
/// Login lives in accounts.db plus the "unity" Keychain item (service
@@ -430,7 +461,7 @@ pub mod electron {
};
/// The built-in Electron apps, in registry order.
- pub const APPS: &[ElectronApp] = &[SLACK, DISCORD, UNITY_HUB];
+ pub const APPS: &[ElectronApp] = &[SLACK, DISCORD, VSCODE, NOTION, UNITY_HUB];
/// The built-in Electron app with provider id `id`.
pub fn app(id: &str) -> Option<ElectronApp> {
@@ -755,6 +786,8 @@ mod tests {
"firefox",
"slack",
"discord",
+ "vscode",
+ "notion",
"unity-hub",
"steam",
"whatsapp",
diff --git a/libs/cua/crates/cua-teleport-bundle/src/lib.rs b/libs/cua/crates/cua-teleport-bundle/src/lib.rs
index dfe8ab563f..c0a79995e2 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/lib.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/lib.rs
@@ -42,6 +42,7 @@ pub mod bundle;
pub mod chromium_crypto;
pub mod cookies;
mod error;
+pub mod firefox_nss;
pub mod keychain;
pub mod layout;
pub mod local_storage;
diff --git a/libs/cua/crates/cua-teleport/Cargo.toml b/libs/cua/crates/cua-teleport/Cargo.toml
index fb32e34261..96cb0a3b6d 100644
--- a/libs/cua/crates/cua-teleport/Cargo.toml
+++ b/libs/cua/crates/cua-teleport/Cargo.toml
@@ -36,6 +36,9 @@ cbc = { version = "0.1", features = ["alloc"] }
pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] }
sha1 = "0.10"
zeroize = "1"
+# Firefox localStorage values are raw Snappy blocks (dom/localstorage/SnappyUtils.cpp).
+snap = "1"
+tempfile.workspace = true
# The teleport UX core (`ux`): the pinned install manifest the catalog
# classifies against (`cua_agents::installables`, a pure table).
cua-agents.workspace = true
diff --git a/libs/cua/crates/cua-teleport/src/browser_cookies.rs b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
index 5e009c5ffa..771cab9676 100644
--- a/libs/cua/crates/cua-teleport/src/browser_cookies.rs
+++ b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
@@ -214,6 +214,9 @@ pub struct ChromeCookies {
/// [`chromium_crypto::macos_safe_storage_service`].
browser_id: String,
profile_dir: Option<PathBuf>,
+ local_state: Option<PathBuf>,
+ service: Option<&'static str>,
+ dpapi: Option<std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>>,
profile: Option<String>,
}
@@ -225,6 +228,9 @@ impl ChromeCookies {
platform: Platform::current(),
browser_id: "chrome".to_string(),
profile_dir: None,
+ local_state: None,
+ service: None,
+ dpapi: None,
profile: None,
}
}
@@ -244,6 +250,43 @@ impl ChromeCookies {
}
/// Read this exact profile directory.
+ /// The `Local State` holding the Windows key (default: next to the
+ /// profile; see [`crate::safe_storage::default_local_state`]).
+ pub fn with_local_state(mut self, path: impl Into<PathBuf>) -> Self {
+ self.local_state = Some(path.into());
+ self
+ }
+
+ /// The macOS Keychain service holding this app's Safe Storage key, for an
+ /// app that is not a catalog browser (an Electron app: `"Slack Safe
+ /// Storage"`).
+ pub fn with_safe_storage_service(mut self, service: &'static str) -> Self {
+ self.service = Some(service);
+ self
+ }
+
+ /// DPAPI for the Windows key (the system's by default).
+ pub fn with_dpapi(
+ mut self,
+ dpapi: std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>,
+ ) -> Self {
+ self.dpapi = Some(dpapi);
+ self
+ }
+
+ fn keys<'a>(&'a self, dir: &std::path::Path, service: &'static str) -> SafeStorageKeys<'a> {
+ let mut k = SafeStorageKeys::new(self.host.as_ref(), self.platform, service)
+ .with_local_state(
+ self.local_state
+ .clone()
+ .or_else(|| crate::safe_storage::default_local_state(dir)),
+ );
+ if let Some(d) = &self.dpapi {
+ k = k.with_dpapi(d.clone());
+ }
+ k
+ }
+
pub fn with_profile_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.profile_dir = Some(dir.into());
self
@@ -294,6 +337,7 @@ impl ChromeCookies {
)));
}
let service = match self.platform {
+ Platform::MacOS if self.service.is_some() => self.service.unwrap_or_default(),
Platform::MacOS => chromium_crypto::macos_safe_storage_service(&self.browser_id)
.ok_or_else(|| {
TeleportError::Provider(format!(
@@ -311,7 +355,7 @@ impl ChromeCookies {
.iter()
.map(|s| s.trim().to_ascii_lowercase())
.collect();
- let mut keys = SafeStorageKeys::new(self.host.as_ref(), self.platform, service);
+ let mut keys = self.keys(&dir, service);
let mut out = CookieRead::default();
for r in rows {
let site = crate::passwords::site_for_host(&r.host_key);
@@ -884,6 +928,42 @@ mod tests {
assert_eq!(rows.iter().filter(|r| r.app_bound).count(), 1);
}
+ /// A Windows source: `v10` AES-256-GCM cookies under the DPAPI-wrapped
+ /// Local State key (with the Chrome 130 host digest), the app-bound `v20`
+ /// one reported, nothing read from this machine's Keychain.
+ #[test]
+ fn windows_v10_cookies_decrypt_through_local_state_and_v20_is_reported() {
+ use cua_chromium_storage::dpapi::{FakeDpapi, ensure_local_state_key};
+ use sha2::{Digest, Sha256};
+ let root = tempfile::tempdir().unwrap();
+ let profile = root.path().join("Default");
+ let (key, _) =
+ ensure_local_state_key(&root.path().join("Local State"), &FakeDpapi, [6u8; 32])
+ .unwrap();
+ let mut plain = Sha256::digest(b".example.com").to_vec();
+ plain.extend_from_slice(b"win-session");
+ let enc = chromium_crypto::gcm::encrypt(&key, &[2u8; 12], &plain);
+ let mut v20 = b"v20".to_vec();
+ v20.extend_from_slice(&[9u8; 40]);
+ write_modern_cookies_db_for_tests(
+ &profile,
+ &[
+ modern_row(".example.com", "sid", enc, CookieExtras::default()),
+ modern_row(".bank.test", "bound", v20, CookieExtras::default()),
+ ],
+ )
+ .unwrap();
+ let read = ChromeCookies::new(Arc::new(FakeHost::new()))
+ .with_platform(Platform::Windows)
+ .with_profile_dir(&profile)
+ .with_dpapi(Arc::new(FakeDpapi))
+ .read_report(&[])
+ .unwrap();
+ assert_eq!(read.cookies.len(), 1);
+ assert_eq!(read.cookies[0].value.as_str(), "win-session");
+ assert_eq!(read.unavailable.len(), 1);
+ }
+
/// Modern Chrome (96+): only `Network/Cookies` exists.
#[test]
fn reads_a_modern_network_cookies_only_profile() {
diff --git a/libs/cua/crates/cua-teleport/src/firefox_store.rs b/libs/cua/crates/cua-teleport/src/firefox_store.rs
new file mode 100644
index 0000000000..8e8d50a484
--- /dev/null
+++ b/libs/cua/crates/cua-teleport/src/firefox_store.rs
@@ -0,0 +1,688 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Firefox's profile data as Keyvault items, from the profile's own files
+//! (formats in `~/projects/.cua-work/keyvault-v2/browser-formats.md`):
+//!
+//! * profile discovery: `profiles.ini` and `installs.ini`;
+//! * cookies: `cookies.sqlite` (`moz_cookies`, schema 16), plaintext values;
+//! * localStorage: `storage/default/<origin>/ls/data.sqlite` (`data`, values
+//! optionally UTF-16-to-UTF-8 converted and Snappy-compressed);
+//! * saved logins: `logins.json` decrypted with the `key4.db` master key
+//! ([`cua_teleport_bundle::firefox_nss`]), only on request.
+//!
+//! Every read works from a private copy of the file(s), so a running Firefox
+//! is never touched.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use cua_teleport_bundle::cookies::{CookieExtra, CookieItem};
+use cua_teleport_bundle::local_storage::LocalStorageItem;
+use cua_teleport_bundle::logins::{LoginItem, signon_realm};
+
+use crate::TeleportError;
+
+const CHROME_EPOCH_OFFSET_MICROS: i64 = 11_644_473_600_000_000;
+
+fn perr(m: impl std::fmt::Display) -> TeleportError {
+ TeleportError::Provider(m.to_string())
+}
+
+// ---- profile discovery ------------------------------------------------------
+
+/// A profile named in `profiles.ini`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FirefoxProfile {
+ /// `Name=`.
+ pub name: String,
+ /// The profile directory (absolute).
+ pub dir: PathBuf,
+ /// `Default=1` in its section.
+ pub is_default: bool,
+}
+
+fn parse_ini(text: &str) -> Vec<(String, BTreeMap<String, String>)> {
+ let mut out: Vec<(String, BTreeMap<String, String>)> = Vec::new();
+ for line in text.lines() {
+ let line = line.trim();
+ if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
+ out.push((name.to_string(), BTreeMap::new()));
+ } else if let Some((k, v)) = line.split_once('=')
+ && let Some((_, kv)) = out.last_mut()
+ {
+ kv.insert(k.trim().to_string(), v.trim().to_string());
+ }
+ }
+ out
+}
+
+/// The profiles of the Firefox application-data directory `app_data`
+/// (`~/Library/Application Support/Firefox`, `~/.mozilla/firefox`, `%APPDATA%\Mozilla\Firefox`).
+pub fn profiles(app_data: &Path) -> Vec<FirefoxProfile> {
+ let Ok(text) = std::fs::read_to_string(app_data.join("profiles.ini")) else {
+ return Vec::new();
+ };
+ parse_ini(&text)
+ .into_iter()
+ .filter(|(s, kv)| s.starts_with("Profile") && kv.contains_key("Path"))
+ .map(|(_, kv)| {
+ let path = kv["Path"].clone();
+ let relative = kv.get("IsRelative").map(|v| v == "1").unwrap_or(true);
+ FirefoxProfile {
+ name: kv.get("Name").cloned().unwrap_or_default(),
+ dir: if relative {
+ app_data.join(&path)
+ } else {
+ PathBuf::from(&path)
+ },
+ is_default: kv.get("Default").map(|v| v == "1").unwrap_or(false),
+ }
+ })
+ .collect()
+}
+
+/// The profile Firefox opens: the install's `Default=` in `installs.ini`,
+/// else the one marked `Default=1`, else the only one.
+pub fn default_profile(app_data: &Path) -> Option<FirefoxProfile> {
+ let all = profiles(app_data);
+ if let Ok(text) = std::fs::read_to_string(app_data.join("installs.ini")) {
+ for (section, kv) in parse_ini(&text) {
+ // installs.ini sections are the install hash itself.
+ let _ = &section;
+ if let Some(d) = kv.get("Default") {
+ let wanted = app_data.join(d);
+ if let Some(p) = all
+ .iter()
+ .find(|p| p.dir == wanted || p.dir == Path::new(d))
+ {
+ return Some(p.clone());
+ }
+ }
+ }
+ }
+ all.iter()
+ .find(|p| p.is_default)
+ .cloned()
+ .or_else(|| (all.len() == 1).then(|| all[0].clone()))
+}
+
+// ---- a private copy of a SQLite file ----------------------------------------
+
+struct Copy {
+ _dir: tempfile::TempDir,
+ db: PathBuf,
+}
+
+fn private_copy(src: &Path) -> Result<Copy, TeleportError> {
+ let dir = tempfile::Builder::new()
+ .prefix("cua-ff-")
+ .tempdir()
+ .map_err(perr)?;
+ let name = src.file_name().ok_or_else(|| perr("a database path"))?;
+ let db = dir.path().join(name);
+ std::fs::copy(src, &db).map_err(|e| perr(format!("copying {}: {e}", src.display())))?;
+ for suffix in ["-wal", "-shm"] {
+ let mut side = src.as_os_str().to_owned();
+ side.push(suffix);
+ let side = PathBuf::from(side);
+ if side.is_file() {
+ let mut to = db.as_os_str().to_owned();
+ to.push(suffix);
+ let _ = std::fs::copy(&side, PathBuf::from(to));
+ }
+ }
+ Ok(Copy { _dir: dir, db })
+}
+
+fn open(c: &Copy) -> Result<rusqlite::Connection, TeleportError> {
+ rusqlite::Connection::open(&c.db).map_err(|e| perr(format!("opening {}: {e}", c.db.display())))
+}
+
+// ---- cookies ----------------------------------------------------------------
+
+/// The partition key of a Firefox `originAttributes`
+/// (`^partitionKey=%28https%2Cexample.com%29`), as the top-level site Chromium
+/// calls `top_frame_site_key` (`https://example.com`).
+pub fn partition_of(origin_attributes: &str) -> Option<String> {
+ let enc = origin_attributes
+ .trim_start_matches('^')
+ .split('&')
+ .find_map(|p| p.strip_prefix("partitionKey="))?;
+ let dec = percent_decode(enc);
+ let inner = dec.strip_prefix('(')?.strip_suffix(')')?;
+ let mut parts = inner.split(',');
+ let scheme = parts.next()?;
+ let host = parts.next()?;
+ Some(format!("{scheme}://{host}"))
+}
+
+fn percent_decode(s: &str) -> String {
+ let b = s.as_bytes();
+ let mut out = Vec::with_capacity(b.len());
+ let mut i = 0;
+ while i < b.len() {
+ if b[i] == b'%'
+ && i + 2 < b.len()
+ && let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16)
+ {
+ out.push(v);
+ i += 3;
+ } else {
+ out.push(b[i]);
+ i += 1;
+ }
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+/// Every cookie of `profile` as the bundle's cookie rows: `expiry` (ms) and the
+/// microsecond times become Chromium's microseconds since 1601; a partitioned
+/// cookie keeps its partition.
+pub fn read_cookies(profile: &Path) -> Result<Vec<CookieItem>, TeleportError> {
+ let src = profile.join("cookies.sqlite");
+ if !src.is_file() {
+ return Ok(Vec::new());
+ }
+ let copy = private_copy(&src)?;
+ let conn = open(&copy)?;
+ let have: std::collections::HashSet<String> = {
+ let mut st = conn
+ .prepare("PRAGMA table_info(moz_cookies)")
+ .map_err(perr)?;
+ st.query_map([], |r| r.get::<_, String>(1))
+ .map_err(perr)?
+ .filter_map(Result::ok)
+ .collect()
+ };
+ let col = |c: &str, fallback: &str| {
+ if have.contains(c) {
+ c.to_string()
+ } else {
+ fallback.to_string()
+ }
+ };
+ let sql = format!(
+ "SELECT name, value, host, path, expiry, {}, {}, isSecure, isHttpOnly, {}, {} FROM moz_cookies",
+ col("lastAccessed", "0"),
+ col("creationTime", "0"),
+ col("sameSite", "0"),
+ col("originAttributes", "''"),
+ );
+ let mut st = conn.prepare(&sql).map_err(perr)?;
+ let rows = st
+ .query_map([], |r| {
+ let expiry_ms: i64 = r.get(4)?;
+ let last: i64 = r.get(5)?;
+ let created: i64 = r.get(6)?;
+ let attrs: String = r.get::<_, Option<String>>(10)?.unwrap_or_default();
+ let micros = |us: i64| (us > 0).then(|| us + CHROME_EPOCH_OFFSET_MICROS);
+ Ok(CookieItem {
+ host_key: r.get(2)?,
+ name: r.get::<_, Option<String>>(0)?.unwrap_or_default(),
+ value: r
+ .get::<_, Option<String>>(1)?
+ .unwrap_or_default()
+ .into_bytes(),
+ path: r.get::<_, Option<String>>(3)?.unwrap_or_default(),
+ // 0 is a session cookie; Firefox's expiry is milliseconds.
+ expires_utc: if expiry_ms > 0 {
+ expiry_ms * 1000 + CHROME_EPOCH_OFFSET_MICROS
+ } else {
+ 0
+ },
+ is_secure: r.get::<_, i64>(7)? != 0,
+ is_httponly: r.get::<_, i64>(8)? != 0,
+ samesite: r.get::<_, i64>(9)?,
+ extra: CookieExtra {
+ creation_utc: micros(created),
+ last_access_utc: micros(last),
+ partition_key: partition_of(&attrs),
+ ..Default::default()
+ },
+ })
+ })
+ .map_err(perr)?;
+ rows.collect::<Result<Vec<_>, _>>().map_err(perr)
+}
+
+// ---- localStorage -----------------------------------------------------------
+
+/// The origin of a `storage/default/<dir>` name: Firefox escapes `:` and `/`
+/// as `+` (`https+++example.com` is `https://example.com`) and keeps origin
+/// attributes after `^`.
+pub fn origin_of_dir(dir_name: &str) -> String {
+ let base = dir_name.split('^').next().unwrap_or(dir_name);
+ // `scheme+++host[+port]`: the first `+++` is `://`; a later `+` is `:`.
+ match base.split_once("+++") {
+ Some((scheme, rest)) => format!("{scheme}://{}", rest.replace('+', ":")),
+ None => base.to_string(),
+ }
+}
+
+fn decode_value(conversion: i64, compression: i64, blob: &[u8]) -> Result<String, TeleportError> {
+ let bytes = if compression == 1 {
+ snap::raw::Decoder::new()
+ .decompress_vec(blob)
+ .map_err(|e| perr(format!("a localStorage value is not valid Snappy: {e}")))?
+ } else {
+ blob.to_vec()
+ };
+ if conversion == 1 {
+ Ok(String::from_utf8_lossy(&bytes).into_owned())
+ } else {
+ let units: Vec<u16> = bytes
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .collect();
+ Ok(String::from_utf16_lossy(&units))
+ }
+}
+
+/// Every localStorage value under `storage/default/*/ls/data.sqlite`.
+pub fn read_local_storage(profile: &Path) -> Result<Vec<LocalStorageItem>, TeleportError> {
+ let root = profile.join("storage").join("default");
+ let Ok(dirs) = std::fs::read_dir(&root) else {
+ return Ok(Vec::new());
+ };
+ let mut out = Vec::new();
+ for d in dirs.flatten() {
+ let db = d.path().join("ls").join("data.sqlite");
+ if !db.is_file() {
+ continue;
+ }
+ let name = d.file_name().to_string_lossy().into_owned();
+ let copy = private_copy(&db)?;
+ let conn = open(&copy)?;
+ // The exact origin is in the database; the directory name is the
+ // escaped form of it.
+ let origin: String = conn
+ .query_row("SELECT origin FROM database LIMIT 1", [], |r| r.get(0))
+ .unwrap_or_else(|_| origin_of_dir(&name));
+ let mut st = conn
+ .prepare("SELECT key, conversion_type, compression_type, value FROM data")
+ .map_err(perr)?;
+ let rows = st
+ .query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, i64>(1)?,
+ r.get::<_, i64>(2)?,
+ r.get::<_, Vec<u8>>(3)?,
+ ))
+ })
+ .map_err(perr)?;
+ for row in rows {
+ let (key, conv, comp, blob) = row.map_err(perr)?;
+ out.push(LocalStorageItem {
+ origin: origin.clone(),
+ key,
+ value: decode_value(conv, comp, &blob)?,
+ key_raw: None,
+ value_raw: None,
+ });
+ }
+ }
+ Ok(out)
+}
+
+// ---- saved logins -----------------------------------------------------------
+
+/// What a read of the saved logins produced.
+#[derive(Debug, Default)]
+pub struct FirefoxLogins {
+ /// Decrypted logins.
+ pub logins: Vec<LoginItem>,
+ /// Logins that could not be decrypted, never with a value.
+ pub unreadable: Vec<String>,
+}
+
+/// The origin of every saved login (the plaintext `hostname`), so a review can
+/// count passwords per site without decrypting anything.
+pub fn login_hosts(profile: &Path) -> Vec<String> {
+ let Ok(text) = std::fs::read_to_string(profile.join("logins.json")) else {
+ return Vec::new();
+ };
+ let Ok(doc) = serde_json::from_str::<serde_json::Value>(&text) else {
+ return Vec::new();
+ };
+ doc.get("logins")
+ .and_then(|l| l.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|e| {
+ e.get("hostname")
+ .and_then(|h| h.as_str())
+ .map(str::to_string)
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// The master key from `key4.db` (empty master password), or why not.
+pub fn login_master_key(profile: &Path) -> Result<zeroize::Zeroizing<Vec<u8>>, TeleportError> {
+ let src = profile.join("key4.db");
+ if !src.is_file() {
+ return Err(perr(
+ "this profile has no key4.db, so its logins cannot be decrypted",
+ ));
+ }
+ let copy = private_copy(&src)?;
+ let conn = open(&copy)?;
+ let (salt, item2): (Vec<u8>, Vec<u8>) = conn
+ .query_row(
+ "SELECT item1, item2 FROM metaData WHERE id = 'password'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .map_err(|e| perr(format!("Firefox key4.db has no password entry: {e}")))?;
+ let a11: Vec<u8> = conn
+ .query_row(
+ "SELECT a11 FROM nssPrivate WHERE a11 IS NOT NULL LIMIT 1",
+ [],
+ |r| r.get(0),
+ )
+ .map_err(|e| perr(format!("Firefox key4.db has no login key: {e}")))?;
+ cua_teleport_bundle::firefox_nss::master_key(&salt, &item2, &a11, b"")
+}
+
+/// The saved logins of `profile`, decrypted with its (empty-password) master
+/// key. A profile with a master password is refused with a message, never
+/// guessed at. Call this only when the user ticked the passwords.
+pub fn read_logins(profile: &Path) -> Result<FirefoxLogins, TeleportError> {
+ let src = profile.join("logins.json");
+ let Ok(text) = std::fs::read_to_string(&src) else {
+ return Ok(FirefoxLogins::default());
+ };
+ let doc: serde_json::Value =
+ serde_json::from_str(&text).map_err(|e| perr(format!("logins.json: {e}")))?;
+ let Some(entries) = doc.get("logins").and_then(|l| l.as_array()) else {
+ return Ok(FirefoxLogins::default());
+ };
+ let key = login_master_key(profile)?;
+ let mut out = FirefoxLogins::default();
+ for e in entries {
+ let host = e.get("hostname").and_then(|v| v.as_str()).unwrap_or("");
+ // A form login (`formSubmitURL` set) is a web login; an HTTP-auth one
+ // has a realm. Both are origin + username + password.
+ if host.is_empty() {
+ continue;
+ }
+ let field = |k: &str| e.get(k).and_then(|v| v.as_str()).unwrap_or("");
+ let user = cua_teleport_bundle::firefox_nss::decrypt_sdr(&key, field("encryptedUsername"));
+ let pass = cua_teleport_bundle::firefox_nss::decrypt_sdr(&key, field("encryptedPassword"));
+ match (user, pass) {
+ (Ok(u), Ok(p)) => out.logins.push(LoginItem {
+ origin: host.to_string(),
+ username: String::from_utf8_lossy(&u).into_owned(),
+ password: p.to_vec(),
+ signon_realm: signon_realm(host),
+ }),
+ _ => out.unreadable.push(host.to_string()),
+ }
+ }
+ Ok(out)
+}
+
+// ---- fixtures ---------------------------------------------------------------
+
+/// A Firefox-shaped profile for tests: `cookies.sqlite` (schema 16),
+/// localStorage data files and a `key4.db` + `logins.json` pair, built from the
+/// formats' sources (no real profile is read).
+pub mod testing {
+ use super::*;
+ use cua_teleport_bundle::firefox_nss::testing as nss;
+
+ /// The 3DES master key the fixture's `key4.db` wraps.
+ pub const MASTER: [u8; 24] = *b"0123456789abcdef01234567";
+
+ /// `cookies.sqlite` at schema 16 with `rows`
+ /// `(host, name, value, path, expiry_ms, originAttributes)`.
+ pub fn write_cookies(profile: &Path, rows: &[(&str, &str, &str, &str, i64, &str)]) {
+ std::fs::create_dir_all(profile).unwrap();
+ let conn = rusqlite::Connection::open(profile.join("cookies.sqlite")).unwrap();
+ conn.execute_batch(
+ "PRAGMA user_version = 16;
+ CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, originAttributes TEXT NOT NULL DEFAULT '',
+ name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER,
+ creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, inBrowserElement INTEGER DEFAULT 0,
+ sameSite INTEGER DEFAULT 0, schemeMap INTEGER DEFAULT 0, isPartitionedAttributeSet INTEGER DEFAULT 0,
+ CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes));",
+ )
+ .unwrap();
+ for (host, name, value, path, expiry, attrs) in rows {
+ conn.execute(
+ "INSERT INTO moz_cookies (originAttributes, name, value, host, path, expiry, lastAccessed,
+ creationTime, isSecure, isHttpOnly, sameSite, schemeMap, isPartitionedAttributeSet)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1700000000000000, 1690000000000000, 1, 1, 1, 2, ?7)",
+ rusqlite::params![attrs, name, value, host, path, expiry, (!attrs.is_empty()) as i64],
+ )
+ .unwrap();
+ }
+ }
+
+ /// One origin's `ls/data.sqlite`: values as `(key, value, compress)`.
+ pub fn write_local_storage(
+ profile: &Path,
+ dir_name: &str,
+ origin: &str,
+ rows: &[(&str, &str, bool)],
+ ) {
+ let dir = profile.join("storage/default").join(dir_name).join("ls");
+ std::fs::create_dir_all(&dir).unwrap();
+ let conn = rusqlite::Connection::open(dir.join("data.sqlite")).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE database (origin TEXT NOT NULL, usage INTEGER NOT NULL DEFAULT 0,
+ last_vacuum_time INTEGER NOT NULL DEFAULT 0, last_analyze_time INTEGER NOT NULL DEFAULT 0,
+ last_vacuum_size INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE data (key TEXT PRIMARY KEY, utf16_length INTEGER NOT NULL,
+ conversion_type INTEGER NOT NULL, compression_type INTEGER NOT NULL,
+ last_access_time INTEGER NOT NULL DEFAULT 0, value BLOB NOT NULL);",
+ )
+ .unwrap();
+ conn.execute("INSERT INTO database (origin) VALUES (?1)", [origin])
+ .unwrap();
+ for (key, value, compress) in rows {
+ let utf8 = value.as_bytes();
+ let (comp, blob) = if *compress && utf8.len() > 16 {
+ (1, snap::raw::Encoder::new().compress_vec(utf8).unwrap())
+ } else {
+ (0, utf8.to_vec())
+ };
+ conn.execute(
+ "INSERT INTO data (key, utf16_length, conversion_type, compression_type, value)
+ VALUES (?1, ?2, 1, ?3, ?4)",
+ rusqlite::params![key, value.encode_utf16().count() as i64, comp, blob],
+ )
+ .unwrap();
+ }
+ }
+
+ /// `key4.db` (legacy or PBES2) and a `logins.json` of `(origin, user, password)`.
+ pub fn write_logins(
+ profile: &Path,
+ logins: &[(&str, &str, &str)],
+ pbes2: bool,
+ master_password: &[u8],
+ ) {
+ std::fs::create_dir_all(profile).unwrap();
+ let (salt, item2, a11) = nss::key4_blobs(&MASTER, master_password, pbes2);
+ let key_id = vec![0xf8u8; 16];
+ let conn = rusqlite::Connection::open(profile.join("key4.db")).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE metaData (id PRIMARY KEY, item1, item2);
+ CREATE TABLE nssPrivate (id INTEGER PRIMARY KEY, a11, a102);",
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO metaData VALUES ('password', ?1, ?2)",
+ rusqlite::params![salt, item2],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO nssPrivate (a11, a102) VALUES (?1, ?2)",
+ rusqlite::params![a11, key_id],
+ )
+ .unwrap();
+ let entries: Vec<serde_json::Value> = logins
+ .iter()
+ .enumerate()
+ .map(|(i, (o, u, p))| {
+ serde_json::json!({
+ "id": i + 1, "hostname": o, "httpRealm": null, "formSubmitURL": o,
+ "usernameField": "user", "passwordField": "pass",
+ "encryptedUsername": nss::sealed_field(&MASTER, &key_id, u.as_bytes()),
+ "encryptedPassword": nss::sealed_field(&MASTER, &key_id, p.as_bytes()),
+ "encType": 1, "timesUsed": 1
+ })
+ })
+ .collect();
+ std::fs::write(
+ profile.join("logins.json"),
+ serde_json::to_vec(
+ &serde_json::json!({"nextId": logins.len() + 1, "logins": entries, "version": 3}),
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::testing::*;
+ use super::*;
+
+ #[test]
+ fn profiles_follow_installs_ini_then_the_default_flag_then_the_only_one() {
+ let d = tempfile::tempdir().unwrap();
+ std::fs::write(
+ d.path().join("profiles.ini"),
+ "[Profile0]\nName=default\nIsRelative=1\nPath=Profiles/abc.default\n\n\
+ [Profile1]\nName=default-release\nIsRelative=1\nPath=Profiles/xyz.default-release\nDefault=1\n\n\
+ [General]\nStartWithLastProfile=1\n",
+ )
+ .unwrap();
+ assert_eq!(profiles(d.path()).len(), 2);
+ assert_eq!(default_profile(d.path()).unwrap().name, "default-release");
+ std::fs::write(
+ d.path().join("installs.ini"),
+ "[4F96D1932A9F858E]\nDefault=Profiles/abc.default\nLocked=1\n",
+ )
+ .unwrap();
+ assert_eq!(
+ default_profile(d.path()).unwrap().name,
+ "default",
+ "the install's choice wins"
+ );
+ }
+
+ #[test]
+ fn cookies_convert_units_session_and_partition() {
+ let p = tempfile::tempdir().unwrap();
+ write_cookies(
+ p.path(),
+ &[
+ (
+ ".github.com",
+ "user_session",
+ "abc",
+ "/",
+ 1_900_000_000_000,
+ "",
+ ),
+ (
+ "example.com",
+ "sid",
+ "p",
+ "/",
+ 0,
+ "^partitionKey=%28https%2Ctop.example%29",
+ ),
+ ],
+ );
+ let mut c = read_cookies(p.path()).unwrap();
+ c.sort_by(|a, b| a.name.cmp(&b.name));
+ let sid = &c[0];
+ assert_eq!(sid.expires_utc, 0, "a session cookie stays one");
+ assert_eq!(
+ sid.extra.partition_key.as_deref(),
+ Some("https://top.example")
+ );
+ let gh = &c[1];
+ assert_eq!(gh.value, b"abc");
+ assert_eq!(
+ gh.expires_utc,
+ 1_900_000_000_000 * 1000 + CHROME_EPOCH_OFFSET_MICROS
+ );
+ assert_eq!(
+ gh.extra.creation_utc,
+ Some(1_690_000_000_000_000 + CHROME_EPOCH_OFFSET_MICROS)
+ );
+ assert!(gh.is_secure && gh.is_httponly && gh.samesite == 1);
+ assert_eq!(partition_of("^userContextId=1"), None);
+ }
+
+ #[test]
+ fn local_storage_decodes_snappy_and_names_the_origin() {
+ let p = tempfile::tempdir().unwrap();
+ let long = "x".repeat(200);
+ write_local_storage(
+ p.path(),
+ "https+++app.example+8443",
+ "https://app.example:8443",
+ &[
+ ("token", "short", false),
+ ("blob", &long, true),
+ ("emoji", "caf\u{e9} \u{1F642}", false),
+ ],
+ );
+ let mut v = read_local_storage(p.path()).unwrap();
+ v.sort_by(|a, b| a.key.cmp(&b.key));
+ assert!(v.iter().all(|i| i.origin == "https://app.example:8443"));
+ assert_eq!(v[0].value, long, "Snappy values come back whole");
+ assert_eq!(v[1].value, "caf\u{e9} \u{1F642}");
+ assert_eq!(
+ origin_of_dir("https+++example.com^userContextId=1"),
+ "https://example.com"
+ );
+ assert_eq!(
+ origin_of_dir("https+++a.example+8443"),
+ "https://a.example:8443"
+ );
+ }
+
+ #[test]
+ fn logins_decrypt_in_both_schemes_and_a_master_password_is_refused() {
+ for pbes2 in [false, true] {
+ let p = tempfile::tempdir().unwrap();
+ write_logins(
+ p.path(),
+ &[
+ ("https://github.com", "octo", "gh-pw-1"),
+ ("https://example.org", "ada", "pw2"),
+ ],
+ pbes2,
+ b"",
+ );
+ let r = read_logins(p.path()).unwrap();
+ assert_eq!(r.logins.len(), 2, "pbes2={pbes2}");
+ assert_eq!(r.logins[0].username, "octo");
+ assert_eq!(r.logins[0].password, b"gh-pw-1");
+ assert_eq!(r.logins[0].signon_realm, "https://github.com/");
+ let locked = tempfile::tempdir().unwrap();
+ write_logins(
+ locked.path(),
+ &[("https://a.test", "u", "p")],
+ pbes2,
+ b"master",
+ );
+ let err = read_logins(locked.path()).unwrap_err().to_string();
+ assert!(err.contains("master password"), "{err}");
+ }
+ // No logins.json: nothing, not an error.
+ let empty = tempfile::tempdir().unwrap();
+ assert!(read_logins(empty.path()).unwrap().logins.is_empty());
+ }
+}
diff --git a/libs/cua/crates/cua-teleport/src/lib.rs b/libs/cua/crates/cua-teleport/src/lib.rs
index 6526bfe636..38c516bea6 100644
--- a/libs/cua/crates/cua-teleport/src/lib.rs
+++ b/libs/cua/crates/cua-teleport/src/lib.rs
@@ -29,6 +29,7 @@ pub mod biometric;
pub mod browser_cookies;
pub mod cookies;
pub mod favicons;
+pub mod firefox_store;
pub mod host;
pub mod keychain;
pub mod passwords;
diff --git a/libs/cua/crates/cua-teleport/src/passwords.rs b/libs/cua/crates/cua-teleport/src/passwords.rs
index 4c07abda75..7d460bd80a 100644
--- a/libs/cua/crates/cua-teleport/src/passwords.rs
+++ b/libs/cua/crates/cua-teleport/src/passwords.rs
@@ -143,6 +143,8 @@ pub struct ChromePasswords {
host: std::sync::Arc<dyn HostEffects>,
platform: Platform,
profile_dir: Option<PathBuf>,
+ local_state: Option<PathBuf>,
+ dpapi: Option<std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>>,
profile: Option<String>,
}
@@ -153,6 +155,8 @@ impl ChromePasswords {
host,
platform: Platform::current(),
profile_dir: None,
+ local_state: None,
+ dpapi: None,
profile: None,
}
}
@@ -164,6 +168,35 @@ impl ChromePasswords {
}
/// Read this exact profile directory.
+ /// The `Local State` holding the Windows key (default: next to the
+ /// profile; see [`crate::safe_storage::default_local_state`]).
+ pub fn with_local_state(mut self, path: impl Into<PathBuf>) -> Self {
+ self.local_state = Some(path.into());
+ self
+ }
+
+ /// DPAPI for the Windows key (the system's by default).
+ pub fn with_dpapi(
+ mut self,
+ dpapi: std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>,
+ ) -> Self {
+ self.dpapi = Some(dpapi);
+ self
+ }
+
+ fn keys<'a>(&'a self, dir: &std::path::Path, service: &'static str) -> SafeStorageKeys<'a> {
+ let mut k = SafeStorageKeys::new(self.host.as_ref(), self.platform, service)
+ .with_local_state(
+ self.local_state
+ .clone()
+ .or_else(|| crate::safe_storage::default_local_state(dir)),
+ );
+ if let Some(d) = &self.dpapi {
+ k = k.with_dpapi(d.clone());
+ }
+ k
+ }
+
pub fn with_profile_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.profile_dir = Some(dir.into());
self
@@ -217,7 +250,7 @@ impl ChromePasswords {
.iter()
.map(|s| s.trim().to_ascii_lowercase())
.collect();
- let mut keys = SafeStorageKeys::new(self.host.as_ref(), self.platform, MAC_SAFE_STORAGE);
+ let mut keys = self.keys(&dir, MAC_SAFE_STORAGE);
let mut out = PasswordRead::default();
for r in rows {
let Some(origin) = origin_of(&r.origin_url) else {
@@ -560,4 +593,39 @@ mod tests {
.to_string();
assert!(err.contains("Windows"), "{err}");
}
+
+ /// A Windows source: `v10` AES-GCM passwords unwrap through Local State; an
+ /// app-bound one is reported, not fatal.
+ #[test]
+ fn windows_v10_passwords_decrypt_through_local_state() {
+ use cua_chromium_storage::dpapi::{FakeDpapi, ensure_local_state_key};
+ let root = tempfile::tempdir().unwrap();
+ let profile = root.path().join("Default");
+ let (key, _) =
+ ensure_local_state_key(&root.path().join("Local State"), &FakeDpapi, [8u8; 32])
+ .unwrap();
+ let mut v20 = b"v20".to_vec();
+ v20.extend_from_slice(&[1u8; 40]);
+ write_login_data_for_tests(
+ &profile,
+ &[
+ (
+ "https://github.com/login",
+ "octo",
+ cua_teleport_bundle::chromium_crypto::gcm::encrypt(&key, &[4u8; 12], b"gh-pw"),
+ ),
+ ("https://bank.test/", "ada", v20),
+ ],
+ )
+ .unwrap();
+ let read = ChromePasswords::new(Arc::new(FakeHost::new()))
+ .with_platform(Platform::Windows)
+ .with_profile_dir(&profile)
+ .with_dpapi(Arc::new(FakeDpapi))
+ .read_report(&[])
+ .unwrap();
+ assert_eq!(read.logins.len(), 1);
+ assert_eq!(&**read.logins[0].password, "gh-pw");
+ assert_eq!(read.unavailable.len(), 1);
+ }
}
diff --git a/libs/cua/crates/cua-teleport/src/providers/chrome.rs b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
index 27014e243b..76127c1f82 100644
--- a/libs/cua/crates/cua-teleport/src/providers/chrome.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
@@ -454,51 +454,6 @@ fn manifest_item(
}
}
-/// `Local Storage/` as items: the LevelDB is read from a private copy and its
-/// values travel in the reserved `localstorage.json` entry, which the receiver
-/// writes into the destination browser's own store (a raw copy of LevelDB
-/// files would replace whatever the destination holds, and tear if the source
-/// is running). Anything else under `Local Storage/` stays a file. When the
-/// LevelDB cannot be read, the whole directory is copied as before.
-fn add_local_storage<W: std::io::Write>(
- writer: &mut cua_teleport_bundle::bundle::BundleWriter<W>,
- profile_dir: &Path,
- disk: &Path,
- rel: &str,
-) -> Result<()> {
- match cua_chromium_storage::read(&cua_chromium_storage::store_dir(profile_dir)) {
- Ok(items) => {
- if !items.is_empty() {
- writer.add_bytes(
- cua_chromium_storage::LOCAL_STORAGE_ENTRY,
- 0o600,
- &cua_teleport_bundle::local_storage::serialize(&items),
- )?;
- }
- if let Ok(entries) = std::fs::read_dir(disk) {
- for entry in entries.flatten() {
- let path = entry.path();
- let name = entry.file_name().to_string_lossy().into_owned();
- if name == "leveldb" {
- continue;
- }
- let child = format!("{rel}/{name}");
- match std::fs::symlink_metadata(&path) {
- Ok(m) if m.is_file() => add_file_best_effort(writer, &path, &child)?,
- Ok(m) if m.is_dir() => add_dir_recursive(writer, &path, &child)?,
- _ => {}
- }
- }
- }
- Ok(())
- }
- Err(e) => {
- tracing::warn!(error = %e, "localStorage could not be read as items; copying its files");
- add_dir_recursive(writer, disk, rel)
- }
- }
-}
-
/// Where curated profile file `name` lives on disk: `Cookies` resolves to
/// whichever of `Network/Cookies` and the root file is newer; every
/// other file is at the profile root.
@@ -831,7 +786,12 @@ impl ExportProvider for ChromeProvider {
let disk = profile_dir.join(dir);
if disk.is_dir() {
if *dir == "Local Storage" {
- add_local_storage(&mut writer, &profile_dir, &disk, &rel)?;
+ crate::providers::util::add_local_storage(
+ &mut writer,
+ &profile_dir,
+ &disk,
+ &rel,
+ )?;
} else {
add_dir_recursive(&mut writer, &disk, &rel)?;
}
diff --git a/libs/cua/crates/cua-teleport/src/providers/electron.rs b/libs/cua/crates/cua-teleport/src/providers/electron.rs
index 367ea70fdf..001f8ffa6f 100644
--- a/libs/cua/crates/cua-teleport/src/providers/electron.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/electron.rs
@@ -24,7 +24,8 @@ use crate::host::{HostEffects, default_host};
use crate::keychain;
pub use crate::layout::electron::ElectronApp;
use crate::layout::electron::{
- DISCORD, PROFILE_DIRS, PROFILE_FILES, SLACK, UNITY_HUB, app_support_root, home_rel, rel,
+ DISCORD, NOTION, PROFILE_DIRS, PROFILE_FILES, SLACK, UNITY_HUB, VSCODE, app_support_root,
+ home_rel, rel,
};
use crate::providers::util::{add_dir_recursive, add_file_best_effort, dir_len, file_len};
use crate::{
@@ -39,6 +40,10 @@ pub struct ElectronProvider {
/// Whether the macOS Keychain Safe Storage read is attempted. Disabled by
/// [`Self::without_keychain`] so tests never touch the real Keychain.
allow_keychain: bool,
+ /// Cookies and localStorage travel as decrypted items for the destination
+ /// to re-encrypt under its own key, not as raw files plus this machine's
+ /// Safe Storage key ([`Self::structured`]).
+ structured: bool,
/// Test/override hook: the home the source profile is resolved under.
home_override: Option<PathBuf>,
/// Every Keychain, `$HOME` and authorization effect goes through this.
@@ -51,6 +56,7 @@ impl ElectronProvider {
app,
max_total_bytes: DEFAULT_MAX_TOTAL_BYTES,
allow_keychain: true,
+ structured: false,
home_override: None,
host: default_host(),
}
@@ -72,6 +78,14 @@ impl ElectronProvider {
self
}
+ /// Send cookies and localStorage as items (Chromium underneath: the same
+ /// readers and re-encryption as a Chromium browser), with the app's own
+ /// Safe Storage key never leaving this machine. Off by default.
+ pub fn structured(mut self) -> Self {
+ self.structured = true;
+ self
+ }
+
/// Disable the macOS Keychain Safe Storage read (tests stay hermetic — no
/// `security` call, no access prompt).
pub fn without_keychain(mut self) -> Self {
@@ -97,6 +111,16 @@ impl ElectronProvider {
/// Unity Hub (also carries the Unity Version Control credentials and the
/// Editor entitlement from `$HOME`; see [`UNITY_HUB`]).
+ pub fn vscode() -> Self {
+ Self::new(VSCODE)
+ }
+
+ /// Notion.
+ pub fn notion() -> Self {
+ Self::new(NOTION)
+ }
+
+ /// Unity Hub.
pub fn unity_hub() -> Self {
Self::new(UNITY_HUB)
}
@@ -259,7 +283,27 @@ impl ExportProvider for ElectronProvider {
);
let wants = |r: &str| include.is_none_or(|set| set.contains(r));
+ // Structured: the cookies as decrypted rows and localStorage as items
+ // (their raw files, and the Local State that holds the key, stay home).
+ let mut raw_skip: Vec<&str> = Vec::new();
+ if self.structured {
+ self.add_structured(&mut writer, app, &dir, &wants)?;
+ raw_skip = vec![
+ "Cookies",
+ "Cookies-journal",
+ "Cookies-wal",
+ "Cookies-shm",
+ "Network/Cookies",
+ "Network/Cookies-wal",
+ "Network/Cookies-shm",
+ "Local State",
+ ];
+ }
+
for (name, _s) in PROFILE_FILES {
+ if raw_skip.contains(name) {
+ continue;
+ }
if wants(&rel(name)) {
let disk = dir.join(name);
if disk.is_file() {
@@ -271,7 +315,21 @@ impl ExportProvider for ElectronProvider {
if wants(&rel(name)) {
let disk = dir.join(name);
if disk.is_dir() {
- add_dir_recursive(&mut writer, &disk, &rel(name))?;
+ if self.structured && *name == "Local State" {
+ continue;
+ }
+ if self.structured && *name == "Local Storage" {
+ // Items, not LevelDB files (and any other file under it
+ // stays a file).
+ crate::providers::util::add_local_storage(
+ &mut writer,
+ &dir,
+ &disk,
+ &rel(name),
+ )?;
+ } else {
+ add_dir_recursive(&mut writer, &disk, &rel(name))?;
+ }
}
}
}
@@ -310,6 +368,11 @@ impl ExportProvider for ElectronProvider {
let trust = self.app.macos_app();
let mut items = Vec::new();
for service in self.app.keychain_services {
+ // The Safe Storage key stays here when the values travel as
+ // items: the destination makes its own.
+ if self.structured && service.ends_with(" Safe Storage") {
+ continue;
+ }
match keychain::probe_generic(&*self.host, service, None) {
keychain::KeychainRead::Read(mut item) => {
item.trust_app = Some(trust.clone());
@@ -347,6 +410,53 @@ impl ExportProvider for ElectronProvider {
}
}
+impl ElectronProvider {
+ /// Cookies as decrypted rows in the reserved `cookies.json` entry, read
+ /// with the app's own Safe Storage key (macOS Keychain), the fixed Linux
+ /// key, or the Windows Local State key. A failure to read is an error: a
+ /// signed-out transfer that looks like a success helps nobody.
+ fn add_structured<W: Write>(
+ &self,
+ writer: &mut BundleWriter<W>,
+ app: &AppRef,
+ dir: &std::path::Path,
+ wants: &dyn Fn(&str) -> bool,
+ ) -> Result<()> {
+ let wants_cookies = ["Cookies", "Network/Cookies"]
+ .iter()
+ .any(|n| wants(&rel(n)));
+ if !wants_cookies || (app.platform == Platform::MacOS && !self.allow_keychain) {
+ return Ok(());
+ }
+ if cua_teleport_bundle::layout::chrome::cookies_store(dir).is_file() {
+ let mut reader = crate::browser_cookies::ChromeCookies::new(self.host.clone())
+ .with_platform(app.platform)
+ .with_profile_dir(dir.to_path_buf());
+ if let Some(service) = self
+ .app
+ .keychain_services
+ .iter()
+ .find(|s| s.ends_with(" Safe Storage"))
+ {
+ reader = reader.with_safe_storage_service(service);
+ }
+ let cookies = reader.read(&[])?;
+ if !cookies.is_empty() {
+ let items: Vec<cua_teleport_bundle::cookies::CookieItem> = cookies
+ .into_iter()
+ .map(crate::browser_cookies::DecryptedCookie::into_item)
+ .collect();
+ writer.add_bytes(
+ cua_teleport_bundle::cookies::COOKIES_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::cookies::serialize(&items),
+ )?;
+ }
+ }
+ Ok(())
+ }
+}
+
fn pretty(name: &str) -> &str {
match name {
"Cookies" => "Cookies and session",
@@ -654,4 +764,81 @@ mod tests {
"only checked cookies: {paths:?}"
);
}
+
+ /// Chromium underneath: structured, the cookies travel decrypted in the
+ /// reserved entry and localStorage as items, no raw store and no Local
+ /// State, and the app's Safe Storage key never leaves.
+ #[test]
+ fn structured_slack_sends_cookies_and_local_storage_as_items() {
+ use cua_teleport_bundle::bundle::BundleReader;
+ let home = tempfile::tempdir().unwrap();
+ let user_data = home.path().join(".config/Slack");
+ std::fs::create_dir_all(&user_data).unwrap();
+ let key = cua_teleport_bundle::chromium_crypto::derive_key(
+ cua_teleport_bundle::chromium_crypto::LINUX_V10_PASSWORD,
+ cua_teleport_bundle::chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ );
+ crate::browser_cookies::write_network_cookies_db_for_tests(
+ &user_data,
+ &[crate::browser_cookies::TestCookieRow {
+ host_key: ".slack.com",
+ name: "d",
+ encrypted_value: cua_teleport_bundle::chromium_crypto::encrypt_v10(
+ &key,
+ b"xoxd-session",
+ ),
+ path: "/",
+ expires_utc: 0,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 0,
+ }],
+ )
+ .unwrap();
+ std::fs::write(user_data.join("Local State"), br#"{"x":1}"#).unwrap();
+ cua_chromium_storage::write(
+ &cua_chromium_storage::store_dir(&user_data),
+ &[cua_chromium_storage::LocalStorageItem {
+ origin: "https://app.slack.com".into(),
+ key: "localConfig_v2".into(),
+ value: "{}".into(),
+ key_raw: None,
+ value_raw: None,
+ }],
+ 1,
+ )
+ .unwrap();
+ let provider = ElectronProvider::slack()
+ .structured()
+ .with_home(home.path());
+ let app = AppRef {
+ app_id: "slack".into(),
+ display_name: "Slack".into(),
+ platform: Platform::Linux,
+ };
+ let mut buf = Vec::new();
+ provider
+ .capture_selected(&app, TransferScope::FullProfile, None, &mut buf)
+ .unwrap();
+ let entries = BundleReader::open(std::io::Cursor::new(buf))
+ .unwrap()
+ .read_all()
+ .unwrap();
+ let paths: Vec<&str> = entries.iter().map(|e| e.rel_path.as_str()).collect();
+ let get = |p: &str| entries.iter().find(|e| e.rel_path == p).unwrap();
+ let cookies = cua_teleport_bundle::cookies::parse(
+ &get(cua_teleport_bundle::cookies::COOKIES_ENTRY).bytes,
+ );
+ assert_eq!(cookies[0].value, b"xoxd-session");
+ let ls = cua_teleport_bundle::local_storage::parse(
+ &get(cua_teleport_bundle::local_storage::LOCAL_STORAGE_ENTRY).bytes,
+ );
+ assert_eq!(ls[0].key, "localConfig_v2");
+ assert!(
+ !paths.iter().any(|p| p.contains("Cookies")
+ || p.ends_with("Local State")
+ || p.contains("leveldb")),
+ "{paths:?}"
+ );
+ }
}
diff --git a/libs/cua/crates/cua-teleport/src/providers/firefox.rs b/libs/cua/crates/cua-teleport/src/providers/firefox.rs
index fc4a3fbab9..27b129ba22 100644
--- a/libs/cua/crates/cua-teleport/src/providers/firefox.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/firefox.rs
@@ -31,6 +31,10 @@ use crate::{
pub struct FirefoxProvider {
profile_dir_override: Option<PathBuf>,
max_total_bytes: u64,
+ /// Cookies, localStorage and (ticked) logins travel as items for the
+ /// destination to write into its own stores, not as raw database files
+ /// ([`Self::structured`]).
+ structured: bool,
/// Every `$HOME`, Keychain and authorization effect goes through this.
host: Arc<dyn HostEffects>,
}
@@ -46,10 +50,20 @@ impl FirefoxProvider {
Self {
profile_dir_override: None,
max_total_bytes: DEFAULT_MAX_TOTAL_BYTES,
+ structured: false,
host: default_host(),
}
}
+ /// Send cookies, localStorage and ticked logins as items. Saved logins are
+ /// decrypted with the profile's own `key4.db` only when `logins.json` is
+ /// in the selection (an opt-in), and a profile with a master password is
+ /// refused rather than guessed at.
+ pub fn structured(mut self) -> Self {
+ self.structured = true;
+ self
+ }
+
/// Act on `host` instead of [`default_host`].
pub fn with_host(mut self, host: Arc<dyn HostEffects>) -> Self {
self.host = host;
@@ -227,11 +241,20 @@ impl ExportProvider for FirefoxProvider {
}
if scope == TransferScope::FullProfile {
+ if self.structured {
+ self.add_items(&mut writer, &profile, &wants)?;
+ }
for (name, _sensitive) in PROFILE_FILES {
let rel = format!("{BUNDLE_PREFIX}/{name}");
if !wants(&rel) {
continue;
}
+ // Items replace the raw stores (and the key database that
+ // only the raw login file needs).
+ if self.structured && matches!(*name, "cookies.sqlite" | "logins.json" | "key4.db")
+ {
+ continue;
+ }
let disk = profile.join(name);
if disk.is_file() {
add_file_best_effort(&mut writer, &disk, &rel)?;
@@ -244,7 +267,12 @@ impl ExportProvider for FirefoxProvider {
}
let disk = profile.join(name);
if disk.is_dir() {
- add_dir_recursive(&mut writer, &disk, &rel)?;
+ if self.structured && *name == "storage" {
+ // localStorage is items; the rest of storage stays files.
+ add_storage_without_ls(&mut writer, &disk, &rel)?;
+ } else {
+ add_dir_recursive(&mut writer, &disk, &rel)?;
+ }
}
}
}
@@ -254,6 +282,87 @@ impl ExportProvider for FirefoxProvider {
}
}
+impl FirefoxProvider {
+ fn add_items<W: Write>(
+ &self,
+ writer: &mut BundleWriter<W>,
+ profile: &Path,
+ wants: &dyn Fn(&str) -> bool,
+ ) -> Result<()> {
+ let rel = |n: &str| format!("{BUNDLE_PREFIX}/{n}");
+ if wants(&rel("cookies.sqlite")) {
+ let items = crate::firefox_store::read_cookies(profile)?;
+ if !items.is_empty() {
+ writer.add_bytes(
+ cua_teleport_bundle::cookies::COOKIES_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::cookies::serialize(&items),
+ )?;
+ }
+ }
+ if wants(&rel("storage")) {
+ let items = crate::firefox_store::read_local_storage(profile)?;
+ if !items.is_empty() {
+ writer.add_bytes(
+ cua_teleport_bundle::local_storage::LOCAL_STORAGE_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::local_storage::serialize(&items),
+ )?;
+ }
+ }
+ // Passwords: only because `logins.json` was explicitly selected.
+ if wants(&rel("logins.json")) {
+ let read = crate::firefox_store::read_logins(profile)?;
+ if !read.logins.is_empty() {
+ writer.add_bytes(
+ cua_teleport_bundle::logins::LOGINS_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::logins::serialize(&read.logins),
+ )?;
+ }
+ }
+ Ok(())
+ }
+}
+
+/// `storage/` as files except each origin's `ls/` (its localStorage, sent as
+/// items).
+fn add_storage_without_ls<W: Write>(
+ writer: &mut BundleWriter<W>,
+ disk: &Path,
+ rel: &str,
+) -> Result<()> {
+ fn walk<W: Write>(
+ writer: &mut BundleWriter<W>,
+ dir: &Path,
+ rel: &str,
+ depth: usize,
+ ) -> Result<()> {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return Ok(());
+ };
+ for e in entries.flatten() {
+ let name = e.file_name().to_string_lossy().into_owned();
+ let path = e.path();
+ let child = format!("{rel}/{name}");
+ let Ok(meta) = std::fs::symlink_metadata(&path) else {
+ continue;
+ };
+ if meta.is_dir() {
+ // storage/default/<origin>/ls
+ if depth == 2 && name == "ls" {
+ continue;
+ }
+ walk(writer, &path, &child, depth + 1)?;
+ } else if meta.is_file() {
+ add_file_best_effort(writer, &path, &child)?;
+ }
+ }
+ Ok(())
+ }
+ walk(writer, disk, rel, 0)
+}
+
/// Resolve the active profile directory under a Firefox root by reading
/// `installs.ini` (install-scoped default), then `profiles.ini`.
fn resolve_active_profile(root: &Path) -> Option<PathBuf> {
@@ -830,4 +939,89 @@ mod tests {
fn mozlz4_rejects_bad_magic() {
assert!(mozlz4_decode(b"NOTMOZLZ4....").is_none());
}
+
+ /// Structured: cookies, localStorage and (selected) logins are items; the
+ /// raw stores and the key database stay home; the rest of storage stays files.
+ #[test]
+ fn structured_export_sends_items_not_the_raw_stores() {
+ use crate::firefox_store::testing::*;
+ use cua_teleport_bundle::bundle::BundleReader;
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Profiles/abc.default-release");
+ write_cookies(
+ &profile,
+ &[(
+ ".github.com",
+ "user_session",
+ "abc",
+ "/",
+ 1_900_000_000_000,
+ "",
+ )],
+ );
+ write_local_storage(
+ &profile,
+ "https+++github.com",
+ "https://github.com",
+ &[("theme", "dark", false)],
+ );
+ std::fs::create_dir_all(profile.join("storage/default/https+++github.com/idb")).unwrap();
+ std::fs::write(
+ profile.join("storage/default/https+++github.com/idb/x.sqlite"),
+ b"idb",
+ )
+ .unwrap();
+ write_logins(
+ &profile,
+ &[("https://github.com", "octo", "gh-pw")],
+ false,
+ b"",
+ );
+ let provider = FirefoxProvider::new()
+ .structured()
+ .with_profile_dir(&profile);
+ let run = |include: Option<HashSet<String>>| {
+ let mut buf = Vec::new();
+ provider
+ .capture_selected(
+ &app(Platform::Linux),
+ TransferScope::FullProfile,
+ include.as_ref(),
+ &mut buf,
+ )
+ .unwrap();
+ BundleReader::open(std::io::Cursor::new(buf))
+ .unwrap()
+ .read_all()
+ .unwrap()
+ };
+ let entries = run(None);
+ let paths: Vec<&str> = entries.iter().map(|e| e.rel_path.as_str()).collect();
+ for items in ["cookies.json", "localstorage.json", "logins.json"] {
+ assert!(paths.contains(&items), "{items} in {paths:?}");
+ }
+ assert!(
+ !paths.iter().any(|p| p.ends_with("cookies.sqlite")
+ || p.ends_with("key4.db")
+ || p.contains("/ls/")),
+ "{paths:?}"
+ );
+ assert!(
+ paths.iter().any(|p| p.ends_with("idb/x.sqlite")),
+ "other storage stays files"
+ );
+ let logins = cua_teleport_bundle::logins::parse(
+ &entries
+ .iter()
+ .find(|e| e.rel_path == "logins.json")
+ .unwrap()
+ .bytes,
+ );
+ assert_eq!(logins[0].password, b"gh-pw");
+ // Passwords are an opt-in: a selection without logins.json sends none.
+ let default: HashSet<String> = ["firefox/cookies.sqlite".to_string()].into_iter().collect();
+ let entries = run(Some(default));
+ assert!(entries.iter().any(|e| e.rel_path == "cookies.json"));
+ assert!(!entries.iter().any(|e| e.rel_path == "logins.json"));
+ }
}
diff --git a/libs/cua/crates/cua-teleport/src/providers/util.rs b/libs/cua/crates/cua-teleport/src/providers/util.rs
index a151b29edf..5df260f0e2 100644
--- a/libs/cua/crates/cua-teleport/src/providers/util.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/util.rs
@@ -79,3 +79,48 @@ pub fn dir_len(dir: &Path) -> u64 {
pub fn file_len(path: &Path) -> u64 {
std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}
+
+/// `Local Storage/` as items: the LevelDB is read from a private copy and its
+/// values travel in the reserved `localstorage.json` entry, which the receiver
+/// writes into the destination browser's own store (a raw copy of LevelDB
+/// files would replace whatever the destination holds, and tear if the source
+/// is running). Anything else under `Local Storage/` stays a file. When the
+/// LevelDB cannot be read, the whole directory is copied as before.
+pub fn add_local_storage<W: std::io::Write>(
+ writer: &mut cua_teleport_bundle::bundle::BundleWriter<W>,
+ profile_dir: &Path,
+ disk: &Path,
+ rel: &str,
+) -> Result<()> {
+ match cua_chromium_storage::read(&cua_chromium_storage::store_dir(profile_dir)) {
+ Ok(items) => {
+ if !items.is_empty() {
+ writer.add_bytes(
+ cua_chromium_storage::LOCAL_STORAGE_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::local_storage::serialize(&items),
+ )?;
+ }
+ if let Ok(entries) = std::fs::read_dir(disk) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if name == "leveldb" {
+ continue;
+ }
+ let child = format!("{rel}/{name}");
+ match std::fs::symlink_metadata(&path) {
+ Ok(m) if m.is_file() => add_file_best_effort(writer, &path, &child)?,
+ Ok(m) if m.is_dir() => add_dir_recursive(writer, &path, &child)?,
+ _ => {}
+ }
+ }
+ }
+ Ok(())
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "localStorage could not be read as items; copying its files");
+ add_dir_recursive(writer, disk, rel)
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-teleport/src/registry.rs b/libs/cua/crates/cua-teleport/src/registry.rs
index 4e5a1080ea..d4aefd1bcc 100644
--- a/libs/cua/crates/cua-teleport/src/registry.rs
+++ b/libs/cua/crates/cua-teleport/src/registry.rs
@@ -75,11 +75,20 @@ impl ExportRegistry {
}
let mut registry = Self::new();
registry.register(Box::new(chrome));
- registry.register(Box::new(FirefoxProvider::new().with_host(host.clone())));
- registry.register(Box::new(ElectronProvider::slack().with_host(host.clone())));
registry.register(Box::new(
- ElectronProvider::discord().with_host(host.clone()),
+ FirefoxProvider::new().structured().with_host(host.clone()),
));
+ // Electron apps are Chromium underneath: their cookies and
+ // localStorage travel as items, re-encrypted for the destination's
+ // own key (see `ElectronProvider::structured`).
+ for provider in [
+ ElectronProvider::slack(),
+ ElectronProvider::discord(),
+ ElectronProvider::vscode(),
+ ElectronProvider::notion(),
+ ] {
+ registry.register(Box::new(provider.structured().with_host(host.clone())));
+ }
registry.register(Box::new(
ElectronProvider::unity_hub().with_host(host.clone()),
));
diff --git a/libs/cua/crates/cua-teleport/src/safe_storage.rs b/libs/cua/crates/cua-teleport/src/safe_storage.rs
index a017c1ffef..7f01293a97 100644
--- a/libs/cua/crates/cua-teleport/src/safe_storage.rs
+++ b/libs/cua/crates/cua-teleport/src/safe_storage.rs
@@ -17,6 +17,17 @@ use zeroize::{Zeroize, Zeroizing};
use crate::host::{EffectKind, HostCommand, HostEffects};
use crate::{Platform, TeleportError};
+/// The `Local State` file next to a profile: inside it (an Electron app's
+/// userData) or in its parent (a browser's `User Data` above `Default`).
+pub fn default_local_state(profile_dir: &std::path::Path) -> Option<std::path::PathBuf> {
+ let inside = profile_dir.join("Local State");
+ if inside.is_file() {
+ return Some(inside);
+ }
+ let above = profile_dir.parent()?.join("Local State");
+ above.is_file().then_some(above)
+}
+
/// Lazily resolves and caches a Chromium-family browser's Safe Storage
/// key(s) on this host. One instance per (browser, profile) read.
pub struct SafeStorageKeys<'a> {
@@ -28,6 +39,11 @@ pub struct SafeStorageKeys<'a> {
macos_service: &'static str,
v10: Option<Zeroizing<[u8; 16]>>,
v11: Option<Zeroizing<[u8; 16]>>,
+ /// Windows: the browser's `Local State` and the DPAPI that unwraps its
+ /// key (`v10` is AES-256-GCM under it).
+ local_state: Option<std::path::PathBuf>,
+ dpapi: std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>,
+ windows_key: Option<Zeroizing<[u8; 32]>>,
}
impl<'a> SafeStorageKeys<'a> {
@@ -40,7 +56,42 @@ impl<'a> SafeStorageKeys<'a> {
macos_service,
v10: None,
v11: None,
+ local_state: None,
+ dpapi: std::sync::Arc::new(cua_chromium_storage::dpapi::SystemDpapi),
+ windows_key: None,
+ }
+ }
+
+ /// The `Local State` file whose `os_crypt.encrypted_key` holds this
+ /// browser's Windows key.
+ pub fn with_local_state(mut self, path: Option<std::path::PathBuf>) -> Self {
+ self.local_state = path;
+ self
+ }
+
+ /// DPAPI to unwrap the Windows key with (the system's by default).
+ pub fn with_dpapi(
+ mut self,
+ dpapi: std::sync::Arc<dyn cua_chromium_storage::dpapi::Dpapi>,
+ ) -> Self {
+ self.dpapi = dpapi;
+ self
+ }
+
+ /// The Windows AES-256-GCM key (read once from `Local State`).
+ fn windows_key(&mut self) -> Result<&[u8; 32], TeleportError> {
+ if self.windows_key.is_none() {
+ let path = self.local_state.clone().ok_or_else(|| {
+ TeleportError::Provider(
+ "this browser's Local State was not found, so its Windows key cannot be read"
+ .into(),
+ )
+ })?;
+ let key = cua_chromium_storage::dpapi::local_state_key(&path, self.dpapi.as_ref())
+ .map_err(|e| TeleportError::Provider(format!("Windows browser key: {e}")))?;
+ self.windows_key = Some(key);
}
+ Ok(self.windows_key.as_deref().expect("set above"))
}
/// The `v10` key: the macOS Keychain secret (prompting for
@@ -68,7 +119,11 @@ impl<'a> SafeStorageKeys<'a> {
secret.zeroize();
key
}
- Platform::Windows => return Err(windows_unsupported()),
+ Platform::Windows => {
+ return Err(TeleportError::Provider(
+ "Windows browsers use AES-GCM, not a v10 CBC key".into(),
+ ));
+ }
};
self.v10 = Some(key);
}
@@ -116,6 +171,15 @@ impl<'a> SafeStorageKeys<'a> {
/// `password_value` or `Cookies`' `encrypted_value`), resolving whichever
/// key its prefix names.
pub fn decrypt(&mut self, value: &[u8]) -> Result<Zeroizing<Vec<u8>>, TeleportError> {
+ if self.platform == Platform::Windows {
+ // `v10` is AES-256-GCM under the DPAPI-wrapped Local State key.
+ // `v20` (app-bound) is refused by callers before they get here.
+ if value.starts_with(b"v20") {
+ return Err(app_bound_unsupported());
+ }
+ let key = *self.windows_key()?;
+ return chromium_crypto::gcm::decrypt(&key, value);
+ }
match value.get(..3) {
Some(b"v10") => {
let key = *self.v10()?;
@@ -126,7 +190,6 @@ impl<'a> SafeStorageKeys<'a> {
chromium_crypto::decrypt(&key, &value[3..])
}
Some(b"v20") => Err(app_bound_unsupported()),
- _ if self.platform == Platform::Windows => Err(windows_unsupported()),
_ => Err(TeleportError::Provider(
"a Safe-Storage-encrypted value uses an encryption version this build does not \
know"
@@ -148,14 +211,6 @@ fn app_bound_unsupported() -> TeleportError {
)
}
-fn windows_unsupported() -> TeleportError {
- TeleportError::Provider(
- "decrypting Chromium's Safe-Storage-encrypted values on Windows (DPAPI) is not \
- supported yet"
- .into(),
- )
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -223,10 +278,34 @@ mod tests {
}
#[test]
- fn windows_is_refused_for_every_key() {
+ fn windows_has_no_cbc_keys_and_decrypts_v10_gcm_through_local_state() {
+ use cua_chromium_storage::dpapi::{Dpapi, FakeDpapi, ensure_local_state_key};
let host = FakeHost::new();
let mut keys = SafeStorageKeys::new(&host, Platform::Windows, "Chrome Safe Storage");
assert!(keys.v10().unwrap_err().to_string().contains("Windows"));
assert!(keys.v11().is_err());
+ // Without a Local State there is nothing to decrypt with.
+ assert!(
+ keys.decrypt(b"v10-anything-long-enough-for-a-nonce-and-tag")
+ .is_err()
+ );
+ let dir = tempfile::tempdir().unwrap();
+ let ls = dir.path().join("Local State");
+ let (key, _) = ensure_local_state_key(&ls, &FakeDpapi, [5u8; 32]).unwrap();
+ let enc = chromium_crypto::gcm::encrypt(&key, &[1u8; 12], b"win-cookie");
+ let dpapi: std::sync::Arc<dyn Dpapi> = std::sync::Arc::new(FakeDpapi);
+ let mut keys = SafeStorageKeys::new(&host, Platform::Windows, "Chrome Safe Storage")
+ .with_local_state(Some(ls))
+ .with_dpapi(dpapi);
+ assert_eq!(&*keys.decrypt(&enc).unwrap(), b"win-cookie");
+ // App-bound values are never attempted.
+ let mut v20 = b"v20".to_vec();
+ v20.extend_from_slice(&[0u8; 40]);
+ assert!(
+ keys.decrypt(&v20)
+ .unwrap_err()
+ .to_string()
+ .contains("App-Bound")
+ );
}
}
diff --git a/libs/cua/crates/cua-teleport/src/ux/catalog.rs b/libs/cua/crates/cua-teleport/src/ux/catalog.rs
index 0038a2a5f3..7afbed7d0d 100644
--- a/libs/cua/crates/cua-teleport/src/ux/catalog.rs
+++ b/libs/cua/crates/cua-teleport/src/ux/catalog.rs
@@ -621,18 +621,28 @@ mod tests {
let p = providers();
let hint = TargetHint::default();
let vs = classify(
- &app("Visual Studio Code", "com.microsoft.VSCode"),
+ &app("Blender", "org.blenderfoundation.blender"),
&p,
Platform::MacOS,
&hint,
);
- assert_eq!(vs.id, "vscode");
+ assert_eq!(vs.id, "blender");
assert_eq!(vs.capability, Capability::InstallOnly);
assert_eq!(vs.moves, [MoveKind::AppOnly, MoveKind::AppWithFiles]);
assert!(
- matches!(vs.install, Some(InstallSource::Manifest { ref id, .. }) if id == "vscode")
+ matches!(vs.install, Some(InstallSource::Manifest { ref id, .. }) if id == "blender")
+ );
+ assert_eq!(vs.launch.as_ref().unwrap().bin, "blender");
+
+ // VS Code is Chromium underneath: its signed-in state teleports too.
+ let code = classify(
+ &app("Visual Studio Code", "com.microsoft.VSCode"),
+ &p,
+ Platform::MacOS,
+ &hint,
);
- assert_eq!(vs.launch.as_ref().unwrap().bin, "code");
+ assert_eq!(code.capability, Capability::Full);
+ assert_eq!(code.provider_id.as_deref(), Some("vscode"));
let ff = classify(
&app("Firefox", "org.mozilla.firefox"),
diff --git a/libs/cua/crates/cua-teleport/src/ux/mod.rs b/libs/cua/crates/cua-teleport/src/ux/mod.rs
index 3fffe37f28..b5d26eb939 100644
--- a/libs/cua/crates/cua-teleport/src/ux/mod.rs
+++ b/libs/cua/crates/cua-teleport/src/ux/mod.rs
@@ -207,9 +207,9 @@ mod tests {
// The host's own app format: the catalog enumerates what this OS lists.
testing::fixture_host_app(
root.path(),
- "Visual Studio Code",
- "com.microsoft.VSCode",
- "code",
+ "Blender",
+ "org.blenderfoundation.blender",
+ "blender",
);
testing::fixture_host_app(
root.path(),
@@ -260,7 +260,7 @@ mod tests {
let e = entry_for_path(&reg, b.to_str().unwrap(), &TargetHint::default()).unwrap();
assert_eq!((e.id.as_str(), e.capability), ("firefox", Capability::Full));
assert!(entry_for_path(&reg, "/tmp/x.txt", &TargetHint::default()).is_err());
- let e = entry_for_name(&reg, "Visual Studio Code", &TargetHint::default());
+ let e = entry_for_name(&reg, "Blender", &TargetHint::default());
assert_eq!(e.capability, Capability::InstallOnly);
}
}
diff --git a/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift b/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift
index b165a31904..507f101bbb 100644
--- a/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift
+++ b/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift
@@ -221,7 +221,7 @@ let safari = fixtureEntry("com.apple.Safari", "Safari", .unsupported, moves: [],
roots: [root.path], spaceOs: "linux", spaceArch: "aarch64",
recentsPath: root.appendingPathComponent("r.json").path))
#expect(rows.map(\.id) == ["firefox", "vscode", "com.example.notes"])
- #expect(rows.map(\.capability) == [.full, .installOnly, .unsupported])
+ #expect(rows.map(\.capability) == [.full, .full, .unsupported])
let drop = t.parseDrop(items: [root.appendingPathComponent("Firefox.app").absoluteString])
#expect(drop.kind == "app")
#expect(try t.catalogEntryForPath(path: drop.apps[0], options: nil).id == "firefox")
diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index b30d0014a0..b4ca493fdd 100644
--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aead"
version = "0.6.1"
@@ -29,6 +39,20 @@ dependencies = [
"cpufeatures 0.2.17",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead 0.5.2",
+ "aes",
+ "cipher 0.4.4",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -685,7 +709,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
- "aead",
+ "aead 0.6.1",
"chacha20",
"cipher 0.5.2",
"poly1305",
@@ -934,6 +958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -987,6 +1012,15 @@ version = "0.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -1055,9 +1089,12 @@ dependencies = [
"base64 0.22.1",
"cua-teleport-bundle",
"rusty-leveldb",
+ "serde_json",
"tempfile",
"thiserror 2.0.20",
"tracing",
+ "windows-sys 0.61.2",
+ "zeroize",
]
[[package]]
@@ -1499,6 +1536,8 @@ dependencies = [
"serde_json",
"sha1",
"sha2 0.10.9",
+ "snap",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -1510,7 +1549,11 @@ name = "cua-teleport-bundle"
version = "0.1.0"
dependencies = [
"aes",
+ "aes-gcm",
+ "base64 0.22.1",
"cbc",
+ "des",
+ "hmac",
"pbkdf2",
"serde",
"serde_json",
@@ -1825,6 +1868,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "des"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -2471,6 +2523,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "gio"
version = "0.18.4"
@@ -4116,6 +4178,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openkoalabot-example-core"
version = "0.1.0"
@@ -4458,7 +4526,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures 0.3.1",
- "universal-hash",
+ "universal-hash 0.6.1",
+]
+
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
]
[[package]]
@@ -6944,6 +7024,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "universal-hash"
version = "0.6.1"