π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
rust/cli: integrate SRP + simplify auth flows
Prateek Sunal39bb7a786078
diff --git a/rust/cli/Cargo.lock b/rust/cli/Cargo.lockindex d70135a8a9..79fbe65f70 100644--- a/rust/cli/Cargo.lock+++ b/rust/cli/Cargo.lock@@ -130,12 +130,6 @@ dependencies = ["windows-sys 0.60.2",]-[[package]]-name = "anyhow"-version = "1.0.99"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"-[[package]]name = "arbitrary"version = "1.4.2"@@ -157,12 +151,6 @@ dependencies = ["password-hash",]-[[package]]-name = "arraydeque"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"-[[package]]name = "arrayref"version = "0.3.9"@@ -185,17 +173,6 @@ dependencies = ["serde_json",]-[[package]]-name = "async-trait"-version = "0.1.89"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"-dependencies = [- "proc-macro2",- "quote",- "syn",-]-[[package]]name = "atoi"version = "2.0.0"@@ -232,12 +209,6 @@ dependencies = ["windows-targets 0.52.6",]-[[package]]-name = "base64"-version = "0.21.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"-[[package]]name = "base64"version = "0.22.1"@@ -457,25 +428,6 @@ dependencies = ["crossbeam-utils",]-[[package]]-name = "config"-version = "0.14.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "68578f196d2a33ff61b27fae256c3164f65e36382648e30666dde05b8cc9dfdf"-dependencies = [- "async-trait",- "convert_case",- "json5",- "nom",- "pathdiff",- "ron",- "rust-ini",- "serde",- "serde_json",- "toml",- "yaml-rust2",-]-[[package]]name = "console"version = "0.15.11"@@ -495,41 +447,12 @@ version = "0.9.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"-[[package]]-name = "const-random"-version = "0.1.18"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"-dependencies = [- "const-random-macro",-]--[[package]]-name = "const-random-macro"-version = "0.1.16"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"-dependencies = [- "getrandom 0.2.16",- "once_cell",- "tiny-keccak",-]-[[package]]name = "constant_time_eq"version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"-[[package]]-name = "convert_case"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"-dependencies = [- "unicode-segmentation",-]-[[package]]name = "core-foundation"version = "0.9.4"@@ -604,12 +527,6 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"-[[package]]-name = "crunchy"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"-[[package]]name = "crypto-common"version = "0.1.6"@@ -755,15 +672,6 @@ dependencies = ["syn",]-[[package]]-name = "dlv-list"-version = "0.5.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"-dependencies = [- "const-random",-]-[[package]]name = "dotenvy"version = "0.15.7"@@ -799,9 +707,10 @@ name = "ente-core"version = "0.0.1"dependencies = ["argon2",- "base64 0.22.1",+ "base64","blake2b_simd","crypto_secretstream",+ "getrandom 0.2.16","hex","md-5","rand_core 0.6.4",@@ -809,6 +718,8 @@ dependencies = ["salsa20","serde","serde_json",+ "sha2",+ "srp","subtle","thiserror 2.0.16","x25519-dalek",@@ -820,11 +731,9 @@ dependencies = [name = "ente-rs"version = "0.0.1"dependencies = [- "anyhow",- "base64 0.22.1",+ "base64","chrono","clap",- "config","dialoguer","dirs","ente-core",@@ -833,27 +742,17 @@ dependencies = ["indicatif","log","mockito",- "num-bigint","open",- "rand 0.8.5","reqwest",- "rpassword","rusqlite","serde","serde_json",- "serde_yaml",- "sha2","sqlx",- "srp",- "srp6","tempdir",- "tempfile","thiserror 2.0.16","tokio",- "toml","urlencoding","uuid",- "walkdir","zeroize","zip",]@@ -1175,7 +1074,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"dependencies = ["ahash",- "allocator-api2",][[package]]@@ -1189,15 +1087,6 @@ dependencies = ["foldhash",]-[[package]]-name = "hashlink"-version = "0.8.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7"-dependencies = [- "hashbrown 0.14.5",-]-[[package]]name = "hashlink"version = "0.9.1"@@ -1228,12 +1117,6 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"-[[package]]-name = "hex-literal"-version = "1.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bcaaec4551594c969335c98c903c1397853d4198408ea609190f420500f6be71"-[[package]]name = "hkdf"version = "0.12.4"@@ -1369,7 +1252,7 @@ version = "0.1.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8d9b05277c7e8da2c93a568989bb6207bef0112e8d17df7a6eda4a3cf143bc5e"dependencies = [- "base64 0.22.1",+ "base64","bytes","futures-channel","futures-core",@@ -1655,17 +1538,6 @@ dependencies = ["wasm-bindgen",]-[[package]]-name = "json5"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1"-dependencies = [- "pest",- "pest_derive",- "serde",-]-[[package]]name = "lazy_static"version = "1.5.0"@@ -1786,12 +1658,6 @@ version = "0.3.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"-[[package]]-name = "minimal-lexical"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"-[[package]]name = "miniz_oxide"version = "0.8.9"@@ -1853,16 +1719,6 @@ dependencies = ["tempfile",]-[[package]]-name = "nom"-version = "7.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"-dependencies = [- "memchr",- "minimal-lexical",-]-[[package]]name = "num-bigint"version = "0.4.6"@@ -1871,8 +1727,6 @@ checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"dependencies = ["num-integer","num-traits",- "rand 0.8.5",- "serde",][[package]]@@ -2022,16 +1876,6 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"-[[package]]-name = "ordered-multimap"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"-dependencies = [- "dlv-list",- "hashbrown 0.14.5",-]-[[package]]name = "parking"version = "2.2.1"@@ -2103,50 +1947,6 @@ version = "2.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"-[[package]]-name = "pest"-version = "2.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1db05f56d34358a8b1066f67cbb203ee3e7ed2ba674a6263a1d5ec6db2204323"-dependencies = [- "memchr",- "thiserror 2.0.16",- "ucd-trie",-]--[[package]]-name = "pest_derive"-version = "2.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb056d9e8ea77922845ec74a1c4e8fb17e7c218cc4fc11a15c5d25e189aa40bc"-dependencies = [- "pest",- "pest_generator",-]--[[package]]-name = "pest_generator"-version = "2.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "87e404e638f781eb3202dc82db6760c8ae8a1eeef7fb3fa8264b2ef280504966"-dependencies = [- "pest",- "pest_meta",- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "pest_meta"-version = "2.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "edd1101f170f5903fde0914f899bb503d9ff5271d7ba76bbb70bea63690cc0d5"-dependencies = [- "pest",- "sha2",-]-[[package]]name = "pin-project-lite"version = "0.2.16"@@ -2475,7 +2275,7 @@ version = "0.12.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d429f34c8092b2d42c7c93cec323bb4adeb7c67698f70839adec842ec10c7ceb"dependencies = [- "base64 0.22.1",+ "base64","bytes","encoding_rs","futures-core",@@ -2530,29 +2330,6 @@ dependencies = ["windows-sys 0.52.0",]-[[package]]-name = "ron"-version = "0.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94"-dependencies = [- "base64 0.21.7",- "bitflags",- "serde",- "serde_derive",-]--[[package]]-name = "rpassword"-version = "7.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "66d4c8b64f049c6721ec8ccec37ddfc3d641c4a7fca57e8f2a89de509c73df39"-dependencies = [- "libc",- "rtoolbox",- "windows-sys 0.59.0",-]-[[package]]name = "rsa"version = "0.9.8"@@ -2573,16 +2350,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rtoolbox"-version = "0.0.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a7cc970b249fbe527d6e02e0a227762c9108b2f49d81094fe357ffc6d14d7f6f"-dependencies = [- "libc",- "windows-sys 0.52.0",-]-[[package]]name = "rusqlite"version = "0.32.1"@@ -2598,16 +2365,6 @@ dependencies = ["smallvec",]-[[package]]-name = "rust-ini"-version = "0.20.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3e0698206bcb8882bf2a9ecb4c1e7785db57ff052297085a6efd4fe42302068a"-dependencies = [- "cfg-if",- "ordered-multimap",-]-[[package]]name = "rustc-demangle"version = "0.1.26"@@ -2710,15 +2467,6 @@ dependencies = ["cipher",]-[[package]]-name = "same-file"-version = "1.0.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"-dependencies = [- "winapi-util",-]-[[package]]name = "schannel"version = "0.1.27"@@ -2808,15 +2556,6 @@ dependencies = ["serde",]-[[package]]-name = "serde_spanned"-version = "0.6.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"-dependencies = [- "serde",-]-[[package]]name = "serde_urlencoded"version = "0.7.1"@@ -2829,19 +2568,6 @@ dependencies = ["serde",]-[[package]]-name = "serde_yaml"-version = "0.9.34+deprecated"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"-dependencies = [- "indexmap",- "itoa",- "ryu",- "serde",- "unsafe-libyaml",-]-[[package]]name = "sha1"version = "0.10.6"@@ -2970,7 +2696,7 @@ version = "0.8.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"dependencies = [- "base64 0.22.1",+ "base64","bytes","crc","crossbeam-queue",@@ -3043,7 +2769,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"dependencies = ["atoi",- "base64 0.22.1",+ "base64","bitflags","byteorder","bytes",@@ -3085,7 +2811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"dependencies = ["atoi",- "base64 0.22.1",+ "base64","bitflags","byteorder","crc",@@ -3152,21 +2878,6 @@ dependencies = ["subtle",]-[[package]]-name = "srp6"-version = "1.0.0-beta.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "279b6afb40ed1f544789f35d689a0b5fadb2f404de70102cdd8918fdce25e47f"-dependencies = [- "hex-literal",- "num-bigint",- "num-traits",- "rand 0.9.2",- "serde",- "sha2",- "thiserror 2.0.16",-]-[[package]]name = "stable_deref_trait"version = "1.2.0"@@ -3330,15 +3041,6 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c"-[[package]]-name = "tiny-keccak"-version = "2.0.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"-dependencies = [- "crunchy",-]-[[package]]name = "tinystr"version = "0.8.1"@@ -3439,47 +3141,6 @@ dependencies = ["tokio",]-[[package]]-name = "toml"-version = "0.8.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"-dependencies = [- "serde",- "serde_spanned",- "toml_datetime",- "toml_edit",-]--[[package]]-name = "toml_datetime"-version = "0.6.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"-dependencies = [- "serde",-]--[[package]]-name = "toml_edit"-version = "0.22.27"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"-dependencies = [- "indexmap",- "serde",- "serde_spanned",- "toml_datetime",- "toml_write",- "winnow",-]--[[package]]-name = "toml_write"-version = "0.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"-[[package]]name = "tower"version = "0.5.2"@@ -3569,12 +3230,6 @@ version = "1.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"-[[package]]-name = "ucd-trie"-version = "0.1.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"-[[package]]name = "unicode-bidi"version = "0.3.18"@@ -3602,12 +3257,6 @@ version = "0.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0"-[[package]]-name = "unicode-segmentation"-version = "1.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"-[[package]]name = "unicode-width"version = "0.2.1"@@ -3624,12 +3273,6 @@ dependencies = ["subtle",]-[[package]]-name = "unsafe-libyaml"-version = "0.2.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"-[[package]]name = "untrusted"version = "0.9.0"@@ -3689,16 +3332,6 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"-[[package]]-name = "walkdir"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"-dependencies = [- "same-file",- "winapi-util",-]-[[package]]name = "want"version = "0.3.1"@@ -3859,15 +3492,6 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"-[[package]]-name = "winapi-util"-version = "0.1.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22"-dependencies = [- "windows-sys 0.60.2",-]-[[package]]name = "winapi-x86_64-pc-windows-gnu"version = "0.4.0"@@ -4166,15 +3790,6 @@ version = "0.53.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"-[[package]]-name = "winnow"-version = "0.7.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95"-dependencies = [- "memchr",-]-[[package]]name = "wit-bindgen-rt"version = "0.39.0"@@ -4224,17 +3839,6 @@ dependencies = ["lzma-sys",]-[[package]]-name = "yaml-rust2"-version = "0.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8902160c4e6f2fb145dbe9d6760a75e3c9522d8bf796ed7047c85919ac7115f8"-dependencies = [- "arraydeque",- "encoding_rs",- "hashlink 0.8.4",-]-[[package]]name = "yoke"version = "0.8.0"diff --git a/rust/cli/Cargo.toml b/rust/cli/Cargo.tomlindex 5a8aafaa76..f4a4513f22 100644--- a/rust/cli/Cargo.toml+++ b/rust/cli/Cargo.toml@@ -8,14 +8,11 @@ repository = "https://github.com/ente-io/ente"license = "AGPL-3.0-only"[dependencies]-# CLI and configuration+# CLIclap = { version = "4.5", features = ["derive", "env"] }-config = "0.14"-ente-core = { path = "../core" }+ente-core = { path = "../core", features = ["srp"] }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"-serde_yaml = "0.9"-toml = "0.8"# Async runtime and networkingtokio = { version = "1.41", features = ["full"] }@@ -26,35 +23,24 @@ futures = "0.3"base64 = "0.22"zeroize = { version = "1.8", features = ["derive"] }-# SRP authentication-srp = "0.6"-srp6 = "1.0.0-beta.1"-num-bigint = { version = "0.4", features = ["rand"] }-sha2 = "0.10"-urlencoding = "2.1"-rand = "0.8"-# Storagerusqlite = { version = "0.32", features = ["bundled", "serde_json"] }sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite", "migrate"], optional = true }# Utilitiesthiserror = "2.0"-anyhow = "1.0"log = "0.4"env_logger = "0.11"dirs = "5.0"chrono = "0.4"uuid = { version = "1.11", features = ["serde", "v4"] }-rpassword = "7.3"+urlencoding = "2.1"indicatif = "0.17"dialoguer = "0.11"open = "5.0"# File operations-walkdir = "2.5"zip = "2.2"-tempfile = "3.14"[dev-dependencies]mockito = "1.6"diff --git a/rust/cli/README.md b/rust/cli/README.mdindex 51383603ee..2515b16493 100644--- a/rust/cli/README.md+++ b/rust/cli/README.md@@ -1,9 +1,5 @@WIP Ente Rust CLI.-## Notes--- Uses `ente-core` with the `srp` feature enabled for SRP login support.-## Development```bashdiff --git a/rust/cli/src/api/auth.rs b/rust/cli/src/api/auth.rsindex cde0924d47..8e9946b98e 100644--- a/rust/cli/src/api/auth.rs+++ b/rust/cli/src/api/auth.rs@@ -1,101 +1,21 @@-//! Authentication API client.-//!-//! Handles HTTP API calls for authentication. Crypto operations are delegated-//! to ente-core's auth module.-use crate::api::client::ApiClient;use crate::api::models::{AuthResponse, CreateSrpSessionRequest, CreateSrpSessionResponse, GetSrpAttributesResponse,SendOtpRequest, SrpAttributes, VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,};-use crate::models::error::{Error, Result};+use crate::models::error::Result;use base64::{Engine, engine::general_purpose::STANDARD};-use rand::RngCore;-use sha2::Sha256;-use srp::client::{SrpClient as SrpClientInner, SrpClientVerifier};-use srp::groups::G_4096;use uuid::Uuid;-// Use ente-core for crypto operations-use ente_core::auth::SrpAttributes as CoreSrpAttributes;--struct SrpSession {- inner: SrpClientInner<'static, Sha256>,- identity: Vec<u8>,- login_key: Vec<u8>,- salt: Vec<u8>,- a_private: Vec<u8>,- a_public: Vec<u8>,- verifier: Option<SrpClientVerifier<Sha256>>,-}+use ente_core::auth::{SrpAttributes as CoreSrpAttributes, SrpSession};-impl SrpSession {- fn new(srp_user_id: &str, srp_salt: &[u8], login_key: &[u8]) -> Result<Self> {- if login_key.len() != 16 {- return Err(Error::Srp(format!(- "login key must be 16 bytes, got {}",- login_key.len()- )));- }-- let client = SrpClientInner::<Sha256>::new(&G_4096);-- let mut a_private = vec![0u8; 64];- rand::rngs::OsRng.fill_bytes(&mut a_private);-- let a_public = client.compute_public_ephemeral(&a_private);- let identity = srp_user_id.as_bytes().to_vec();-- Ok(Self {- inner: client,- identity,- login_key: login_key.to_vec(),- salt: srp_salt.to_vec(),- a_private,- a_public,- verifier: None,- })- }-- fn public_a(&self) -> Vec<u8> {- self.a_public.clone()- }+const SRP_A_LEN: usize = 512; // 4096-bit group- fn compute_m1(&mut self, server_b: &[u8]) -> Result<Vec<u8>> {- let verifier = self- .inner- .process_reply(- &self.a_private,- &self.identity,- &self.login_key,- &self.salt,- server_b,- )- .map_err(|e| Error::Srp(format!("Failed to process server response: {:?}", e)))?;-- let proof = verifier.proof().to_vec();- self.verifier = Some(verifier);-- Ok(proof)- }-- #[allow(dead_code)]- fn verify_m2(&self, server_m2: &[u8]) -> Result<()> {- let verifier = self- .verifier- .as_ref()- .ok_or_else(|| Error::Srp("Client proof not computed".to_string()))?;-- verifier- .verify_server(server_m2)- .map_err(|_| Error::Srp("Server proof verification failed".to_string()))- }-}--fn pad_bytes(data: &[u8], len: usize) -> Vec<u8> {+fn pad_left(data: &[u8], len: usize) -> Vec<u8> {if data.len() >= len {return data.to_vec();}+let mut padded = vec![0u8; len - data.len()];padded.extend_from_slice(data);padded@@ -115,10 +35,6 @@ impl<'a> AuthClient<'a> {pub async fn get_srp_attributes(&self, email: &str) -> Result<SrpAttributes> {let url = format!("/users/srp/attributes?email={}", urlencoding::encode(email));let response: GetSrpAttributesResponse = self.api.get(&url, None).await?;- log::debug!(- "SRP attributes response: is_email_mfa_enabled={}",- response.attributes.is_email_mfa_enabled- );Ok(response.attributes)}@@ -161,7 +77,7 @@ impl<'a> AuthClient<'a> {.await}- /// Complete SRP authentication flow using ente-core credential derivation+ /// Complete SRP authentication flowpub async fn login_with_srp(&self,email: &str,@@ -170,8 +86,6 @@ impl<'a> AuthClient<'a> {// Step 1: Get SRP attributeslet srp_attrs = self.get_srp_attributes(email).await?;- // Step 2: Derive SRP credentials and build SRP client state- println!("Deriving encryption key (this may take a few seconds)...");let core_attrs = CoreSrpAttributes {srp_user_id: srp_attrs.srp_user_id.to_string(),srp_salt: srp_attrs.srp_salt.clone(),@@ -181,21 +95,16 @@ impl<'a> AuthClient<'a> {is_email_mfa_enabled: srp_attrs.is_email_mfa_enabled,};- let creds = ente_core::auth::derive_srp_credentials(password, &core_attrs)- .map_err(|e| Error::Crypto(e.to_string()))?;- let srp_salt = STANDARD- .decode(&srp_attrs.srp_salt)- .map_err(|e| Error::Crypto(format!("Invalid srp_salt: {}", e)))?;-- let mut srp_session = SrpSession::new(- &srp_attrs.srp_user_id.to_string(),- &srp_salt,- &creds.login_key,- )?;+ // Step 2: Derive SRP credentials+ let creds = ente_core::auth::derive_srp_credentials(password, &core_attrs)?;- // Step 3: Get client's public value and create session- let a_pub = pad_bytes(&srp_session.public_a(), 512);+ // Step 3: Start SRP session+ let srp_salt = STANDARD.decode(&srp_attrs.srp_salt)?;+ let mut srp_session =+ SrpSession::new(&core_attrs.srp_user_id, &srp_salt, &creds.login_key)?;+ let a_pub = pad_left(&srp_session.public_a(), SRP_A_LEN);+ // Step 4: Create SRP sessionlog::debug!("Creating SRP session...");let session = self.create_srp_session(&srp_attrs.srp_user_id, &a_pub)@@ -205,25 +114,14 @@ impl<'a> AuthClient<'a> {// Add a small delay to avoid potential rate limitingtokio::time::sleep(tokio::time::Duration::from_millis(100)).await;- // Step 4: Decode server's public key- let server_b = STANDARD- .decode(&session.srp_b)- .map_err(|e| Error::Crypto(format!("Invalid server B: {}", e)))?;-- // Step 5: Compute proof using server's public value+ // Step 5: Compute and send proof+ let server_b = STANDARD.decode(&session.srp_b)?;let proof = srp_session.compute_m1(&server_b)?;- let proof = pad_bytes(&proof, 32);let auth_response = self.verify_srp_session(&srp_attrs.srp_user_id, &session.session_id, &proof).await?;- // TODO: Verify server proof if provided- // if let Some(srp_m2) = &auth_response.srp_m2 {- // let server_proof = STANDARD.decode(srp_m2)?;- // srp_session.verify_m2(&server_proof)?;- // }-Ok((auth_response, creds.kek))}@@ -269,22 +167,19 @@ impl<'a> AuthClient<'a> {#[cfg(test)]mod tests {use super::*;- use base64::engine::general_purpose::STANDARD;#[test]- fn test_login_key_derivation() {+ fn test_derive_srp_credentials() {ente_core::crypto::init().unwrap();- // Test that ente-core's key derivation works correctlylet password = "test_password";- let salt = b"test_salt_16byte"; // Exactly 16 byteslet srp_attrs = CoreSrpAttributes {srp_user_id: "test-user".to_string(),srp_salt: STANDARD.encode([0u8; 16]),mem_limit: 67108864, // Interactiveops_limit: 2,- kek_salt: STANDARD.encode(salt),+ kek_salt: STANDARD.encode(b"test_salt_16byte"),is_email_mfa_enabled: false,};@@ -293,6 +188,7 @@ mod tests {let session = SrpSession::new(&srp_attrs.srp_user_id, &srp_salt, &creds.login_key).unwrap();assert_eq!(creds.kek.len(), 32);+ assert_eq!(creds.login_key.len(), 16);assert!(!session.public_a().is_empty());}}diff --git a/rust/cli/src/api/client.rs b/rust/cli/src/api/client.rsindex f9001e92b4..3fc2da1c5f 100644--- a/rust/cli/src/api/client.rs+++ b/rust/cli/src/api/client.rs@@ -27,6 +27,37 @@ pub struct ApiError {pub message: Option<String>,}+fn make_api_error(method: &str, path: &str, status: StatusCode, body: String) -> Error {+ if status.is_server_error() {+ log::error!("API request failed: status={status}");+ } else if status == StatusCode::TOO_MANY_REQUESTS {+ log::warn!("API request failed: status={status}");+ } else {+ log::debug!("API request failed: status={status}");+ }++ log::debug!("API request: {method} {path}");++ if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&body) {+ log::debug!(+ "API error body: {}",+ serde_json::to_string_pretty(&error_json).unwrap_or(body.clone())+ );+ } else {+ log::debug!("API error body: {body}");+ }++ let message = serde_json::from_str::<ApiError>(&body)+ .ok()+ .and_then(|e| e.code.or(e.message))+ .unwrap_or_else(|| status.to_string());++ Error::ApiError {+ status: status.as_u16(),+ message,+ }+}+pub struct ApiClient {client: Client,download_client: Client,@@ -39,13 +70,11 @@ pub struct ApiClient {impl ApiClient {pub fn new(base_url: Option<String>) -> Result<Self> {- // Main API client with standard timeoutlet client = Client::builder().timeout(Duration::from_secs(30)).user_agent(format!("ente-cli-rust/{}", env!("CARGO_PKG_VERSION"))).build()?;- // Download client with longer timeout and connection pool settingslet download_client = Client::builder().timeout(Duration::from_secs(300)).pool_idle_timeout(Duration::from_secs(90))@@ -89,7 +118,6 @@ impl ApiClient {fn build_request(&self, builder: RequestBuilder, account_id: Option<&str>) -> RequestBuilder {let mut req = builder.header(CLIENT_PKG_HEADER, CLIENT_PACKAGE);- // Add auth token if account_id is providedif let Some(id) = account_id {if let Some(token) = self.get_token(id) {log::debug!("Adding auth token for account {id}");@@ -114,7 +142,6 @@ impl ApiClient {match req.send().await {Ok(response) => {- // Check if we should retry based on status codeif (response.status() == StatusCode::TOO_MANY_REQUESTS|| response.status().is_server_error())&& retry_count < MAX_RETRIES@@ -127,7 +154,6 @@ impl ApiClient {MAX_RETRIES);- // Exponential backoff with jittersleep(Duration::from_millis(delay_ms)).await;delay_ms = (delay_ms * 2).min(MAX_RETRY_DELAY_MS);continue;@@ -165,32 +191,16 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());-- // Try to parse as JSON to get error details- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::debug!(- "API error: status={}, body={}",- status,- serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())- );- } else {- log::debug!("API error: status={status}, body={error_text}");- }-- return Err(Error::api_error(- status.as_u16(),- format!("API error ({status}): {error_text}"),- ));+ return Err(make_api_error("GET", path, status, body));}let text = response.text().await?;- log::trace!("Raw API response: {}", &text[..500.min(text.len())]);serde_json::from_str(&text).map_err(|e| {- log::debug!("Failed to deserialize response: {e}");+ log::error!("Failed to deserialize response: {e}");log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]@@ -214,32 +224,16 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());-- // Try to parse as JSON to get error details- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::debug!(- "API error: status={}, body={}",- status,- serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())- );- } else {- log::debug!("API error: status={status}, body={error_text}");- }-- return Err(Error::api_error(- status.as_u16(),- format!("API error ({status}): {error_text}"),- ));+ return Err(make_api_error("POST", path, status, body));}let text = response.text().await?;-serde_json::from_str(&text).map_err(|e| {- log::debug!("Failed to deserialize response: {e}");+ log::error!("Failed to deserialize response: {e}");log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]@@ -254,6 +248,7 @@ impl ApiClient {B: Serialize,{let url = format!("{}{}", self.base_url, path);+let request = self.client.post(&url).json(body);let request = self.build_request(request, account_id);@@ -261,25 +256,11 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());-- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::debug!(- "API error: status={}, body={}",- status,- serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())- );- } else {- log::debug!("API error: status={status}, body={error_text}");- }-- return Err(Error::api_error(- status.as_u16(),- format!("API error ({status}): {error_text}"),- ));+ return Err(make_api_error("POST", path, status, body));}Ok(())@@ -299,31 +280,16 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());-- // Try to parse as JSON to get error details- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::debug!(- "API error: status={}, body={}",- status,- serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())- );- } else {- log::debug!("API error: status={status}, body={error_text}");- }-- return Err(Error::api_error(- status.as_u16(),- format!("API error ({status}): {error_text}"),- ));+ return Err(make_api_error("PUT", path, status, body));}let text = response.text().await?;serde_json::from_str(&text).map_err(|e| {- log::debug!("Failed to deserialize response: {e}");+ log::error!("Failed to deserialize response: {e}");log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]@@ -332,7 +298,7 @@ impl ApiClient {})}- /// Make a DELETE request+ /// Make a DELETE requestpub async fn delete(&self, path: &str, account_id: Option<&str>) -> Result<()> {let url = format!("{}{}", self.base_url, path);let request = self.client.delete(&url);@@ -342,26 +308,11 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());-- // Try to parse as JSON to get error details- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::debug!(- "API error: status={}, body={}",- status,- serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())- );- } else {- log::debug!("API error: status={status}, body={error_text}");- }-- return Err(Error::api_error(- status.as_u16(),- format!("API error ({status}): {error_text}"),- ));+ return Err(make_api_error("DELETE", path, status, body));}Ok(())@@ -376,14 +327,11 @@ impl ApiClient {if !response.status().is_success() {let status = response.status();- let error_text = response+ let body = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());- return Err(Error::api_error(- status.as_u16(),- format!("Download error: {error_text}"),- ));+ return Err(make_api_error("GET", url, status, body));}Ok(response.bytes().await?.to_vec())diff --git a/rust/cli/src/api/models.rs b/rust/cli/src/api/models.rsindex 006d64ac12..94fb9f471c 100644--- a/rust/cli/src/api/models.rs+++ b/rust/cli/src/api/models.rs@@ -3,9 +3,6 @@ use uuid::Uuid;// ========== Authentication Models ==========-/// Default to true for security - if field is missing, use email OTP flow.-///-/// Matches mobile/web behavior: absence falls back to email verification.fn default_email_mfa_enabled() -> bool {true}@@ -79,19 +76,17 @@ pub struct AuthResponse {pub key_attributes: Option<KeyAttributes>,pub encrypted_token: Option<String>,pub token: Option<String>,- #[serde(default, rename = "twoFactorSessionID")]+ #[serde(rename = "twoFactorSessionID")]pub two_factor_session_id: Option<String>,- /// V2 TOTP session ID (used during migration period)- #[serde(default, rename = "twoFactorSessionIDV2")]+ #[serde(rename = "twoFactorSessionIDV2")]pub two_factor_session_id_v2: Option<String>,- #[serde(default, rename = "passkeySessionID")]+ #[serde(rename = "passkeySessionID")]pub passkey_session_id: Option<String>,pub srp_m2: Option<String>,pub accounts_url: Option<String>,}impl AuthResponse {- /// Get the TOTP session ID (checks both V1 and V2 fields, filters empty strings)pub fn get_two_factor_session_id(&self) -> Option<&String> {self.two_factor_session_id.as_ref()@@ -108,7 +103,9 @@ impl AuthResponse {}pub fn is_passkey_required(&self) -> bool {- self.passkey_session_id.is_some()+ self.passkey_session_id+ .as_ref()+ .is_some_and(|s| !s.is_empty())}}diff --git a/rust/cli/src/commands/account.rs b/rust/cli/src/commands/account.rsindex 83218d3b8d..57a214f474 100644--- a/rust/cli/src/commands/account.rs+++ b/rust/cli/src/commands/account.rs@@ -3,7 +3,7 @@ use crate::{cli::account::{AccountCommand, AccountSubcommands},models::{account::{Account, AccountSecrets, App},- error::Result,+ error::{Error, Result},},storage::Storage,};@@ -11,11 +11,9 @@ use base64::Engine;use dialoguer::{Input, Password, Select};use std::path::PathBuf;-// Use ente-core for auth operations-use ente_core::auth::{DecryptedSecrets, KeyAttributes as CoreKeyAttributes, derive_kek};+use ente_core::auth::{self, DecryptedSecrets, KeyAttributes as CoreKeyAttributes, derive_kek};use ente_core::crypto;-/// Convert CLI's KeyAttributes to core's KeyAttributesfn to_core_key_attributes(attrs: &crate::api::models::KeyAttributes) -> CoreKeyAttributes {CoreKeyAttributes {kek_salt: attrs.kek_salt.clone(),@@ -34,20 +32,16 @@ fn to_core_key_attributes(attrs: &crate::api::models::KeyAttributes) -> CoreKeyA}fn decrypt_secrets_with_plain_token(- key_enc_key: &[u8],+ kek: &[u8],key_attrs: &CoreKeyAttributes,token: &str,-) -> std::result::Result<DecryptedSecrets, ente_core::auth::AuthError> {- use ente_core::auth::AuthError;+) -> auth::Result<DecryptedSecrets> {+ let (master_key, secret_key) = auth::decrypt_keys_only(kek, key_attrs)?;- // Decrypt keys (shared logic lives in ente-core)- let (master_key, secret_key) = ente_core::auth::decrypt_keys_only(key_enc_key, key_attrs)?;-- // Tokens are base64 (URL-safe) in other clients; decode to raw bytes here.let token = base64::engine::general_purpose::URL_SAFE.decode(token).or_else(|_| base64::engine::general_purpose::STANDARD.decode(token))- .map_err(|e| AuthError::Decode(format!("token: {}", e)))?;+ .map_err(|e| auth::AuthError::Decode(format!("token: {e}")))?;Ok(DecryptedSecrets {master_key,@@ -123,25 +117,22 @@ async fn add_account() -> Result<()> {println!("\n=== Add Ente Account ===\n");- // Get email (from arg or prompt)let email = if let Some(email) = email_arg {} else {Input::new().with_prompt("Enter your email address").interact_text()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?+ .map_err(|e| Error::InvalidInput(e.to_string()))?};- // Parse app typelet app = match app_arg.to_lowercase().as_str() {"photos" => App::Photos,"locker" => App::Locker,"auth" => App::Auth,_ => {- // If invalid app provided via CLI, use interactive selectionif password_arg.is_some() {- return Err(crate::models::error::Error::InvalidInput(format!(+ return Err(Error::InvalidInput(format!("Invalid app: {app_arg}. Must be one of: photos, locker, auth")));}@@ -151,7 +142,7 @@ async fn add_account(.items(&apps).default(0).interact()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;+ .map_err(|e| Error::InvalidInput(e.to_string()))?;match apps[app_index] {"photos" => App::Photos,"locker" => App::Locker,@@ -161,300 +152,162 @@ async fn add_account(}};- // Check if account already existsif let Ok(Some(_existing)) = storage.accounts().get(&email, app) {println!("\nβ Account already exists for {email} with app {app:?}");return Ok(());}- // Check if we're in non-interactive mode (password provided via CLI)let is_non_interactive = password_arg.is_some();- // Get password (from arg or prompt)- let password = if let Some(password) = password_arg {+ let mut password = if let Some(password) = password_arg {password} else {Password::new().with_prompt("Enter your password").interact()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?+ .map_err(|e| Error::InvalidInput(e.to_string()))?};- // Get export directory (from arg or use default)let export_dir = if let Some(dir) = export_dir_arg {dir} else if is_non_interactive {- // If password was provided via CLI (non-interactive mode), use default pathformat!("./exports/{email}")} else {Input::new().with_prompt("Enter export directory path").default(format!("./exports/{email}")).interact_text()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?+ .map_err(|e| Error::InvalidInput(e.to_string()))?};- // Validate export directorylet export_path = PathBuf::from(&export_dir);if !export_path.exists() {println!("Creating export directory: {export_dir}");- std::fs::create_dir_all(&export_path).map_err(crate::models::error::Error::Io)?;+ std::fs::create_dir_all(&export_path).map_err(Error::Io)?;}- // Initialize API client with the specified endpointlog::info!("Using API endpoint: {endpoint}");let api_client = ApiClient::new(Some(endpoint.clone()))?;let auth_client = AuthClient::new(&api_client);println!("\nAuthenticating with Ente servers...");- // First, get SRP attributes to check if email MFA is enabledlet srp_attrs = auth_client.get_srp_attributes(&email).await?;- log::debug!(- "SRP attributes: is_email_mfa_enabled={}",- srp_attrs.is_email_mfa_enabled- );- // Determine auth flow based on email MFA settinglet (auth_response, mut key_enc_key) = if srp_attrs.is_email_mfa_enabled {- // Email MFA flow: send OTP, verify email first, then do SRPprintln!("\nπ§ Email MFA is enabled. Sending verification code...");-auth_client.send_login_otp(&email).await?;- println!("β Verification code sent to {email}");- // Prompt for OTP- let otp: String = Input::new()- .with_prompt("Enter the 6-digit code from your email")- .validate_with(|input: &String| {- if input.len() == 6 && input.chars().all(char::is_numeric) {- Ok(())- } else {- Err("Code must be 6 digits")- }- })- .interact_text()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;-- // Verify email with OTP (with retry on wrong code)- let mut current_otp = otp;- let email_auth_resp = loop {- println!("Verifying email...");- match auth_client.verify_email(&email, ¤t_otp).await {- Ok(resp) => {- println!("β Email verified!");- break resp;- }- Err(e) => {- // Invalid or expired code - allow retry- if e.is_retryable_auth() || e.is_gone() {- println!("β Invalid or expired code. Please try again.");- // Resend OTP- auth_client.send_login_otp(&email).await?;- println!("β New verification code sent to {email}");-- // Prompt for new OTP- current_otp = Input::new()- .with_prompt("Enter the 6-digit code from your email")- .validate_with(|input: &String| {- if input.len() == 6 && input.chars().all(char::is_numeric) {- Ok(())- } else {- Err("Code must be 6 digits")- }- })- .interact_text()- .map_err(|e| {- crate::models::error::Error::InvalidInput(e.to_string())- })?;- continue;+ let auth_response = loop {+ let otp: String = Input::new()+ .with_prompt("Enter the 6-digit code from your email")+ .validate_with(|input: &String| {+ if input.len() == 6 && input.chars().all(char::is_numeric) {+ Ok(())} else {- return Err(e);+ Err("Code must be 6 digits")}+ })+ .interact_text()+ .map_err(|e| Error::InvalidInput(e.to_string()))?;++ match auth_client.verify_email(&email, &otp).await {+ Ok(resp) => break resp,+ Err(Error::ApiError {+ status: 400 | 401, ..+ }) => {+ println!("β Invalid code, please try again.");}+ Err(Error::ApiError { status: 410, .. }) => {+ println!("β Code expired. Sending a new code...");+ auth_client.send_login_otp(&email).await?;+ }+ Err(e) => return Err(e),}};- let mut email_auth_resp = email_auth_resp;-- // Check if 2FA is required after email verification- let has_totp = email_auth_resp.get_two_factor_session_id().is_some();- let has_passkey = email_auth_resp- .passkey_session_id- .as_ref()- .is_some_and(|s| !s.is_empty());-- if has_totp && has_passkey {- // Both available - let user choose- println!("\nπ Two-factor authentication required");- println!("Choose verification method:");- let options = vec!["TOTP (Authenticator app)", "Passkey"];- let choice = Select::new()- .items(&options)- .default(0)- .interact()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;-- if choice == 0 {- // TOTP- email_auth_resp = verify_totp_2fa(&auth_client, &email_auth_resp).await?;- } else {- // Passkey- email_auth_resp = verify_passkey_2fa(&auth_client, &email_auth_resp, app).await?;- }- } else if has_totp {- email_auth_resp = verify_totp_2fa(&auth_client, &email_auth_resp).await?;- } else if has_passkey {- email_auth_resp = verify_passkey_2fa(&auth_client, &email_auth_resp, app).await?;- }- // Derive key encryption key from password for decryption using ente-core- println!("Deriving encryption key (this may take a few seconds)...");+ let auth_response = maybe_verify_2fa(&auth_client, auth_response, app).await?;++ println!("\nPlease wait authenticating...");let key_enc_key = derive_kek(&password,&srp_attrs.kek_salt,srp_attrs.mem_limit as u32,srp_attrs.ops_limit as u32,- )- .map_err(|e| crate::models::error::Error::Crypto(e.to_string()))?;+ )?;- (email_auth_resp, key_enc_key)+ (auth_response, key_enc_key)} else {- // Standard SRP password authentication (with retry on wrong password)- let mut current_password = password.clone();- loop {- match auth_client.login_with_srp(&email, ¤t_password).await {- Ok(result) => break result,- Err(e) => {- // Wrong password - allow retry- if e.is_unauthorized() || e.is_retryable_auth() {- println!("\nβ Incorrect password. Please try again.");- current_password = Password::new()+ let (auth_response, key_enc_key) = if is_non_interactive {+ auth_client.login_with_srp(&email, &password).await?+ } else {+ loop {+ match auth_client.login_with_srp(&email, &password).await {+ Ok(result) => break result,+ Err(Error::ApiError {+ status: 400 | 401, ..+ }) => {+ println!("β Incorrect password, please try again.");+ password = Password::new().with_prompt("Enter your password").interact()- .map_err(|e| {- crate::models::error::Error::InvalidInput(e.to_string())- })?;- continue;- } else {- return Err(e);+ .map_err(|e| Error::InvalidInput(e.to_string()))?;}+ Err(e) => return Err(e),}}- }- };-- // Handle 2FA if required - for non-email-MFA flow- let has_totp = auth_response.get_two_factor_session_id().is_some();- let has_passkey = auth_response- .passkey_session_id- .as_ref()- .is_some_and(|s| !s.is_empty());-- let auth_response = if has_totp && has_passkey {- // Both available - let user choose- println!("\nπ Two-factor authentication required");- println!("Choose verification method:");- let options = vec!["TOTP (Authenticator app)", "Passkey"];- let choice = Select::new()- .items(&options)- .default(0)- .interact()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;+ };- if choice == 0 {- verify_totp_2fa(&auth_client, &auth_response).await?- } else {- verify_passkey_2fa(&auth_client, &auth_response, app).await?- }- } else if has_totp {- verify_totp_2fa(&auth_client, &auth_response).await?- } else if has_passkey {- verify_passkey_2fa(&auth_client, &auth_response, app).await?- } else {- auth_response+ let auth_response = maybe_verify_2fa(&auth_client, auth_response, app).await?;+ (auth_response, key_enc_key)};- // Decrypt keys- log::debug!(- "Final auth_response: id={}, has_key_attributes={}, has_encrypted_token={}",- auth_response.id,- auth_response.key_attributes.is_some(),- auth_response.encrypted_token.is_some()- );-- let key_attributes = auth_response.key_attributes.as_ref().ok_or_else(|| {- crate::models::error::Error::AuthenticationFailed("No key attributes".to_string())- })?;+ let key_attributes = auth_response+ .key_attributes+ .as_ref()+ .ok_or_else(|| Error::AuthenticationFailed("No key attributes".to_string()))?;println!("\nDecrypting account keys...");+ let core_key_attrs = to_core_key_attributes(key_attributes);+let encrypted_token = auth_response.encrypted_token.as_deref();let response_token = auth_response.token.as_deref();- if encrypted_token.is_none() && response_token.is_none() {- return Err(crate::models::error::Error::AuthenticationFailed(- "No token in response".to_string(),- ));- }-- // Convert to core key attributes- let core_key_attrs = to_core_key_attributes(key_attributes);-- // Decrypt secrets (with retry on wrong password)let secrets: DecryptedSecrets = loop {- let decrypt_result = if let Some(encrypted_token) = encrypted_token {- ente_core::auth::decrypt_secrets(&key_enc_key, &core_key_attrs, encrypted_token)+ let result = if let Some(encrypted_token) = encrypted_token {+ auth::decrypt_secrets(&key_enc_key, &core_key_attrs, encrypted_token)} else if let Some(token) = response_token {decrypt_secrets_with_plain_token(&key_enc_key, &core_key_attrs, token)} else {- return Err(crate::models::error::Error::AuthenticationFailed(+ return Err(Error::AuthenticationFailed("No token in response".to_string(),));};- match decrypt_result {- Ok(secrets) => {- log::info!("Secrets decrypted successfully");- break secrets;- }- Err(e) => {- if matches!(e, ente_core::auth::AuthError::IncorrectPassword) {- println!("β Incorrect password. Please try again.");-- // Prompt for password again- let new_password = Password::new()- .with_prompt("Enter your password")- .interact()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;-- // Re-derive key encryption key using ente-core- println!("Verifying password (this may take a few seconds)...");- key_enc_key = derive_kek(- &new_password,- &key_attributes.kek_salt,- key_attributes.mem_limit as u32,- key_attributes.ops_limit as u32,- )- .map_err(|e| crate::models::error::Error::Crypto(e.to_string()))?;-- println!("Decrypting account keys...");- continue;- } else {- return Err(crate::models::error::Error::Crypto(e.to_string()));- }+ match result {+ Ok(secrets) => break secrets,+ Err(auth::AuthError::IncorrectPassword) if !is_non_interactive => {+ println!("β Incorrect password.");+ password = Password::new()+ .with_prompt("Enter your password")+ .interact()+ .map_err(|e| Error::InvalidInput(e.to_string()))?;++ println!("\nPlease wait authenticating...");+ key_enc_key = derive_kek(+ &password,+ &key_attributes.kek_salt,+ key_attributes.mem_limit as u32,+ key_attributes.ops_limit as u32,+ )?;}+ Err(e) => return Err(e.into()),}};- // Extract keys from decrypted secrets- let master_key = secrets.master_key;- let secret_key = secrets.secret_key;let public_key = crypto::decode_b64(&key_attributes.public_key)?;- // Token is already decrypted by decrypt_secrets- let token = secrets.token;-- // Create accountlet account = Account {user_id: auth_response.id,email: email.clone(),@@ -463,15 +316,13 @@ async fn add_account(export_dir: Some(export_dir.clone()),};- // Create account secretslet secrets = AccountSecrets {- token,- master_key,- secret_key,+ token: secrets.token,+ master_key: secrets.master_key,+ secret_key: secrets.secret_key,public_key,};- // Store account in databasestorage.accounts().add(&account)?;storage.accounts()@@ -486,34 +337,66 @@ async fn add_account(Ok(())}+async fn maybe_verify_2fa(+ auth_client: &AuthClient<'_>,+ auth_resp: crate::api::models::AuthResponse,+ app: App,+) -> Result<crate::api::models::AuthResponse> {+ let has_totp = auth_resp.get_two_factor_session_id().is_some();+ let has_passkey = auth_resp+ .passkey_session_id+ .as_ref()+ .is_some_and(|s| !s.is_empty());++ if has_totp && has_passkey {+ println!("\nπ Two-factor authentication required");+ println!("Choose verification method:");+ let options = vec!["TOTP (Authenticator app)", "Passkey"];+ let choice = Select::new()+ .items(&options)+ .default(0)+ .interact()+ .map_err(|e| Error::InvalidInput(e.to_string()))?;++ if choice == 0 {+ verify_totp_2fa(auth_client, &auth_resp).await+ } else {+ verify_passkey_2fa(auth_client, &auth_resp, app).await+ }+ } else if has_totp {+ verify_totp_2fa(auth_client, &auth_resp).await+ } else if has_passkey {+ verify_passkey_2fa(auth_client, &auth_resp, app).await+ } else {+ Ok(auth_resp)+ }+}+async fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str) -> Result<()> {let app = match app_str.to_lowercase().as_str() {"photos" => App::Photos,"locker" => App::Locker,"auth" => App::Auth,_ => {- return Err(crate::models::error::Error::InvalidInput(format!(+ return Err(Error::InvalidInput(format!("Invalid app: {app_str}. Must be one of: photos, locker, auth")));}};- // Check if account existsif storage.accounts().get(email, app)?.is_none() {- return Err(crate::models::error::Error::NotFound(format!(+ return Err(Error::NotFound(format!("Account not found: {} (app: {:?})",email, app)));}- // Validate export directorylet export_path = PathBuf::from(dir);if !export_path.exists() {println!("Creating export directory: {dir}");- std::fs::create_dir_all(&export_path).map_err(crate::models::error::Error::Io)?;+ std::fs::create_dir_all(&export_path).map_err(Error::Io)?;}- // Update accountstorage.accounts().update_export_dir(email, app, dir)?;println!("\nβ Account updated successfully!");@@ -530,27 +413,22 @@ async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()>"locker" => App::Locker,"auth" => App::Auth,_ => {- return Err(crate::models::error::Error::InvalidInput(format!(+ return Err(Error::InvalidInput(format!("Invalid app: {app_str}. Must be one of: photos, locker, auth")));}};- // Get account- let account = storage.accounts().get(email, app)?.ok_or_else(|| {- crate::models::error::Error::NotFound(format!("Account not found: {email}"))- })?;+ let account = storage+ .accounts()+ .get(email, app)?+ .ok_or_else(|| Error::NotFound(format!("Account not found: {email}")))?;- // Get account secretslet secrets = storage.accounts().get_secrets(account.user_id, account.app)?- .ok_or_else(|| {- crate::models::error::Error::NotFound(format!("Secrets not found for account {email}"))- })?;+ .ok_or_else(|| Error::NotFound(format!("Secrets not found for account {email}")))?;- // Token is stored as raw bytes from sealed_box_open- // The Go CLI returns it as base64 URL-encoded string WITH padding (matching TokenStr() in Go)let token_str = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);println!("{token_str}");@@ -558,16 +436,15 @@ async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()>Ok(())}-/// Helper function to verify TOTP 2FA with retry on wrong codeasync fn verify_totp_2fa(auth_client: &AuthClient<'_>,auth_resp: &crate::api::models::AuthResponse,) -> Result<crate::api::models::AuthResponse> {println!("\nπ± Two-factor authentication required");- let session_id = auth_resp.get_two_factor_session_id().ok_or_else(|| {- crate::models::error::Error::AuthenticationFailed("No 2FA session ID".to_string())- })?;+ let session_id = auth_resp+ .get_two_factor_session_id()+ .ok_or_else(|| Error::AuthenticationFailed("No 2FA session ID".to_string()))?;loop {let totp_code: String = Input::new()@@ -580,31 +457,28 @@ async fn verify_totp_2fa(}}).interact_text()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;+ .map_err(|e| Error::InvalidInput(e.to_string()))?;match auth_client.verify_totp(session_id, &totp_code).await {Ok(result) => {println!("β Two-factor authentication verified!");return Ok(result);}- Err(e) => {- // Invalid TOTP code - allow retry- if e.is_retryable_auth() {- println!("β Invalid TOTP code. Please try again.");- continue;- } else if e.is_gone() {- return Err(crate::models::error::Error::AuthenticationFailed(- "TOTP session expired. Please restart login.".to_string(),- ));- } else {- return Err(e);- }+ Err(Error::ApiError {+ status: 400 | 401, ..+ }) => {+ println!("β Invalid code, please try again.");+ }+ Err(Error::ApiError { status: 410, .. }) => {+ return Err(Error::AuthenticationFailed(+ "TOTP session expired. Please restart login.".to_string(),+ ));}+ Err(e) => return Err(e),}}}-/// Helper function to verify Passkey 2FAasync fn verify_passkey_2fa(auth_client: &AuthClient<'_>,auth_resp: &crate::api::models::AuthResponse,@@ -614,9 +488,7 @@ async fn verify_passkey_2fa(.passkey_session_id.as_ref().filter(|s| !s.is_empty())- .ok_or_else(|| {- crate::models::error::Error::AuthenticationFailed("No passkey session ID".to_string())- })?;+ .ok_or_else(|| Error::AuthenticationFailed("No passkey session ID".to_string()))?;let accounts_url = auth_resp.accounts_url@@ -637,41 +509,35 @@ async fn verify_passkey_2fa();println!("\nπ Passkey verification required");- println!("Opening browser for passkey verification...");- println!("URL: {}", passkey_url);+ println!("Open this URL in your browser to verify your passkey:\n{passkey_url}");- // Try to open the URL in the browserif let Err(e) = open::that(&passkey_url) {- println!("Failed to open browser: {e}");- println!("Please open the URL manually.");+ log::error!("failed to open browser: {e}");}- // Poll for passkey verification completionloop {let _: String = Input::new()- .with_prompt("Press Enter after completing passkey verification in browser")+ .with_prompt("Press Enter once you have completed passkey verification").allow_empty(true).interact_text()- .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;+ .map_err(|e| Error::InvalidInput(e.to_string()))?;match auth_client.check_passkey_status(passkey_session_id).await {Ok(result) => {println!("β Passkey verification completed!");return Ok(result);}- Err(e) => {- if e.is_not_ready() {- println!("β³ Passkey verification not yet complete.");- println!("Please complete the verification in your browser and press Enter.");- } else if e.is_gone() {- return Err(crate::models::error::Error::AuthenticationFailed(- "Passkey session expired. Please restart login.".to_string(),- ));- } else {- println!("Error checking passkey status: {e}");- println!("Please try again.");- }+ Err(Error::ApiError {+ status: 400 | 404, ..+ }) => {+ println!("β³ Passkey verification not yet complete.");+ }+ Err(Error::ApiError { status: 410, .. }) => {+ return Err(Error::AuthenticationFailed(+ "Passkey session expired. Please restart login.".to_string(),+ ));}+ Err(e) => return Err(e),}}}diff --git a/rust/cli/src/main.rs b/rust/cli/src/main.rsindex 1e4f32526b..5e3a0d9cd6 100644--- a/rust/cli/src/main.rs+++ b/rust/cli/src/main.rs@@ -1,5 +1,6 @@use clap::Parser;use ente_rs::{+ Result,cli::{Cli, Commands},commands,storage::Storage,@@ -8,27 +9,22 @@ use ente_rs::{#[tokio::main]async fn main() {if let Err(e) = run().await {- eprintln!("\n{}", e.user_message());+ eprintln!("{e}");std::process::exit(1);}}-async fn run() -> ente_rs::Result<()> {- // Initialize logger+async fn run() -> Result<()> {env_logger::init();- // Initialize cryptoente_core::crypto::init()?;- // Initialize storagelet config_dir = ente_rs::utils::get_cli_config_dir()?;let db_path = config_dir.join("ente.db");let storage = Storage::new(&db_path)?;- // Parse CLI argumentslet cli = Cli::parse();- // Handle commandsmatch cli.command {Commands::Version => {println!("ente-rs version {}", ente_rs::cli::version::VERSION);diff --git a/rust/cli/src/models/error.rs b/rust/cli/src/models/error.rsindex 8962202e32..29de383d3e 100644--- a/rust/cli/src/models/error.rs+++ b/rust/cli/src/models/error.rs@@ -1,4 +1,4 @@-use ente_core::crypto::CryptoError;+use ente_core::{auth::AuthError, crypto::CryptoError};use thiserror::Error;#[derive(Error, Debug)]@@ -39,76 +39,11 @@ pub enum Error {#[error("ZIP error: {0}")]Zip(#[from] zip::result::ZipError),- #[error("{0}")]- Generic(String),-- #[error("Too many requests. Please wait a minute and try again.")]- RateLimited,-#[error("API error ({status}): {message}")]ApiError { status: u16, message: String },-}--impl Error {- /// Create an API error with status code- pub fn api_error(status: u16, message: String) -> Self {- Error::ApiError { status, message }- }-- /// Check if this is a specific HTTP status code- pub fn is_status(&self, code: u16) -> bool {- matches!(self, Error::ApiError { status, .. } if *status == code)- }-- /// Check if this is an authentication error (401)- pub fn is_unauthorized(&self) -> bool {- self.is_status(401)- }-- /// Check if this is a session expired error (410)- pub fn is_gone(&self) -> bool {- self.is_status(410)- }-- /// Check if this is a rate limit error (429)- pub fn is_rate_limited(&self) -> bool {- matches!(self, Error::RateLimited) || self.is_status(429)- }-- /// Check if this is a "not yet complete" error (400/404 for passkey polling)- pub fn is_not_ready(&self) -> bool {- self.is_status(400) || self.is_status(404)- }- /// Check if retry is appropriate for this error- pub fn is_retryable_auth(&self) -> bool {- self.is_unauthorized() || self.is_status(400)- }-- /// Get a user-friendly display message- pub fn user_message(&self) -> String {- match self {- Error::RateLimited => {- "β³ Too many requests. Please wait a minute and try again.".to_string()- }- Error::ApiError { status: 401, .. } => {- "π Invalid credentials. Please check your password.".to_string()- }- Error::ApiError { status: 410, .. } => {- "π Session expired. Please restart the login process.".to_string()- }- Error::ApiError { status: 429, .. } => {- "β³ Too many requests. Please wait a minute and try again.".to_string()- }- Error::ApiError { status: 404, .. } => "π Not found.".to_string(),- Error::AuthenticationFailed(msg) => format!("π {}", msg),- Error::Crypto(_) => "π Decryption failed. Please check your password.".to_string(),- Error::NotFound(msg) => format!("π {}", msg),- Error::Network(_) => "π Network error. Please check your connection.".to_string(),- Error::InvalidInput(msg) => format!("β οΈ {}", msg),- _ => format!("β {}", self),- }- }+ #[error("{0}")]+ Generic(String),}impl From<CryptoError> for Error {@@ -121,4 +56,23 @@ impl From<CryptoError> for Error {}}+impl From<AuthError> for Error {+ fn from(err: AuthError) -> Self {+ match err {+ AuthError::IncorrectPassword => {+ Error::AuthenticationFailed("Incorrect password".to_string())+ }+ AuthError::IncorrectRecoveryKey => {+ Error::AuthenticationFailed("Incorrect recovery key".to_string())+ }+ AuthError::InvalidKeyAttributes => Error::Crypto(err.to_string()),+ AuthError::MissingField(field) => Error::Crypto(format!("Missing field: {field}")),+ AuthError::Crypto(source) => source.into(),+ AuthError::Decode(msg) => Error::Crypto(msg),+ AuthError::InvalidKey(msg) => Error::Crypto(msg),+ AuthError::Srp(msg) => Error::Srp(msg),+ }+ }+}+pub type Result<T> = std::result::Result<T, Error>;