π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Unify account login and management commands
Manav Rathidcb76c25f262
diff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli-next/src/api.rsindex 13de887363..dc154b3a51 100644--- a/rust/apps/cli-next/src/api.rs+++ b/rust/apps/cli-next/src/api.rs@@ -16,9 +16,9 @@ use url::Url;use zeroize::Zeroizing;use crate::{- args::{ApiArgs, App},+ args::{ApiArgs, App, Options},parse_json, read_input,- vault::Account,+ vault::{Account, State},};pub(crate) const USER_AGENT: &str = concat!("ente-cli-next/", env!("CARGO_PKG_VERSION"));@@ -65,7 +65,10 @@ pub fn session(account: &Account, app: App) -> Result<Session> {.map_err(Into::into)}-pub async fn raw(account: &Account, app: App, args: ApiArgs) -> Result<()> {+pub async fn run(app: App, args: ApiArgs, selected: Option<&str>, options: &Options) -> Result<()> {+ ensure!(!options.offline, "this command requires network access");+ let state = State::load()?;+ let account = &state.accounts[state.resolve(selected)?];ensure!(!(args.headers.as_deref() == Some(Path::new("-"))&& args.body.as_deref() == Some(Path::new("-"))),diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex 0b7d62a1cb..1d894ecbc3 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -9,12 +9,12 @@ use serde::{Deserialize, Serialize};about = "Use Ente from the command line",override_usage = "ente-cli-next [OPTIONS] <COMMAND>",after_help = "Photos:- ente-cli-next photos login+ ente-cli-next account login --app photosente-cli-next photos album listente-cli-next photos file list --album <ID>ente-cli-next photos export <DIR>Auth backups:- ente-cli-next auth login+ ente-cli-next account login --app authente-cli-next auth export <DIR>")]pub struct Cli {@@ -86,7 +86,7 @@ pub enum Command {#[command(flatten)]selector: AccountSelector,#[command(subcommand)]- command: AppCommand,+ command: LockerCommand,},#[command(about = "Manage Ente Auth")]Auth {@@ -116,8 +116,8 @@ Keep the same home and key across unattended invocations."#[derive(Subcommand)]pub enum AuthCommand {- #[command(flatten)]- App(AppCommand),+ #[command(about = "Make an authenticated API request", after_help = API_HELP)]+ Api(ApiArgs),#[command(about = "Export your Auth codes; encrypted by default")]#[command(after_long_help = "Refreshes Auth data first; --offline uses previously synced data.@@ -164,14 +164,8 @@ pub struct AuthExportArgs {#[derive(Subcommand)]pub enum PhotosCommand {- #[command(flatten)]- App(AppCommand),- #[command(flatten)]- Library(PhotosLibraryCommand),-}--#[derive(Subcommand)]-pub enum PhotosLibraryCommand {+ #[command(about = "Make an authenticated API request", after_help = API_HELP)]+ Api(ApiArgs),#[command(about = "Maintain an independent copy of your Photos library")]#[command(after_long_help = "Refreshes metadata and downloads originals to DESTINATION; requires network access.@@ -225,40 +219,22 @@ pub struct PhotosExportArgs {}#[derive(Subcommand)]-pub enum AppCommand {- #[command(- about = "Log in",- after_help = "Non-interactive login reads JSON from --input:- {\"email\": \"...\", \"password\": \"...\", \"otp\": \"123456\", \"totp\": \"654321\"}--All fields are strings. otp is the email code; totp is the authenticator code. Supply them when required.-With --no-input, supply email and password through --input PATH or --input -.-For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help)."- )]- Login(LoginArgs),- #[command(about = "Log out")]- Logout,- #[command(- about = "Make an authenticated API request",- after_help = "The response body is written unchanged, including when --json is set."- )]+pub enum LockerCommand {+ #[command(about = "Make an authenticated API request", after_help = API_HELP)]Api(ApiArgs),}#[derive(Args)]pub struct LoginArgs {+ #[arg(help = "Local account name; creates an entry if it does not exist")]+ pub name: Option<String>,+ #[arg(long, value_enum, help = "App to log in to")]+ pub app: App,#[arg(long,- conflicts_with = "account",- help = "Ente server to log in to; defaults to api.ente.com"+ help = "Ente server; defaults to the saved account's server or api.ente.com")]pub host: Option<String>,- #[arg(- long,- conflicts_with = "account",- help = "Name for a new account on this device; defaults to the account's email"- )]- pub name: Option<String>,#[arg(long,help = "Read login credentials as JSON from this file, or from stdin with -"@@ -266,6 +242,8 @@ pub struct LoginArgs {pub input: Option<PathBuf>,}+const API_HELP: &str = "The response body is written unchanged, including when --json is set.";+#[derive(Args)]pub struct ApiArgs {#[arg(help = "API path or URL at the selected account's server")]@@ -344,19 +322,35 @@ Fields: id, name, email, host (strings); apps (string array); selected (boolean)#[derive(Subcommand)]pub enum AccountCommand {+ #[command(+ about = "Log an account into an app",+ after_long_help = "An existing name requires matching credentials; a new name creates a local entry.+Omit NAME to use the selected account, or the only saved account.+With no saved accounts, creates an entry named after the authenticated email.+With several accounts and none selected, supply NAME or use account switch.+A new entry becomes selected; logging into an existing entry keeps the selection.++Non-interactive login reads JSON from --input:+ {\"email\": \"...\", \"password\": \"...\", \"otp\": \"123456\", \"totp\": \"654321\"}++All fields are strings. otp is the email code; totp is the authenticator code. Supply them when required.+With --no-input, supply email and password through --input PATH or --input -.+For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help)."+ )]+ Login(LoginArgs),#[command(about = "List accounts on this device")]#[command(after_long_help = ACCOUNT_HELP)]List,#[command(about = "Show an account")]#[command(after_long_help = ACCOUNT_HELP)]View {- #[arg(help = "Account name")]- name: String,+ #[arg(help = "Account name; defaults to the selected or only saved account")]+ name: Option<String>,},#[command(about = "Print the saved API token for an account")]#[command(- after_long_help = "Uses --account NAME, otherwise the selected account, otherwise the only saved account.-With several accounts and none selected, use --account NAME or account switch.+ after_long_help = "Uses NAME, otherwise the selected account, otherwise the only saved account.+With several accounts and none selected, supply NAME or use account switch.--app is required and selects that account's saved login.Reads the saved token from the local vault without contacting the server or refreshing it.This prints a secret and does not check whether the server still accepts it.@@ -364,8 +358,8 @@ Plain output is padded URL-safe Base64 followed by a newline.With --json, returns {\"token\":\"...\"}.")]Token {- #[command(flatten)]- selector: AccountSelector,+ #[arg(help = "Account name; defaults to the selected or only saved account")]+ name: Option<String>,#[arg(long, value_enum, help = "App whose token to print")]app: App,},@@ -376,17 +370,29 @@ With --json, returns {\"token\":\"...\"}."},#[command(about = "Change an account's local name")]Rename {- #[arg(help = "Account name")]+ #[arg(value_name = "OLD_NAME", help = "Current local name")]name: String,- #[arg(help = "New local name")]+ #[arg(value_name = "NEW_NAME", help = "New local name")]new_name: String,},- #[command(about = "Log out of every app and remove the account from this device")]+ #[command(+ about = "Log out of an app, or every app when --app is omitted",+ after_long_help = "Removes the local account and its cached data after its last app login is removed.+Without --app, logs out of all this account's saved app logins on this device.+--local removes the account and its cached data without contacting the server."+ )]Logout {- #[arg(help = "Account name")]- name: String,+ #[arg(help = "Account name; defaults to the selected or only saved account")]+ name: Option<String>,+ #[arg(+ long,+ value_enum,+ help = "App to log out of; defaults to every saved app"+ )]+ app: Option<App>,#[arg(long,+ conflicts_with = "app",help = "Forget the account on this device without logging out on the server")]local: bool,diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rsindex 1b41b403e3..dbbf07e7bc 100644--- a/rust/apps/cli-next/src/auth/mod.rs+++ b/rust/apps/cli-next/src/auth/mod.rs@@ -18,9 +18,7 @@ use output::Destination;pub async fn run(command: AuthCommand, selected: Option<&str>, options: &Options) -> Result<()> {match command {- AuthCommand::App(command) => {- crate::app_command(App::Auth, command, selected, options).await- }+ AuthCommand::Api(args) => api::run(App::Auth, args, selected, options).await,AuthCommand::Export(args) => export(args, selected, options).await,AuthCommand::Decrypt { input, output } => {let destination = Destination::file(output.unwrap_or_else(|| PathBuf::from("-")));diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rsindex b1935e00e4..e7ff0b93b9 100644--- a/rust/apps/cli-next/src/login.rs+++ b/rust/apps/cli-next/src/login.rs@@ -14,28 +14,14 @@ use zeroize::{ZeroizeOnDrop, Zeroizing};use crate::{api,- args::{App, LoginArgs, Options},+ args::{LoginArgs, Options},parse_json, read_input,vault::{Account, AccountKeys, DbKey, State, StoredSession, Vault},};-pub async fn login(- app: App,- args: LoginArgs,- selected: Option<&str>,- options: &Options,-) -> Result<(State, usize)> {- enum Target<'a> {- Existing(&'a str),- New(String),- }-- let target = match selected {- Some(name) => Target::Existing(name),- None => Target::New(normalize_host(- args.host.as_deref().unwrap_or(DEFAULT_API_ORIGIN),- )?),- };+pub async fn login(args: LoginArgs, options: &Options) -> Result<(State, usize)> {+ let app = args.app;+ let host = args.host.as_deref().map(normalize_host).transpose()?;let credentials = args.input.as_deref().map(Credentials::read).transpose()?;let interactive = credentials.is_none() && options.can_prompt();ensure!(@@ -43,17 +29,33 @@ pub async fn login("login requires email and password; supply --input <file> or --input -");let vault = Vault::open()?;- if let Some(name) = args.name.as_deref() {- vault.state.check_name(name)?;- }- let (expected, origin) = match target {- Target::Existing(name) => {- let account = &vault.state.accounts[vault.state.named(name)?];- (Some(account.storage_id), account.origin.clone())+ let index = if let Some(name) = args.name.as_deref() {+ vault+ .state+ .accounts+ .iter()+ .position(|account| account.name == name)+ } else if vault.state.accounts.is_empty() {+ None+ } else {+ Some(vault.state.resolve(None)?)+ };+ let (expected, origin) = if let Some(index) = index {+ let account = &vault.state.accounts[index];+ ensure!(+ host.as_ref().is_none_or(|host| *host == account.origin),+ "account {:?} uses {}; supply a new account name to log in to another server",+ account.name,+ account.origin,+ );+ (Some(account.storage_id), account.origin.clone())+ } else {+ if let Some(name) = args.name.as_deref() {+ vault.state.check_name(name)?;}- Target::New(origin) => (None, origin),+ (None, host.unwrap_or_else(|| DEFAULT_API_ORIGIN.to_owned()))};- let (snapshot, access) = vault.release();+ let access = vault.release();let mut config = ApiConfig::new(origin.clone());config.user_agent = Some(api::USER_AGENT.into());Api::new(Http::new()?, config)@@ -70,35 +72,9 @@ pub async fn login(&authenticated.secrets.token,)));- let supplied_name = args.name.is_some();- let requested_name = args.name;let mut previous_session = None;let result = async {let email = client.email().await?;- let snapshot_existing = snapshot.accounts.iter().position(|account| {- account.origin == origin && account.user_id == authenticated.user_id- });- if let Some(expected) = expected {- ensure!(- snapshot_existing- .is_some_and(|index| snapshot.accounts[index].storage_id == expected),- "authenticated identity does not match --account"- );- }- let mut new_name = requested_name.unwrap_or_else(|| email.clone());- if snapshot_existing.is_none() {- while let Err(error) = snapshot.check_name(&new_name) {- if !interactive {- return Err(error.context("supply a different local account name with --name"));- }- eprintln!("{error}");- new_name = Input::new()- .with_prompt("Local account name")- .interact_on(&Term::stderr())?;- }- }- drop(snapshot);-let mut vault = access.open()?;let existing = vault.state@@ -114,7 +90,7 @@ pub async fn login(.context("selected account was removed during login")?;ensure!(existing == Some(current),- "authenticated identity does not match --account"+ "authenticated identity does not match the saved account");}let recovery_key = Zeroizing::new(@@ -133,7 +109,7 @@ pub async fn login(};let index = if let Some(index) = existing {ensure!(- !supplied_name,+ expected.is_some() || args.name.is_none(),"account already exists; use account rename to change its local name");let account = &mut vault.state.accounts[index];@@ -142,6 +118,7 @@ pub async fn login(previous_session = account.sessions.insert(app, session);index} else {+ let new_name = args.name.unwrap_or_else(|| email.clone());vault.state.check_name(&new_name)?;let index = vault.state.accounts.len();vault.state.accounts.push(Account {@@ -154,11 +131,9 @@ pub async fn login(identity,sessions: BTreeMap::from([(app, session)]),});+ vault.state.selected = Some(vault.state.accounts[index].storage_id);index};- if expected.is_none() {- vault.state.selected = Some(vault.state.accounts[index].storage_id);- }vault.save()?;Ok((vault.into_state(), index))}diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsindex 5b58fb8a69..38ae6f3f0d 100644--- a/rust/apps/cli-next/src/main.rs+++ b/rust/apps/cli-next/src/main.rs@@ -21,9 +21,7 @@ use serde::de::DeserializeOwned;use serde_json::json;use zeroize::Zeroizing;-use args::{- AccountCommand, App, AppCommand, Cli, Command, KeyCommand, Options, PhotosCommand, VaultCommand,-};+use args::{AccountCommand, App, Cli, Command, KeyCommand, LockerCommand, Options, VaultCommand};use output::AccountView;use vault::{Account, State, Vault};@@ -73,17 +71,13 @@ fn print_all_help(command: &mut clap::Command, output: &mut impl Write) -> Resulasync fn run(cli: Cli) -> Result<()> {let Cli { options, command } = cli;match command {- Command::Photos {- selector,- command: PhotosCommand::App(command),- } => app_command(App::Photos, command, selector.account.as_deref(), &options).await,- Command::Photos {- selector,- command: PhotosCommand::Library(command),- } => photos::run(command, selector.account.as_deref(), &options).await,- Command::Locker { selector, command } => {- app_command(App::Locker, command, selector.account.as_deref(), &options).await+ Command::Photos { selector, command } => {+ photos::run(command, selector.account.as_deref(), &options).await}+ Command::Locker {+ selector,+ command: LockerCommand::Api(args),+ } => api::run(App::Locker, args, selector.account.as_deref(), &options).await,Command::Auth { selector, command } => {auth::run(command, selector.account.as_deref(), &options).await}@@ -106,21 +100,12 @@ fn vault_key(json_output: bool) -> Result<()> {}}-async fn app_command(- app: App,- command: AppCommand,- selected: Option<&str>,- options: &Options,-) -> Result<()> {- ensure!(!options.offline, "this command requires network access");+async fn account_command(command: AccountCommand, options: &Options) -> Result<()> {match command {- AppCommand::Api(args) => {- let state = State::load()?;- let index = state.resolve(selected)?;- api::raw(&state.accounts[index], app, args).await- }- AppCommand::Login(args) => {- let (state, index) = login::login(app, args, selected, options).await?;+ AccountCommand::Login(args) => {+ ensure!(!options.offline, "login requires network access");+ let app = args.app;+ let (state, index) = login::login(args, options).await?;let account = AccountView::new(&state.accounts[index], state.selected);if options.json {output::json(&json!({ "account": account, "app": app }))@@ -128,51 +113,6 @@ async fn app_command(output::account(&account)}}- AppCommand::Logout => {- let mut vault = Vault::open()?;- let index = vault.state.resolve(selected)?;- let home = home::try_lock_account(vault.state.accounts[index].storage_id)?;- let name = vault.state.accounts[index].name.clone();- let sessions = &vault.state.accounts[index].sessions;- let removal = if sessions.len() == 1 && sessions.contains_key(&app) {- Some(home.for_removal()?)- } else {- None- };- api::logout(&vault.state.accounts[index], app).await?;- vault.state.accounts[index].sessions.remove(&app);- let removed = vault.state.accounts[index]- .sessions- .is_empty()- .then(|| remove_account(&mut vault.state, index));- vault.save()?;- if let Some(removal) = removal {- removal.remove()?;- }- let state = vault.into_state();- let account = AccountView::new(- removed.as_ref().unwrap_or_else(|| &state.accounts[index]),- state.selected,- );- let message = if removed.is_some() {- format!(- "Logged out of {}. Removed account {name:?} from this device.",- app.display_name()- )- } else {- format!("Logged out of {} for {name:?}.", app.display_name())- };- output::action(- options.json,- &json!({ "account": account, "app": app, "remoteLogout": true }),- &message,- )- }- }-}--async fn account_command(command: AccountCommand, options: &Options) -> Result<()> {- match command {AccountCommand::List => {let state = State::load()?;let accounts: Vec<_> = state@@ -188,12 +128,12 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(}AccountCommand::View { name } => {let state = State::load()?;- let index = state.named(&name)?;+ let index = state.resolve(name.as_deref())?;output_account(state, index, options.json)}- AccountCommand::Token { selector, app } => {+ AccountCommand::Token { name, app } => {let state = State::load()?;- let index = state.resolve(selector.account.as_deref())?;+ let index = state.resolve(name.as_deref())?;let token = Zeroizing::new(b64::encode_url_safe(state.accounts[index].token(app)?));if options.json {output::json(&json!({ "token": token.as_str() }))@@ -223,24 +163,33 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(}output_account(vault.into_state(), index, options.json)}- AccountCommand::Logout { name, local } => {+ AccountCommand::Logout { name, app, local } => {ensure!(!options.offline || local,"logging out on the server requires network access; use --local to forget the account on this device");let mut vault = Vault::open()?;- let index = vault.state.named(&name)?;- let home =- home::try_lock_account(vault.state.accounts[index].storage_id)?.for_removal()?;- let apps = vault.state.accounts[index]+ let index = vault.state.resolve(name.as_deref())?;+ let account = &vault.state.accounts[index];+ let name = account.name.clone();+ let apps = match app {+ Some(app) => vec![app],+ None => account.sessions.keys().copied().collect(),+ };+ let home = home::try_lock_account(account.storage_id)?;+ let removal = if account.sessions.keys()- .copied()- .collect::<Vec<_>>();+ .all(|saved| app.is_none_or(|app| *saved == app))+ {+ Some(home.for_removal()?)+ } else {+ None+ };if !local {- for app in &apps {+ for (completed, app) in apps.iter().enumerate() {if let Err(error) = api::logout(&vault.state.accounts[index], *app).await {- if vault.state.accounts[index].sessions.len() < apps.len() {+ if completed > 0 {vault.save()?;}let remaining = vault.state.accounts[index]@@ -256,14 +205,25 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(}vault.state.accounts[index].sessions.remove(app);}+ } else {+ vault.state.accounts[index].sessions.clear();}- let mut account = remove_account(&mut vault.state, index);- account.sessions.clear();- let selected = vault.state.selected;+ let removed = vault.state.accounts[index]+ .sessions+ .is_empty()+ .then(|| remove_account(&mut vault.state, index));vault.save()?;- home.remove()?;- drop(vault);- let message = if local && !apps.is_empty() {+ if let Some(removal) = removal {+ removal.remove()?;+ }+ let state = vault.into_state();+ let account = AccountView::new(+ removed.as_ref().unwrap_or_else(|| &state.accounts[index]),+ state.selected,+ );+ let message = if removed.is_none() {+ format!("Logged out of {} for {name:?}.", app_names(&apps))+ } else if local && !apps.is_empty() {format!("Removed account {name:?} from this device. Server logout was skipped.")} else if apps.is_empty() {format!("Removed account {name:?} from this device.")@@ -273,15 +233,11 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(app_names(&apps))};- output::action(- options.json,- &json!({- "account": AccountView::new(&account, selected),- "apps": apps,- "remoteLogout": !local,- }),- &message,- )+ let result = match app {+ Some(app) => json!({ "account": account, "app": app, "remoteLogout": !local }),+ None => json!({ "account": account, "apps": apps, "remoteLogout": !local }),+ };+ output::action(options.json, &result, &message)}}}diff --git a/rust/apps/cli-next/src/photos/mod.rs b/rust/apps/cli-next/src/photos/mod.rsindex 9ca8c1bfdb..a944b15909 100644--- a/rust/apps/cli-next/src/photos/mod.rs+++ b/rust/apps/cli-next/src/photos/mod.rs@@ -10,7 +10,7 @@ use serde_json::json;use crate::{api,- args::{AlbumCommand, App, FileCommand, Options, PhotosLibraryCommand},+ args::{AlbumCommand, App, FileCommand, Options, PhotosCommand},db, home,output::{self, AlbumView, FileView},};@@ -18,19 +18,17 @@ use replica::Replica;const MAX_CANDIDATES: usize = 10;-pub async fn run(- command: PhotosLibraryCommand,- selected: Option<&str>,- options: &Options,-) -> Result<()> {- if let PhotosLibraryCommand::Export(args) = command {- return export::run(args, selected, options).await;+pub async fn run(command: PhotosCommand, selected: Option<&str>, options: &Options) -> Result<()> {+ match command {+ PhotosCommand::Api(args) => return api::run(App::Photos, args, selected, options).await,+ PhotosCommand::Export(args) => return export::run(args, selected, options).await,+ _ => {}}ensure!(!options.offline|| !matches!(&command,- PhotosLibraryCommand::File {+ PhotosCommand::File {command: FileCommand::Download { .. },..}@@ -51,9 +49,9 @@ pub async fn run();}match command {- PhotosLibraryCommand::Export(_) => unreachable!(),- PhotosLibraryCommand::Album { command } => album(command, &replica, options),- PhotosLibraryCommand::File { album, command } => {+ PhotosCommand::Api(_) | PhotosCommand::Export(_) => unreachable!(),+ PhotosCommand::Album { command } => album(command, &replica, options),+ PhotosCommand::File { album, command } => {file(command, album.as_deref(), &session, &mut replica, options).await}}diff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli-next/src/vault.rsindex 0444558ab2..f4c42da63a 100644--- a/rust/apps/cli-next/src/vault.rs+++ b/rust/apps/cli-next/src/vault.rs@@ -104,15 +104,11 @@ impl Vault {self.state}- pub fn release(self) -> (State, VaultAccess) {- let Self {- state,- home,- key,- _lock,- } = self;- drop(_lock);- (state, VaultAccess { home, key })+ pub fn release(self) -> VaultAccess {+ VaultAccess {+ home: self.home,+ key: self.key,+ }}pub fn save(&self) -> Result<()> {@@ -190,9 +186,11 @@ impl State {return Ok(index);}match self.accounts.len() {- 0 => bail!("no accounts; use photos login, locker login, or auth login"),+ 0 => bail!("no accounts; use account login --app <APP>"),1 => Ok(0),- _ => bail!("no account selected; use account switch <name> or --account <name>"),+ _ => bail!(+ "no account selected; use account switch <NAME> or name an account explicitly"+ ),}}@@ -200,7 +198,7 @@ impl State {ensure!(!name.trim().is_empty(), "account name cannot be empty");ensure!(!self.accounts.iter().any(|a| a.name == name),- "account name {name:?} is already in use; choose another --name"+ "account name {name:?} is already in use; choose another name");Ok(())}@@ -213,11 +211,11 @@ impl Account {.map(|s| s.token.as_slice()).with_context(|| {format!(- "account {:?} is not logged into {}; use {} login --account {:?}",+ "account {:?} is not logged into {}; use account login {:?} --app {}",self.name,app.display_name(),- app.name(),- self.name+ self.name,+ app.name())})}diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rsindex 976841aeeb..b088eb71a0 100644--- a/rust/apps/cli-next/tests/cli.rs+++ b/rust/apps/cli-next/tests/cli.rs@@ -36,13 +36,15 @@ fn reads_do_not_initialize_storage() {assert!(help.contains(&format!("=== {binary} photos file download ===")));assert!(help.contains(&format!("=== {binary} vault key generate ===")));assert!(help.contains(&format!("=== {binary} account token ===")));- let missing_app = home- .command(&["account", "token"])- .env("ENTE_CLI_VAULT_KEY", "invalid")- .output()- .unwrap();- assert!(failure(&missing_app).contains("--app <APP>"));- assert!(missing_app.stdout.is_empty());+ for command in ["login", "token"] {+ let missing_app = home+ .command(&["account", command])+ .env("ENTE_CLI_VAULT_KEY", "invalid")+ .output()+ .unwrap();+ assert!(failure(&missing_app).contains("--app <APP>"));+ assert!(missing_app.stdout.is_empty());+ }let output = home.command(&["accounts", "list"]).env("ENTE_CLI_HOME", &path)@@ -104,7 +106,7 @@ fn invalid_login_host_does_not_initialize_storage() {let home = TestHome::new();let path = home.dir.path().join("unused");let output = home- .command(&["photos", "login", "--host", "https://["])+ .command(&["account", "login", "--app", "photos", "--host", "https://["]).env("ENTE_CLI_HOME", &path).output().unwrap();@@ -122,7 +124,15 @@ fn login_requires_input_before_storage_or_network() {.expect(1).create();let origin = server.url();- let mut args = vec!["photos", "login", "--host", &origin, "--no-input"];+ let mut args = vec![+ "account",+ "login",+ "--app",+ "photos",+ "--host",+ &origin,+ "--no-input",+ ];assert!(failure(&home.run(&args)).contains("supply --input"));assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 0);args.extend(["--input", "-"]);@@ -399,7 +409,16 @@ fn private_json_errors_do_not_echo_values() {json!("private-987654321"),] {let output = home.with_input(- &["photos", "login", "--host", &server.url(), "--input", "-"],+ &[+ "account",+ "login",+ "--app",+ "photos",+ "--host",+ &server.url(),+ "--input",+ "-",+ ],&serde_json::to_vec(&input).unwrap(),);assert!(output.stdout.is_empty());@@ -468,7 +487,7 @@ fn logout_reconciles_remote_and_local_session_state() {let mut state = home.read_vault();let mut account = home.json(&["account", "view", "fixture"]);assert_eq!(- success(home.run(&["photos", "logout"])).stdout,+ success(home.run(&["account", "logout", "--app", "photos"])).stdout,b"Logged out of Ente Photos. Removed account \"fixture\" from this device.\n");assert_eq!(home.json(&["account", "list"]), json!([]));@@ -483,7 +502,7 @@ fn logout_reconciles_remote_and_local_session_state() {home.write_vault(&state);account["apps"] = json!(["auth"]);assert_eq!(- home.json(&["photos", "logout"]),+ home.json(&["account", "logout", "--app", "photos"]),json!({"account": account, "app": "photos", "remoteLogout": true}));assert_eq!(home.json(&["account", "view", "fixture"]), account);@@ -495,7 +514,7 @@ fn logout_reconciles_remote_and_local_session_state() {account["apps"] = json!([]);account["selected"] = json!(false);assert_eq!(- home.json(&["photos", "logout"]),+ home.json(&["account", "logout", "--app", "photos"]),json!({"account": account, "app": "photos", "remoteLogout": true}));assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));@@ -509,7 +528,7 @@ fn logout_reconciles_remote_and_local_session_state() {let home = TestHome::new();home.seed(&server.url());let before = fs::read(home.dir.path().join("vault.json")).unwrap();- failure(&home.run(&["photos", "logout"]));+ failure(&home.run(&["account", "logout", "--app", "photos"]));assert_eq!(fs::read(home.dir.path().join("vault.json")).unwrap(),before@@ -641,6 +660,7 @@ fn account_updates_preserve_identity_and_selection() {});assert_eq!(home.json(&["account", "list"]), json!([account]));assert_eq!(home.json(&["accounts", "view", "fixture"]), account);+ assert_eq!(home.json(&["account", "view"]), account);let mut state = home.read_vault();let mut second = state["accounts"][0].clone();second["storage_id"] = json!("f6579aae-83ef-4f28-965e-8d34883d3fe5");@@ -673,6 +693,15 @@ fn account_updates_preserve_identity_and_selection() {);success(home.run(&["account", "switch", "other"]));assert_eq!(home.read_encrypted_vault(), after);+ state["selected"] = Value::Null;+ home.write_vault(&state);+ let before = home.read_encrypted_vault();+ let output = home.with_input(+ &["account", "login", "--app", "auth", "--input", "-"],+ br#"{"email":"[email protected]","password":"password"}"#,+ );+ assert!(failure(&output).contains("no account selected"));+ assert_eq!(home.read_encrypted_vault(), before);}#[test]@@ -712,31 +741,20 @@ fn account_token_reads_the_requested_saved_login() {json!({"token": "AQ=="}));assert_eq!(- home.json(&["account", "token", "--account", "fixture", "--app", "auth"]),+ home.json(&["account", "token", "fixture", "--app", "auth"]),json!({"token": "_w=="}));let missing_login = home.run(&args);assert!(failure(&missing_login).contains(- "account \"other\" is not logged into Ente Photos; use photos login --account \"other\""+ "account \"other\" is not logged into Ente Photos; use account login \"other\" --app photos"));assert!(missing_login.stdout.is_empty());- let explicit_login = home.run(&[- "account",- "token",- "--app",- "locker",- "--account",- "fixture",- ]);+ let explicit_login = home.run(&["account", "token", "--app", "locker", "fixture"]);assert!(failure(&explicit_login).contains(- "account \"fixture\" is not logged into Ente Locker; use locker login --account \"fixture\""+ "account \"fixture\" is not logged into Ente Locker; use account login \"fixture\" --app locker"));assert!(explicit_login.stdout.is_empty());- let missing_account = home- .command(&args)- .args(["--account", "missing"])- .output()- .unwrap();+ let missing_account = home.command(&args).arg("missing").output().unwrap();assert!(failure(&missing_account).contains("no account named \"missing\"; use account list"));assert!(missing_account.stdout.is_empty());assert_eq!(fs::read(&vault).unwrap(), before);@@ -746,15 +764,16 @@ fn account_token_reads_the_requested_saved_login() {let before = fs::read(&vault).unwrap();let ambiguous = home.run(&args);assert!(- failure(&ambiguous)- .contains("no account selected; use account switch <name> or --account <name>")+ failure(&ambiguous).contains(+ "no account selected; use account switch <NAME> or name an account explicitly"+ ));assert!(ambiguous.stdout.is_empty());let (reader, writer) = std::io::pipe().unwrap();drop(reader);let write_failure = home.command(&args)- .args(["--account", "fixture"])+ .arg("fixture").stdout(writer).output().unwrap();@@ -793,7 +812,14 @@ fn native_keyring_survives_separate_processes() {).unwrap();let output = home- .command(&["photos", "login", "--host", &server.url()])+ .command(&[+ "account",+ "login",+ "--app",+ "photos",+ "--host",+ &server.url(),+ ]).args(["--input", input.to_str().unwrap()]).env_remove("ENTE_CLI_VAULT_KEY").output()diff --git a/rust/apps/cli-next/tests/support/export_maintenance.rs b/rust/apps/cli-next/tests/support/export_maintenance.rsindex ce250cbd81..786cc015d1 100644--- a/rust/apps/cli-next/tests/support/export_maintenance.rs+++ b/rust/apps/cli-next/tests/support/export_maintenance.rs@@ -2527,7 +2527,7 @@ fn export_reports_progress_and_keeps_account_storage_while_workers_run() {for args in [vec!["account", "logout", "fixture", "--local"],vec!["account", "logout", "fixture"],- vec!["photos", "logout"],+ vec!["account", "logout", "--app", "photos"],] {let output = ExportChild::spawn(&mut home.command(&args)).unwrap()@@ -2563,7 +2563,7 @@ fn export_reports_progress_and_keeps_account_storage_while_workers_run() {home.write_vault(&with_locker);let revoke = server.mock("POST", "/users/logout").expect(1).create();success(- ExportChild::spawn(&mut home.command(&["photos", "logout"]))+ ExportChild::spawn(&mut home.command(&["account", "logout", "--app", "photos"])).unwrap().wait_with_output().unwrap(),diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rsindex f3f4c89d63..b5239ad601 100644--- a/rust/apps/cli-next/tests/support/museum.rs+++ b/rust/apps/cli-next/tests/support/museum.rs@@ -22,6 +22,10 @@ fn auth_login_refresh_and_offline_export_across_processes() -> TestResult {let owner = create_account(&origin, &email).await;let home = TestHome::new();login(&home, "auth", &email, &["--host", &origin, "--no-input"]);+ let mut state = home.read_vault();+ state["selected"] = Value::Null;+ home.write_vault(&state);+ login(&home, "auth", &email, &[]);let export = ["auth", "export", "--output", "-", "--plaintext"];assert!(success(home.run(&export)).stdout.is_empty());let key = Key::generate();@@ -123,7 +127,8 @@ fn login_save_failures_follow_the_vault_replacement() -> TestResult {);let mut child = home.command(&[- "photos", "login", "--host", &origin, "--input", "-", "--json",+ "account", "login", "--app", "photos", "--host", &origin, "--input", "-",+ "--json",]).stdin(Stdio::piped()).spawn()@@ -360,10 +365,19 @@ async fn exercise(origin: String) -> TestResult {let before = fs::read(home.dir.path().join("vault.json")).unwrap();assert!(failure(&home.with_input(- &["photos", "login", "--host", &alias_origin, "--input", "-"],+ &[+ "account",+ "login",+ "--app",+ "photos",+ "--host",+ &alias_origin,+ "--input",+ "-"+ ],&credentials(&alice_email),))- .contains("already in use")+ .contains("supply a new account name"));assert_eq!(fs::read(home.dir.path().join("vault.json")).unwrap(),@@ -373,16 +387,16 @@ async fn exercise(origin: String) -> TestResult {&home,"photos",&alice_email,- &["--host", &alias_origin, "--name", "other-server"],+ &["other-server", "--host", &alias_origin],);success(home.run(&["account", "rename", &alice_email, "work"]));assert_eq!(home.read_vault()["accounts"][0]["storage_id"], first_id);- login(&home, "auth", &bob_email, &["--host", &origin]);+ login(&home, "auth", &bob_email, &[&bob_email, "--host", &origin]);assert!(failure(&home.run(&["photos", "album", "list"])).contains("is not logged into Ente Photos"));- login(&home, "locker", &alice_email, &["--account", "work"]);+ login(&home, "locker", &alice_email, &["work"]);let accounts = home.json(&["account", "list"]);assert!(accounts@@ -399,7 +413,7 @@ async fn exercise(origin: String) -> TestResult {.any(|a| a["name"] == "work" && a["apps"] == json!(["photos", "locker"])));- login(&home, "photos", &bob_email, &["--account", &bob_email]);+ login(&home, "photos", &bob_email, &[]);let albums = home.json(&["photos", "album", "list"]);let mut ids: Vec<_> = albums.as_array()@@ -530,7 +544,8 @@ async fn exercise(origin: String) -> TestResult {0);- login(&home, "photos", &alice_email, &["--host", &origin]);+ login(&home, "photos", &alice_email, &["work"]);+ success(home.run(&["account", "switch", "work"]));let added_original = b"added after the first sync";let added_file = upload_file(&origin, &alice, album, &key, added_original, None).await@@ -596,23 +611,24 @@ async fn exercise(origin: String) -> TestResult {assert_eq!(state["accounts"][0]["name"], "work");assert!(!serde_json::to_string(&state).unwrap().contains(PASSWORD));let before = fs::read(home.dir.path().join("vault.json")).unwrap();- assert!(- failure(&home.with_input(- &["photos", "login", "--account", "work", "--input", "-"],- &credentials(&bob_email),- ))- .contains("identity does not match")- );- assert_eq!(- fs::read(home.dir.path().join("vault.json")).unwrap(),- before- );+ for name in [Some("work"), None] {+ let mut args = vec!["account", "login", "--app", "photos", "--input", "-"];+ args.extend(name);+ assert!(+ failure(&home.with_input(&args, &credentials(&bob_email)))+ .contains("identity does not match")+ );+ assert_eq!(+ fs::read(home.dir.path().join("vault.json")).unwrap(),+ before+ );+ }let token: Vec<u8> =serde_json::from_value(state["accounts"][0]["sessions"]["photos"]["token"].clone()).unwrap();assert_eq!(- success(home.run(&["photos", "logout"])).stdout,+ success(home.run(&["account", "logout", "--app", "photos"])).stdout,b"Logged out of Ente Photos for \"work\".\n");let response = reqwest::Client::new()@@ -664,7 +680,7 @@ async fn exercise(origin: String) -> TestResult {}fn login(home: &TestHome, app: &str, email: &str, options: &[&str]) {- let mut args = vec![app, "login", "--input", "-", "--json"];+ let mut args = vec!["account", "login", "--app", app, "--input", "-", "--json"];args.extend_from_slice(options);let output = success(home.with_input(&args, &credentials(email)));let result: Value = serde_json::from_slice(&output.stdout).unwrap();