Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

feat(rust): Implement account management commands

Manav Rathicd20a9885053
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index dbfeefd81d..1ac9047c07 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -587,6 +587,19 @@ dependencies = [
"syn",
]
+[[package]]
+name = "dialoguer"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de"
+dependencies = [
+ "console",
+ "shell-words",
+ "tempfile",
+ "thiserror 1.0.69",
+ "zeroize",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -679,6 +692,7 @@ dependencies = [
"chrono",
"clap",
"config",
+ "dialoguer",
"dirs",
"env_logger",
"futures",
@@ -2584,6 +2598,12 @@ dependencies = [
"digest",
]
+[[package]]
+name = "shell-words"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"
+
[[package]]
name = "shlex"
version = "1.3.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index b2f3c26d39..008587caff 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -48,6 +48,7 @@ chrono = "0.4"
uuid = { version = "1.11", features = ["serde", "v4"] }
rpassword = "7.3"
indicatif = "0.17"
+dialoguer = "0.11"
# File operations
walkdir = "2.5"
diff --git a/rust/src/commands/account.rs b/rust/src/commands/account.rs
new file mode 100644
index 0000000000..132f35b7dd
--- /dev/null
+++ b/rust/src/commands/account.rs
@@ -0,0 +1,283 @@
+use crate::{
+ api::{ApiClient, AuthClient},
+ cli::account::{AccountCommand, AccountSubcommands},
+ crypto::{decode_base64, sealed_box_open, secret_box_open},
+ models::{
+ account::{Account, AccountSecrets, App},
+ error::Result,
+ },
+ storage::Storage,
+};
+use dialoguer::{Input, Password, Select};
+use std::path::PathBuf;
+
+pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> Result<()> {
+ match cmd.command {
+ AccountSubcommands::List => list_accounts(storage).await,
+ AccountSubcommands::Add => add_account(storage).await,
+ AccountSubcommands::Update { email, dir, app } => {
+ update_account(storage, &email, &dir, &app).await
+ }
+ AccountSubcommands::GetToken { email, app } => get_token(storage, &email, &app).await,
+ }
+}
+
+async fn list_accounts(storage: &Storage) -> Result<()> {
+ let accounts = storage.accounts().list()?;
+
+ if accounts.is_empty() {
+ println!("No accounts configured. Use 'ente account add' to add an account.");
+ return Ok(());
+ }
+
+ println!("\nConfigured accounts:\n");
+ println!("{:<30} {:<10} {:<40}", "Email", "App", "Export Directory");
+ println!("{}", "-".repeat(80));
+
+ for account in accounts {
+ println!(
+ "{:<30} {:<10} {:<40}",
+ account.email,
+ format!("{:?}", account.app).to_lowercase(),
+ account.export_dir.as_deref().unwrap_or("Not configured")
+ );
+ }
+
+ Ok(())
+}
+
+async fn add_account(storage: &Storage) -> Result<()> {
+ println!("\n=== Add Ente Account ===\n");
+
+ // Get email
+ let email: String = Input::new()
+ .with_prompt("Enter your email address")
+ .interact_text()
+ .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;
+
+ // Get app type
+ let apps = vec!["photos", "locker", "auth"];
+ let app_index = Select::new()
+ .with_prompt("Select the Ente app")
+ .items(&apps)
+ .default(0)
+ .interact()
+ .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;
+
+ let app = match apps[app_index] {
+ "photos" => App::Photos,
+ "locker" => App::Locker,
+ "auth" => App::Auth,
+ _ => unreachable!(),
+ };
+
+ // Check if account already exists
+ if let Ok(Some(_existing)) = storage.accounts().get(&email, app) {
+ println!(
+ "\n❌ Account already exists for {} with app {:?}",
+ email, app
+ );
+ return Ok(());
+ }
+
+ // Get password
+ let password = Password::new()
+ .with_prompt("Enter your password")
+ .interact()
+ .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;
+
+ // Get export directory
+ let export_dir: String = 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()))?;
+
+ // Validate export directory
+ let 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(|e| crate::models::error::Error::Io(e))?;
+ }
+
+ // Initialize API client
+ let api_client = ApiClient::new(None)?;
+ let auth_client = AuthClient::new(&api_client);
+
+ println!("\nAuthenticating with Ente servers...");
+
+ // Perform SRP authentication
+ let (auth_response, key_enc_key) = match auth_client.login_with_srp(&email, &password).await {
+ Ok(result) => result,
+ Err(e) => {
+ println!("\n❌ Authentication failed: {}", e);
+ return Err(e);
+ }
+ };
+
+ // Handle 2FA if required
+ let auth_response = if auth_response.is_mfa_required() {
+ println!("\nπŸ“± Two-factor authentication required");
+ let totp_code: String = Input::new()
+ .with_prompt("Enter TOTP code")
+ .validate_with(|input: &String| {
+ if input.len() == 6 && input.chars().all(char::is_numeric) {
+ Ok(())
+ } else {
+ Err("TOTP code must be 6 digits")
+ }
+ })
+ .interact_text()
+ .map_err(|e| crate::models::error::Error::InvalidInput(e.to_string()))?;
+
+ auth_client
+ .verify_totp(
+ auth_response
+ .two_factor_session_id
+ .as_ref()
+ .ok_or_else(|| {
+ crate::models::error::Error::AuthenticationFailed(
+ "No 2FA session ID".to_string(),
+ )
+ })?,
+ &totp_code,
+ )
+ .await?
+ } else if auth_response.is_passkey_required() {
+ println!("\nπŸ”‘ Passkey verification required");
+ println!("Please complete passkey verification in your browser...");
+ // TODO: Implement passkey verification flow
+ return Err(crate::models::error::Error::Generic(
+ "Passkey verification not yet implemented".to_string(),
+ ));
+ } else {
+ auth_response
+ };
+
+ // Decrypt keys
+ let key_attributes = auth_response.key_attributes.as_ref().ok_or_else(|| {
+ crate::models::error::Error::AuthenticationFailed("No key attributes".to_string())
+ })?;
+
+ println!("\nDecrypting account keys...");
+
+ // Decrypt master key
+ let master_key = secret_box_open(
+ &decode_base64(&key_attributes.encrypted_key)?,
+ &decode_base64(&key_attributes.key_decryption_nonce)?,
+ &key_enc_key,
+ )?;
+
+ // Decrypt secret key
+ let secret_key = secret_box_open(
+ &decode_base64(&key_attributes.encrypted_secret_key)?,
+ &decode_base64(&key_attributes.secret_key_decryption_nonce)?,
+ &master_key,
+ )?;
+
+ // Get public key
+ let public_key = decode_base64(&key_attributes.public_key)?;
+
+ // Decrypt token if encrypted
+ let token = if let Some(encrypted_token) = &auth_response.encrypted_token {
+ sealed_box_open(&decode_base64(encrypted_token)?, &public_key, &secret_key)?
+ } else if let Some(plain_token) = &auth_response.token {
+ plain_token.as_bytes().to_vec()
+ } else {
+ return Err(crate::models::error::Error::AuthenticationFailed(
+ "No token in response".to_string(),
+ ));
+ };
+
+ // Create account
+ let account = Account {
+ id: 0, // Will be set by database
+ email: email.clone(),
+ user_id: auth_response.id,
+ app,
+ export_dir: Some(export_dir.clone()),
+ };
+
+ // Create account secrets
+ let secrets = AccountSecrets {
+ token,
+ master_key,
+ secret_key,
+ public_key,
+ };
+
+ // Store account in database
+ let account_id = storage.accounts().add(&account)?;
+ storage.accounts().store_secrets(account_id, &secrets)?;
+
+ println!("\nβœ… Account added successfully!");
+ println!(" Email: {}", email);
+ println!(" App: {:?}", app);
+ println!(" Export directory: {}", export_dir);
+
+ Ok(())
+}
+
+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!(
+ "Invalid app: {}. Must be one of: photos, locker, auth",
+ app_str
+ )));
+ }
+ };
+
+ // Validate export directory
+ let export_path = PathBuf::from(dir);
+ if !export_path.exists() {
+ println!("Creating export directory: {}", dir);
+ std::fs::create_dir_all(&export_path).map_err(|e| crate::models::error::Error::Io(e))?;
+ }
+
+ // Update account
+ storage.accounts().update_export_dir(email, app, dir)?;
+
+ println!("\nβœ… Account updated successfully!");
+ println!(" Email: {}", email);
+ println!(" App: {:?}", app);
+ println!(" New export directory: {}", dir);
+
+ Ok(())
+}
+
+async fn get_token(storage: &Storage, email: &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!(
+ "Invalid app: {}. Must be one of: photos, locker, auth",
+ app_str
+ )));
+ }
+ };
+
+ // Get account
+ let account = storage.accounts().get(email, app)?.ok_or_else(|| {
+ crate::models::error::Error::NotFound(format!("Account not found: {}", email))
+ })?;
+
+ // Get account secrets
+ let secrets = storage.accounts().get_secrets(account.id)?.ok_or_else(|| {
+ crate::models::error::Error::NotFound(format!("Secrets not found for account {}", email))
+ })?;
+
+ // Convert token to string (assuming it's UTF-8)
+ let token_str = String::from_utf8(secrets.token.clone()).map_err(|_| {
+ crate::models::error::Error::Generic("Token is not valid UTF-8".to_string())
+ })?;
+
+ println!("{}", token_str);
+
+ Ok(())
+}
diff --git a/rust/src/commands/mod.rs b/rust/src/commands/mod.rs
new file mode 100644
index 0000000000..35f0b12b28
--- /dev/null
+++ b/rust/src/commands/mod.rs
@@ -0,0 +1,3 @@
+pub mod account;
+
+pub use account::handle_account_command;
diff --git a/rust/src/crypto/chacha.rs b/rust/src/crypto/chacha.rs
index 883c1ae9cf..8f60dcc75b 100644
--- a/rust/src/crypto/chacha.rs
+++ b/rust/src/crypto/chacha.rs
@@ -93,6 +93,47 @@ pub fn encrypt_chacha(plaintext: &[u8], nonce: &[u8], key: &[u8]) -> Result<Vec<
Ok(ciphertext)
}
+/// Open a sealed box (decrypt with public key crypto)
+pub fn sealed_box_open(ciphertext: &[u8], public_key: &[u8], secret_key: &[u8]) -> Result<Vec<u8>> {
+ if public_key.len() != sodium::crypto_box_PUBLICKEYBYTES as usize {
+ return Err(Error::Crypto(format!(
+ "Invalid public key length: expected {}, got {}",
+ sodium::crypto_box_PUBLICKEYBYTES,
+ public_key.len()
+ )));
+ }
+
+ if secret_key.len() != sodium::crypto_box_SECRETKEYBYTES as usize {
+ return Err(Error::Crypto(format!(
+ "Invalid secret key length: expected {}, got {}",
+ sodium::crypto_box_SECRETKEYBYTES,
+ secret_key.len()
+ )));
+ }
+
+ if ciphertext.len() < sodium::crypto_box_SEALBYTES as usize {
+ return Err(Error::Crypto("Ciphertext too short".into()));
+ }
+
+ let mut plaintext = vec![0u8; ciphertext.len() - sodium::crypto_box_SEALBYTES as usize];
+
+ let result = unsafe {
+ sodium::crypto_box_seal_open(
+ plaintext.as_mut_ptr(),
+ ciphertext.as_ptr(),
+ ciphertext.len() as u64,
+ public_key.as_ptr(),
+ secret_key.as_ptr(),
+ )
+ };
+
+ if result != 0 {
+ return Err(Error::Crypto("Failed to open sealed box".into()));
+ }
+
+ Ok(plaintext)
+}
+
/// Open a secret box (decrypt with XSalsa20-Poly1305)
pub fn secret_box_open(ciphertext: &[u8], nonce: &[u8], key: &[u8]) -> Result<Vec<u8>> {
if nonce.len() != sodium::crypto_secretbox_NONCEBYTES as usize {
diff --git a/rust/src/crypto/mod.rs b/rust/src/crypto/mod.rs
index c9b19b4c68..b7872d9ef3 100644
--- a/rust/src/crypto/mod.rs
+++ b/rust/src/crypto/mod.rs
@@ -8,7 +8,9 @@ mod chacha;
mod kdf;
pub use argon::derive_argon_key;
-pub use chacha::{decrypt_chacha, encrypt_chacha, secret_box_open, secret_box_seal};
+pub use chacha::{
+ decrypt_chacha, encrypt_chacha, sealed_box_open, secret_box_open, secret_box_seal,
+};
pub use kdf::derive_login_key;
static INIT: Once = Once::new();
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
index cd7da447fd..5af59b6902 100644
--- a/rust/src/lib.rs
+++ b/rust/src/lib.rs
@@ -1,5 +1,6 @@
pub mod api;
pub mod cli;
+pub mod commands;
pub mod crypto;
pub mod models;
pub mod storage;
diff --git a/rust/src/main.rs b/rust/src/main.rs
index 915c819be0..f888db32f7 100644
--- a/rust/src/main.rs
+++ b/rust/src/main.rs
@@ -2,6 +2,7 @@ use clap::Parser;
use ente_rs::{
Result,
cli::{Cli, Commands},
+ commands,
storage::Storage,
};
@@ -16,7 +17,7 @@ async fn main() -> Result<()> {
// Initialize storage
let config_dir = ente_rs::utils::get_cli_config_dir()?;
let db_path = config_dir.join("ente.db");
- let _storage = Storage::new(&db_path)?;
+ let storage = Storage::new(&db_path)?;
// Parse CLI arguments
let cli = Cli::parse();
@@ -26,9 +27,8 @@ async fn main() -> Result<()> {
Commands::Version => {
println!("ente-rs version {}", ente_rs::cli::version::VERSION);
}
- Commands::Account(_account_cmd) => {
- // TODO: Implement account commands
- println!("Account command not yet implemented");
+ Commands::Account(account_cmd) => {
+ commands::account::handle_account_command(account_cmd, &storage).await?;
}
Commands::Export(_export_cmd) => {
// TODO: Implement export command
diff --git a/rust/src/storage/mod.rs b/rust/src/storage/mod.rs
index 0e31c9198f..065b44fc8f 100644
--- a/rust/src/storage/mod.rs
+++ b/rust/src/storage/mod.rs
@@ -1,6 +1,6 @@
#![allow(dead_code)]
-use crate::{Error, Result};
+use crate::Result;
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::path::Path;