π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Expose saved account tokens and unify app naming
Manav Rathi872c3afde9ce
diff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli-next/src/api.rsindex b87a4d32b9..13de887363 100644--- a/rust/apps/cli-next/src/api.rs+++ b/rust/apps/cli-next/src/api.rs@@ -16,7 +16,7 @@ use url::Url;use zeroize::Zeroizing;use crate::{- args::{ApiArgs, Product},+ args::{ApiArgs, App},parse_json, read_input,vault::Account,};@@ -32,17 +32,17 @@ pub fn http() -> Result<Client> {.build()?)}-pub fn accounts_client(origin: &str, product: Product) -> Result<AccountsClient> {+pub fn accounts_client(origin: &str, app: App) -> Result<AccountsClient> {Ok(AccountsClient::new(- AccountsClientConfig::new(product.client_package())+ AccountsClientConfig::new(app.client_package()).with_origin(origin).with_user_agent(USER_AGENT),)?)}-pub async fn logout(account: &Account, product: Product) -> Result<()> {- let client = accounts_client(&account.origin, product)?;- client.set_auth_token(Some(b64::encode_url_safe(account.token(product)?)));+pub async fn logout(account: &Account, app: App) -> Result<()> {+ let client = accounts_client(&account.origin, app)?;+ client.set_auth_token(Some(b64::encode_url_safe(account.token(app)?)));match client.logout().await {Ok(()) => Ok(()),Err(ente_accounts::Error::Http(error)) if error.status_code() == Some(401) => Ok(()),@@ -50,11 +50,11 @@ pub async fn logout(account: &Account, product: Product) -> Result<()> {}}-pub fn session(account: &Account, product: Product) -> Result<Session> {+pub fn session(account: &Account, app: App) -> Result<Session> {let mut config = ApiConfig::new(account.origin.clone());- config.client_package = Some(product.client_package().into());+ config.client_package = Some(app.client_package().into());config.user_agent = Some(USER_AGENT.into());- config.auth = Some(Auth::User(b64::encode_url_safe(account.token(product)?)));+ config.auth = Some(Auth::User(b64::encode_url_safe(account.token(app)?)));Session::new(config,account.user_id,@@ -65,7 +65,7 @@ pub fn session(account: &Account, product: Product) -> Result<Session> {.map_err(Into::into)}-pub async fn raw(account: &Account, product: Product, args: ApiArgs) -> Result<()> {+pub async fn raw(account: &Account, app: App, args: ApiArgs) -> Result<()> {ensure!(!(args.headers.as_deref() == Some(Path::new("-"))&& args.body.as_deref() == Some(Path::new("-"))),@@ -100,7 +100,7 @@ pub async fn raw(account: &Account, product: Product, args: ApiArgs) -> Result<("Host cannot redirect stored account credentials");}- let token = Zeroizing::new(b64::encode_url_safe(account.token(product)?));+ let token = Zeroizing::new(b64::encode_url_safe(account.token(app)?));let mut value = HeaderValue::from_str(&token)?;value.set_sensitive(true);headers.insert("x-auth-token", value);@@ -108,7 +108,7 @@ pub async fn raw(account: &Account, product: Product, args: ApiArgs) -> Result<(if !headers.contains_key("x-client-package") {headers.insert("x-client-package",- HeaderValue::from_static(product.client_package()),+ HeaderValue::from_static(app.client_package()),);}let method = Method::from_bytes(args.method.to_ascii_uppercase().as_bytes())?;diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex ad04c57fb1..0b7d62a1cb 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -1,6 +1,6 @@use std::{io::IsTerminal, num::NonZeroUsize, path::PathBuf};-use clap::{Args, Parser, Subcommand};+use clap::{Args, Parser, Subcommand, ValueEnum};use serde::{Deserialize, Serialize};#[derive(Parser)]@@ -81,12 +81,12 @@ pub enum Command {#[command(subcommand)]command: PhotosCommand,},- #[command(about = "Manage Locker sessions and make API requests")]+ #[command(about = "Manage Ente Locker")]Locker {#[command(flatten)]selector: AccountSelector,#[command(subcommand)]- command: SessionCommand,+ command: AppCommand,},#[command(about = "Manage Ente Auth")]Auth {@@ -95,8 +95,8 @@ pub enum Command {#[command(subcommand)]command: AuthCommand,},- #[command(about = "Manage accounts on this device", alias = "account")]- Accounts {+ #[command(about = "Manage Ente accounts", alias = "accounts")]+ Account {#[command(subcommand)]command: AccountCommand,},@@ -117,7 +117,7 @@ Keep the same home and key across unattended invocations."#[derive(Subcommand)]pub enum AuthCommand {#[command(flatten)]- Session(SessionCommand),+ App(AppCommand),#[command(about = "Export your Auth codes; encrypted by default")]#[command(after_long_help = "Refreshes Auth data first; --offline uses previously synced data.@@ -165,7 +165,7 @@ pub struct AuthExportArgs {#[derive(Subcommand)]pub enum PhotosCommand {#[command(flatten)]- Session(SessionCommand),+ App(AppCommand),#[command(flatten)]Library(PhotosLibraryCommand),}@@ -177,7 +177,7 @@ pub enum PhotosLibraryCommand {after_long_help = "Refreshes metadata and downloads originals to DESTINATION; requires network access.Progress goes to stderr; the result goes to stdout. Use --json for a structured result.")]- Export(ExportArgs),+ Export(PhotosExportArgs),#[command(about = "Manage albums")]Album {#[command(subcommand)]@@ -198,7 +198,7 @@ Progress goes to stderr; the result goes to stdout. Use --json for a structured}#[derive(Args)]-pub struct ExportArgs {+pub struct PhotosExportArgs {#[arg(long,value_name = "ALBUM",@@ -225,7 +225,7 @@ pub struct ExportArgs {}#[derive(Subcommand)]-pub enum SessionCommand {+pub enum AppCommand {#[command(about = "Log in",after_help = "Non-interactive login reads JSON from --input:@@ -340,7 +340,7 @@ pub enum FileCommand {const ACCOUNT_HELP: &str = "Reads accounts stored on this device without network access.With --json, list returns an array and view returns one object.-Fields: id, name, email, host (strings); products (string array); selected (boolean).";+Fields: id, name, email, host (strings); apps (string array); selected (boolean).";#[derive(Subcommand)]pub enum AccountCommand {@@ -353,6 +353,22 @@ pub enum AccountCommand {#[arg(help = "Account name")]name: 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.+--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.+Plain output is padded URL-safe Base64 followed by a newline.+With --json, returns {\"token\":\"...\"}."+ )]+ Token {+ #[command(flatten)]+ selector: AccountSelector,+ #[arg(long, value_enum, help = "App whose token to print")]+ app: App,+ },#[command(about = "Make an account the selected one")]Switch {#[arg(help = "Account name")]@@ -365,7 +381,7 @@ pub enum AccountCommand {#[arg(help = "New local name")]new_name: String,},- #[command(about = "Log out of every product and remove the account from this device")]+ #[command(about = "Log out of every app and remove the account from this device")]Logout {#[arg(help = "Account name")]name: String,@@ -392,15 +408,15 @@ pub enum KeyCommand {Generate,}-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, ValueEnum)]#[serde(rename_all = "lowercase")]-pub enum Product {+pub enum App {Photos,Locker,Auth,}-impl Product {+impl App {pub fn name(self) -> &'static str {match self {Self::Photos => "photos",diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rsindex a31988ab83..1b41b403e3 100644--- a/rust/apps/cli-next/src/auth/mod.rs+++ b/rust/apps/cli-next/src/auth/mod.rs@@ -11,15 +11,15 @@ use zeroize::Zeroizing;use crate::{api,- args::{AuthCommand, AuthExportArgs, Options, Product},+ args::{App, AuthCommand, AuthExportArgs, Options},db, home,};use output::Destination;pub async fn run(command: AuthCommand, selected: Option<&str>, options: &Options) -> Result<()> {match command {- AuthCommand::Session(command) => {- crate::session(Product::Auth, command, selected, options).await+ AuthCommand::App(command) => {+ crate::app_command(App::Auth, command, selected, options).await}AuthCommand::Export(args) => export(args, selected, options).await,AuthCommand::Decrypt { input, output } => {@@ -62,7 +62,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)};let payload = {let (account, home) = home::open_account(selected, !options.offline)?;- let session = api::session(&account, Product::Auth)?;+ let session = api::session(&account, App::Auth)?;let mut db = db::open(&home.path, &account.db_key, !options.offline)?;if !options.offline {replica::refresh(&mut db, &session).await?;@@ -74,15 +74,15 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)if !matches!(destination, Destination::Stdout) {crate::output::action(options.json,- &json!({"output": null, "records": 0, "failed": payload.failed}),+ &json!({"output": null, "codes": 0, "failures": payload.failed}),&format!(- "{} unreadable Auth record{plural}; no new backup was written.",+ "{} unreadable Auth code{plural}; no new backup was written.",payload.failed),)?;}bail!(- "{} unreadable Auth record{plural}; no new backup was written (record ID{plural}: {})",+ "{} unreadable Auth code{plural}; no new backup was written (code ID{plural}: {})",payload.failed,payload.failed_ids.join(", "));@@ -94,7 +94,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)if let Some(path) = destination.publish(&artifact)? {crate::output::action(options.json,- &json!({"output": path.to_string_lossy(), "records": payload.records, "failed": 0}),+ &json!({"output": path.to_string_lossy(), "codes": payload.records, "failures": 0}),&format!("Exported {} code{} to {}.",payload.records,diff --git a/rust/apps/cli-next/src/db.rs b/rust/apps/cli-next/src/db.rsindex 18e6abba8e..8b583ea29c 100644--- a/rust/apps/cli-next/src/db.rs+++ b/rust/apps/cli-next/src/db.rs@@ -4,7 +4,7 @@ use anyhow::{Context, Result};use rusqlite::{Connection, OpenFlags};use zeroize::Zeroizing;-use crate::{auth, core_db::Db, replica, vault::DbKey};+use crate::{auth, core_db::Db, photos::replica, vault::DbKey};const MIGRATIONS: &[&str] = &[replica::SCHEMA, auth::replica::SCHEMA];diff --git a/rust/apps/cli-next/src/home.rs b/rust/apps/cli-next/src/home.rsindex 3f05cf9ec3..59ea6ab107 100644--- a/rust/apps/cli-next/src/home.rs+++ b/rust/apps/cli-next/src/home.rs@@ -10,17 +10,17 @@ use uuid::Uuid;use crate::vault::{Account, State};-pub struct AccountHome {+pub struct LockedAccountHome {pub path: PathBuf,_lock: File,}pub struct RemovalGuard {_lock: File,- home: AccountHome,+ home: LockedAccountHome,}-pub fn open_account(selected: Option<&str>, create: bool) -> Result<(Account, AccountHome)> {+pub fn open_account(selected: Option<&str>, create: bool) -> Result<(Account, LockedAccountHome)> {let state = State::load()?;let id = state.accounts[state.resolve(selected)?].storage_id;let home = lock_account(id, create)?;@@ -62,19 +62,19 @@ pub fn create(path: &Path) -> io::Result<()> {Ok(())}-pub fn lock_account(id: Uuid, create: bool) -> Result<AccountHome> {+pub fn lock_account(id: Uuid, create: bool) -> Result<LockedAccountHome> {let home = account_home(id, create)?;home._lock.lock().context("cannot lock the account home")?;Ok(home)}-pub fn try_lock_account(id: Uuid) -> Result<AccountHome> {+pub fn try_lock_account(id: Uuid) -> Result<LockedAccountHome> {let home = account_home(id, true)?;try_lock(&home._lock)?;Ok(home)}-fn account_home(id: Uuid, create: bool) -> Result<AccountHome> {+fn account_home(id: Uuid, create: bool) -> Result<LockedAccountHome> {let accounts = application_home()?.join("accounts");let path = accounts.join(id.to_string());let lock_path = accounts.join(format!("{id}.lock"));@@ -84,10 +84,10 @@ fn account_home(id: Uuid, create: bool) -> Result<AccountHome> {ensure!(path.is_dir(), "no local data; run the command online first");}let lock = open_lock(&lock_path).context("cannot open the account lock")?;- Ok(AccountHome { path, _lock: lock })+ Ok(LockedAccountHome { path, _lock: lock })}-impl AccountHome {+impl LockedAccountHome {pub fn storage_use(&self) -> Result<File> {let lock = open_lock(&self.path.with_extension("use.lock")).context("cannot open the account use lock")?;diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rsindex b5a2d6184f..b1935e00e4 100644--- a/rust/apps/cli-next/src/login.rs+++ b/rust/apps/cli-next/src/login.rs@@ -14,13 +14,13 @@ use zeroize::{ZeroizeOnDrop, Zeroizing};use crate::{api,- args::{LoginArgs, Options, Product},+ args::{App, LoginArgs, Options},parse_json, read_input,vault::{Account, AccountKeys, DbKey, State, StoredSession, Vault},};pub async fn login(- product: Product,+ app: App,args: LoginArgs,selected: Option<&str>,options: &Options,@@ -64,7 +64,7 @@ pub async fn login(Some(credentials) => credentials,None => Credentials::prompt()?,};- let client = api::accounts_client(&origin, product)?;+ let client = api::accounts_client(&origin, app)?;let mut authenticated = authenticate(&client, &mut credentials, interactive).await?;client.set_auth_token(Some(ente_core::b64::encode_url_safe(&authenticated.secrets.token,@@ -134,12 +134,12 @@ pub async fn login(let index = if let Some(index) = existing {ensure!(!supplied_name,- "account already exists; use accounts rename to change its local name"+ "account already exists; use account rename to change its local name");let account = &mut vault.state.accounts[index];account.email = email;account.identity = identity;- previous_session = account.sessions.insert(product, session);+ previous_session = account.sessions.insert(app, session);index} else {vault.state.check_name(&new_name)?;@@ -152,7 +152,7 @@ pub async fn login(origin,user_id: authenticated.user_id,identity,- sessions: BTreeMap::from([(product, session)]),+ sessions: BTreeMap::from([(app, session)]),});index};@@ -177,7 +177,7 @@ pub async fn login(} else {"previous"};- eprintln!("Could not revoke the {session} login session: {error}");+ eprintln!("Could not end the {session} login: {error}");}result}diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsindex 8a4ec00c26..5f6cfc277b 100644--- a/rust/apps/cli-next/src/main.rs+++ b/rust/apps/cli-next/src/main.rs@@ -3,12 +3,10 @@ mod args;mod auth;mod core_db;mod db;-mod export;mod home;mod login;mod output;mod photos;-mod replica;mod vault;use std::{@@ -24,11 +22,10 @@ use serde_json::json;use zeroize::Zeroizing;use args::{- AccountCommand, Cli, Command, KeyCommand, Options, PhotosCommand, Product, SessionCommand,- VaultCommand,+ AccountCommand, App, AppCommand, Cli, Command, KeyCommand, Options, PhotosCommand, VaultCommand,};use output::AccountView;-use vault::{State, Vault};+use vault::{Account, State, Vault};#[tokio::main]async fn main() {@@ -78,33 +75,19 @@ async fn run(cli: Cli) -> Result<()> {match command {Command::Photos {selector,- command: PhotosCommand::Session(command),- } => {- session(- Product::Photos,- command,- selector.account.as_deref(),- &options,- )- .await- }+ 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 } => {- session(- Product::Locker,- command,- selector.account.as_deref(),- &options,- )- .await+ app_command(App::Locker, command, selector.account.as_deref(), &options).await}Command::Auth { selector, command } => {auth::run(command, selector.account.as_deref(), &options).await}- Command::Accounts { command } => account_command(command, &options).await,+ Command::Account { command } => account_command(command, &options).await,Command::Vault {command:VaultCommand::Key {@@ -123,54 +106,66 @@ fn vault_key(json_output: bool) -> Result<()> {}}-async fn session(- product: Product,- command: SessionCommand,+async fn app_command(+ app: App,+ command: AppCommand,selected: Option<&str>,options: &Options,) -> Result<()> {ensure!(!options.offline, "this command requires network access");match command {- SessionCommand::Api(args) => {+ AppCommand::Api(args) => {let state = State::load()?;let index = state.resolve(selected)?;- api::raw(&state.accounts[index], product, args).await+ api::raw(&state.accounts[index], app, args).await}- SessionCommand::Login(args) => {- let (state, index) = login::login(product, args, selected, options).await?;+ AppCommand::Login(args) => {+ let (state, index) = login::login(app, args, selected, options).await?;let account = AccountView::new(&state.accounts[index], state.selected);if options.json {- output::json(&json!({ "account": account, "product": product }))+ output::json(&json!({ "account": account, "app": app }))} else {output::account(&account)}}- SessionCommand::Logout => {+ 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(&product) {+ let removal = if sessions.len() == 1 && sessions.contains_key(&app) {Some(home.for_removal()?)} else {None};- api::logout(&vault.state.accounts[index], product).await?;- vault.state.accounts[index].sessions.remove(&product);- let removed = vault.state.accounts[index].sessions.is_empty();- if removed {- remove_account(&mut vault.state, index);- }+ 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()?;}- drop(vault);+ 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": name, "product": product, "loggedOut": true }),- &format!("Logged out of {} for {:?}.", product.display_name(), name),+ &json!({ "account": account, "app": app, "remoteLogout": true }),+ &message,)}}@@ -200,6 +195,16 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(output::account(&account)}}+ AccountCommand::Token { selector, app } => {+ let state = State::load()?;+ let index = state.resolve(selector.account.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() }))+ } else {+ writeln!(std::io::stdout(), "{}", token.as_str()).map_err(Into::into)+ }+ }AccountCommand::Switch { name } => {let mut vault = Vault::open()?;let state = &mut vault.state;@@ -231,15 +236,15 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(let index = vault.state.named(&name)?;let home =home::try_lock_account(vault.state.accounts[index].storage_id)?.for_removal()?;- let products = vault.state.accounts[index]+ let apps = vault.state.accounts[index].sessions.keys().copied().collect::<Vec<_>>();if !local {- for product in &products {- if let Err(error) = api::logout(&vault.state.accounts[index], *product).await {- if vault.state.accounts[index].sessions.len() < products.len() {+ for app in &apps {+ if let Err(error) = api::logout(&vault.state.accounts[index], *app).await {+ if vault.state.accounts[index].sessions.len() < apps.len() {vault.save()?;}let remaining = vault.state.accounts[index]@@ -249,33 +254,35 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(.collect::<Vec<_>>();bail!("cannot log out of {} for {name:?}: {error:#}. Still logged in: {}. Retry when the server is reachable, or use --local to forget the account on this device.",- product.display_name(),- product_names(&remaining),+ app.display_name(),+ app_names(&remaining),);}- vault.state.accounts[index].sessions.remove(product);+ vault.state.accounts[index].sessions.remove(app);}}- remove_account(&mut vault.state, index);+ let mut account = remove_account(&mut vault.state, index);+ account.sessions.clear();+ let selected = vault.state.selected;vault.save()?;home.remove()?;drop(vault);- let message = if local && !products.is_empty() {- format!(- "Logged out of {name:?} on this device only. Still logged in on the server: {}.",- product_names(&products)- )- } else if products.is_empty() {+ let message = 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.")} else {- format!("Logged out of {} for {name:?}.", product_names(&products))+ format!(+ "Logged out of {}. Removed account {name:?} from this device.",+ app_names(&apps)+ )};output::action(options.json,&json!({- "account": name,- "products": products,- "sessions": if local { "active" } else { "revoked" },+ "account": AccountView::new(&account, selected),+ "apps": apps,+ "remoteLogout": !local,}),&message,)@@ -283,17 +290,18 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(}}-fn remove_account(state: &mut State, index: usize) {- let storage_id = state.accounts.remove(index).storage_id;- if state.selected == Some(storage_id) {+fn remove_account(state: &mut State, index: usize) -> Account {+ let account = state.accounts.remove(index);+ if state.selected == Some(account.storage_id) {state.selected = None;}+ account}-fn product_names(products: &[Product]) -> String {- let names = products+fn app_names(apps: &[App]) -> String {+ let names = apps.iter()- .map(|product| product.display_name())+ .map(|app| app.display_name()).collect::<Vec<_>>();match names.as_slice() {[] => String::new(),diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli-next/src/output.rsindex dee0265d5c..246dcb0a58 100644--- a/rust/apps/cli-next/src/output.rs+++ b/rust/apps/cli-next/src/output.rs@@ -11,7 +11,7 @@ use serde::Serialize;use uuid::Uuid;use crate::{- args::{DEFAULT_LIST_LIMIT, ListArgs, Product},+ args::{App, DEFAULT_LIST_LIMIT, ListArgs},vault::Account,};@@ -21,7 +21,7 @@ pub struct AccountView<'a> {name: &'a str,email: &'a str,host: &'a str,- products: Vec<Product>,+ apps: Vec<App>,selected: bool,}@@ -32,7 +32,7 @@ impl<'a> AccountView<'a> {name: &account.name,email: &account.email,host: &account.origin,- products: account.sessions.keys().copied().collect(),+ apps: account.sessions.keys().copied().collect(),selected: selected == Some(account.storage_id),}}@@ -150,7 +150,7 @@ pub fn accounts(accounts: &[AccountView<'_>]) -> Result<()> {escape_controls(account.name),escape_controls(account.email),escape_controls(account.host),- products(account),+ apps(account),account.id.clone(),]})@@ -168,7 +168,7 @@ pub fn account(account: &AccountView<'_>) -> Result<()> {("Name", escape_controls(account.name)),("Email", escape_controls(account.email)),("Host", escape_controls(account.host)),- ("Logged in", products(account)),+ ("Logged in", apps(account)),("Selected",if account.selected { "yes" } else { "no" }.to_owned(),@@ -281,17 +281,17 @@ fn timestamp(micros: i64) -> Result<String> {.to_rfc3339_opts(SecondsFormat::Micros, true))}-fn products(account: &AccountView<'_>) -> String {- let products = account- .products+fn apps(account: &AccountView<'_>) -> String {+ let apps = account+ .apps.iter()- .map(|product| product.name())+ .map(|app| app.name()).collect::<Vec<_>>().join(",");- if products.is_empty() {+ if apps.is_empty() {"none".to_owned()} else {- products+ apps}}diff --git a/rust/apps/cli-next/src/export/mod.rs b/rust/apps/cli-next/src/photos/export/mod.rssimilarity index 91%rename from rust/apps/cli-next/src/export/mod.rsrename to rust/apps/cli-next/src/photos/export/mod.rsindex 974ecf3724..e22d51ba6d 100644--- a/rust/apps/cli-next/src/export/mod.rs+++ b/rust/apps/cli-next/src/photos/export/mod.rs@@ -9,12 +9,12 @@ use tokio::sync::watch;use crate::{api,- args::{ExportArgs, Options, Product},+ args::{App, Options, PhotosExportArgs},db, home, output,vault::State,};-pub async fn run(args: ExportArgs, selected: Option<&str>, options: &Options) -> Result<()> {+pub async fn run(args: PhotosExportArgs, selected: Option<&str>, options: &Options) -> Result<()> {ensure!(!options.offline,"export requires network access; remove --offline"@@ -28,11 +28,11 @@ pub async fn run(args: ExportArgs, selected: Option<&str>, options: &Options) ->.await?}-async fn run_locked(args: ExportArgs, selected: Option<&str>, as_json: bool) -> Result<()> {+async fn run_locked(args: PhotosExportArgs, selected: Option<&str>, as_json: bool) -> Result<()> {let mut state = State::load()?;let index = state.resolve(selected)?;let account = state.accounts.swap_remove(index);- let session = api::session(&account, Product::Photos)?;+ let session = api::session(&account, App::Photos)?;// Declare first so export's stores drop before this lock.let _storage_use;let mut export = Export::open(@@ -52,7 +52,7 @@ async fn run_locked(args: ExportArgs, selected: Option<&str>, as_json: bool) ->.into_iter().find(|a| a.storage_id == account.storage_id).context("account was removed while waiting for access")?;- let session = api::session(&account, Product::Photos)?;+ let session = api::session(&account, App::Photos)?;export.verify_source(&session.master_key)?;_storage_use = account_home.storage_use()?;home::create(&account_home.path)?;diff --git a/rust/apps/cli-next/src/export/source.rs b/rust/apps/cli-next/src/photos/export/source.rssimilarity index 98%rename from rust/apps/cli-next/src/export/source.rsrename to rust/apps/cli-next/src/photos/export/source.rsindex bfa687672a..557bf9393d 100644--- a/rust/apps/cli-next/src/export/source.rs+++ b/rust/apps/cli-next/src/photos/export/source.rs@@ -4,7 +4,7 @@ use ente_photos_export::{CollectionEntry, FileEntry, Source};use crate::{core_db::{Db, OptionalExtension, SqliteResult, params},- replica::{AlbumRecord, FileRecord, Replica, read_json},+ photos::replica::{AlbumRecord, FileRecord, Replica, read_json},};pub struct ReplicaSource<'a> {diff --git a/rust/apps/cli-next/src/photos.rs b/rust/apps/cli-next/src/photos/mod.rssimilarity index 97%rename from rust/apps/cli-next/src/photos.rsrename to rust/apps/cli-next/src/photos/mod.rsindex e53c062daf..9ca8c1bfdb 100644--- a/rust/apps/cli-next/src/photos.rs+++ b/rust/apps/cli-next/src/photos/mod.rs@@ -1,3 +1,6 @@+mod export;+pub mod replica;+use std::{io::Seek, path::Path};use anyhow::{Context, Result, bail, ensure};@@ -7,11 +10,11 @@ use serde_json::json;use crate::{api,- args::{AlbumCommand, FileCommand, Options, PhotosLibraryCommand, Product},+ args::{AlbumCommand, App, FileCommand, Options, PhotosLibraryCommand},db, home,output::{self, AlbumView, FileView},- replica::Replica,};+use replica::Replica;const MAX_CANDIDATES: usize = 10;@@ -21,7 +24,7 @@ pub async fn run(options: &Options,) -> Result<()> {if let PhotosLibraryCommand::Export(args) = command {- return crate::export::run(args, selected, options).await;+ return export::run(args, selected, options).await;}ensure!(!options.offline@@ -35,7 +38,7 @@ pub async fn run("original files are not stored locally; download requires network access");let (account, home) = home::open_account(selected, !options.offline)?;- let session = api::session(&account, Product::Photos)?;+ let session = api::session(&account, App::Photos)?;let mut db = db::open(&home.path, &account.db_key, !options.offline)?;let mut replica = Replica::new(&mut db, session.user_id);if !options.offline {diff --git a/rust/apps/cli-next/src/replica.rs b/rust/apps/cli-next/src/photos/replica.rssimilarity index 100%rename from rust/apps/cli-next/src/replica.rsrename to rust/apps/cli-next/src/photos/replica.rsdiff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli-next/src/vault.rsindex d83a90c5f9..0444558ab2 100644--- a/rust/apps/cli-next/src/vault.rs+++ b/rust/apps/cli-next/src/vault.rs@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};use uuid::Uuid;use zeroize::{ZeroizeOnDrop, Zeroizing};-use crate::{args::Product, home, parse_json};+use crate::{args::App, home, parse_json};const SCHEMA_VERSION: u8 = 1;const VAULT_FILE: &str = "vault.json";@@ -59,7 +59,7 @@ pub struct Account {pub origin: String,pub user_id: i64,pub identity: AccountKeys,- pub sessions: BTreeMap<Product, StoredSession>,+ pub sessions: BTreeMap<App, StoredSession>,}#[derive(Serialize, Deserialize, ZeroizeOnDrop)]@@ -175,7 +175,7 @@ impl State {self.accounts.iter().position(|a| a.name == name)- .with_context(|| format!("no account named {name:?}; use accounts list"))+ .with_context(|| format!("no account named {name:?}; use account list"))}pub fn resolve(&self, name: Option<&str>) -> Result<usize> {@@ -192,7 +192,7 @@ impl State {match self.accounts.len() {0 => bail!("no accounts; use photos login, locker login, or auth login"),1 => Ok(0),- _ => bail!("no account selected; use accounts switch <name> or --account <name>"),+ _ => bail!("no account selected; use account switch <name> or --account <name>"),}}@@ -207,16 +207,16 @@ impl State {}impl Account {- pub fn token(&self, product: Product) -> Result<&[u8]> {+ pub fn token(&self, app: App) -> Result<&[u8]> {self.sessions- .get(&product)+ .get(&app).map(|s| s.token.as_slice()).with_context(|| {format!(- "account {:?} has no {} session; use {} login --account {:?}",+ "account {:?} is not logged into {}; use {} login --account {:?}",self.name,- product.name(),- product.name(),+ app.display_name(),+ app.name(),self.name)})diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rsindex 9f338aed3a..36a9bca4d5 100644--- a/rust/apps/cli-next/tests/cli.rs+++ b/rust/apps/cli-next/tests/cli.rs@@ -35,6 +35,22 @@ fn reads_do_not_initialize_storage() {assert!(help.contains("Usage: ente-cli-next [OPTIONS] <COMMAND>"));assert!(help.contains(&format!("=== {binary} photos file download ===")));assert!(help.contains(&format!("=== {binary} vault key generate ===")));+ assert!(help.contains(&format!("=== {binary} account token ===")));+ assert!(help.contains("Manage Ente accounts"));+ assert!(help.contains("Manage Ente Locker"));+ assert!(help.contains("Use this account instead of the selected one"));+ assert!(help.contains("apps (string array); selected (boolean)"));+ assert!(help.contains(+ "This prints a secret and does not check whether the server still accepts it."+ ));+ assert!(help.contains("With --json, returns {\"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());let output = home.command(&["accounts", "list"]).env("ENTE_CLI_HOME", &path)@@ -44,6 +60,7 @@ fn reads_do_not_initialize_storage() {for args in [vec!["accounts", "list", "--json"],vec!["accounts", "view", "missing"],+ vec!["account", "token", "--app", "photos"],vec!["photos", "album", "list"],vec!["photos", "album", "view", "missing"],vec!["photos", "file", "list"],@@ -169,10 +186,10 @@ fn reading_an_existing_vault_does_not_change_its_directory() {let home = TestHome::new();home.seed("http://localhost:8080");fs::set_permissions(home.dir.path(), fs::Permissions::from_mode(0o500)).unwrap();- let result = home.run(&["account", "list"]);+ let result = home.run(&["account", "token", "--app", "photos"]);let mode = fs::metadata(home.dir.path()).unwrap().permissions().mode() & 0o777;fs::set_permissions(home.dir.path(), fs::Permissions::from_mode(0o700)).unwrap();- success(result);+ assert_eq!(success(result).stdout, b"--8=\n");assert_eq!(mode, 0o500, "read changed the CLI home permissions");assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 1);}@@ -234,7 +251,7 @@ fn keys_and_invalid_vaults_have_no_destructive_fallback() {}let wrong_key = failure(&home- .command(&["account", "list"])+ .command(&["account", "token", "--app", "photos"]).env("ENTE_CLI_VAULT_KEY",b64::encode(Key::generate().as_bytes()),@@ -452,12 +469,15 @@ fn logout_reconciles_remote_and_local_session_state() {.match_header("x-auth-token", "--8=").match_header("x-client-package", "io.ente.photos").with_status(401)+ .expect(3).create();let home = TestHome::new();home.seed(&server.url());+ let mut state = home.read_vault();+ let mut account = home.json(&["account", "view", "fixture"]);assert_eq!(success(home.run(&["photos", "logout"])).stdout,- b"Logged out of Ente Photos for \"fixture\".\n"+ b"Logged out of Ente Photos. Removed account \"fixture\" from this device.\n");assert_eq!(home.json(&["account", "list"]), json!([]));assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));@@ -467,6 +487,26 @@ fn logout_reconciles_remote_and_local_session_state() {.count(),0);+ state["accounts"][0]["sessions"]["auth"] = json!({"token": [2]});+ home.write_vault(&state);+ account["apps"] = json!(["auth"]);+ assert_eq!(+ home.json(&["photos", "logout"]),+ json!({"account": account, "app": "photos", "remoteLogout": true})+ );+ assert_eq!(home.json(&["account", "view", "fixture"]), account);+ state["accounts"][0]["sessions"]+ .as_object_mut()+ .unwrap()+ .remove("auth");+ home.write_vault(&state);+ account["apps"] = json!([]);+ account["selected"] = json!(false);+ assert_eq!(+ home.json(&["photos", "logout"]),+ json!({"account": account, "app": "photos", "remoteLogout": true})+ );+ assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));revoked.assert();let unavailable = server@@ -486,7 +526,7 @@ fn logout_reconciles_remote_and_local_session_state() {}#[test]-fn account_logout_revokes_every_product_before_removing_the_account() {+fn account_logout_revokes_every_app_before_removing_the_account() {let mut server = mockito::Server::new();let home = TestHome::new();home.seed(&server.url());@@ -494,27 +534,55 @@ fn account_logout_revokes_every_product_before_removing_the_account() {state["accounts"][0]["sessions"]["locker"] = json!({"token": [1]});state["accounts"][0]["sessions"]["auth"] = json!({"token": [2]});home.write_vault(&state);+ let mut account = home.json(&["account", "view", "fixture"]);+ account["apps"] = json!([]);+ account["selected"] = json!(false);let photos = server.mock("POST", "/users/logout").match_header("x-auth-token", "--8=").match_header("x-client-package", "io.ente.photos")+ .expect(2).create();let locker_token = b64::encode_url_safe(&[1]);let locker = server.mock("POST", "/users/logout").match_header("x-auth-token", locker_token.as_str()).match_header("x-client-package", "io.ente.locker")+ .expect(2).create();let auth_token = b64::encode_url_safe(&[2]);let auth = server.mock("POST", "/users/logout").match_header("x-auth-token", auth_token.as_str()).match_header("x-client-package", "io.ente.auth")+ .expect(2).create();assert_eq!(success(home.run(&["account", "logout", "fixture"])).stdout,- b"Logged out of Ente Photos, Ente Locker, and Ente Auth for \"fixture\".\n"+ b"Logged out of Ente Photos, Ente Locker, and Ente Auth. Removed account \"fixture\" from this device.\n"+ );+ assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));+ home.write_vault(&state);+ assert_eq!(+ home.json(&["account", "logout", "fixture"]),+ json!({"account": account, "apps": ["photos", "locker", "auth"], "remoteLogout": true})+ );+ home.write_vault(&state);+ assert_eq!(+ home.json(&["account", "logout", "fixture", "--local", "--offline"]),+ json!({"account": account, "apps": ["photos", "locker", "auth"], "remoteLogout": false})+ );+ state["accounts"][0]["sessions"] = json!({});+ home.write_vault(&state);+ assert_eq!(+ home.json(&["account", "logout", "fixture"]),+ json!({"account": account, "apps": [], "remoteLogout": true})+ );+ home.write_vault(&state);+ assert_eq!(+ success(home.run(&["account", "logout", "fixture", "--local"])).stdout,+ b"Removed account \"fixture\" from this device.\n");assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));photos.assert();@@ -559,7 +627,7 @@ fn account_logout_preserves_sessions_that_it_could_not_revoke() {assert_eq!(success(home.run(&["account", "logout", "fixture", "--local"])).stdout,- b"Logged out of \"fixture\" on this device only. Still logged in on the server: Ente Locker and Ente Auth.\n"+ b"Removed account \"fixture\" from this device. Server logout was skipped.\n");assert_eq!(home.read_vault(), json!({"accounts": [], "selected": null}));photos.assert();@@ -575,13 +643,12 @@ fn account_updates_preserve_identity_and_selection() {success(home.run(&["account", "view", "fixture"])).stdout,b"Name fixture\nEmail [email protected]\nHost http://localhost:8080\nLogged in photos\nSelected yes\nID 9007199254740993\n");- assert_eq!(- home.json(&["account", "list"]),- json!([{- "id": "9007199254740993", "name": "fixture", "email": "[email protected]",- "host": "http://localhost:8080", "products": ["photos"], "selected": true- }])- );+ let account = json!({+ "id": "9007199254740993", "name": "fixture", "email": "[email protected]",+ "host": "http://localhost:8080", "apps": ["photos"], "selected": true+ });+ assert_eq!(home.json(&["account", "list"]), json!([account]));+ assert_eq!(home.json(&["accounts", "view", "fixture"]), account);let mut state = home.read_vault();let mut second = state["accounts"][0].clone();second["storage_id"] = json!("f6579aae-83ef-4f28-965e-8d34883d3fe5");@@ -616,6 +683,98 @@ fn account_updates_preserve_identity_and_selection() {assert_eq!(home.read_encrypted_vault(), after);}+#[test]+fn account_token_reads_the_requested_saved_login() {+ let home = TestHome::new();+ let args = [+ "account",+ "token",+ "--app",+ "photos",+ "--offline",+ "--no-input",+ ];+ assert!(+ failure(&home.run(&args))+ .contains("no accounts; use photos login, locker login, or auth login")+ );+ home.seed("http://127.0.0.1:1");+ let mut state = home.read_vault();+ state["selected"] = Value::Null;+ home.write_vault(&state);+ let vault = home.dir.path().join("vault.json");+ let before = fs::read(&vault).unwrap();+ let output = success(home.run(&args));+ assert_eq!(output.stdout, b"--8=\n");+ assert!(output.stderr.is_empty());+ assert_eq!(home.json(&args), json!({"token": "--8="}));+ assert_eq!(fs::read(&vault).unwrap(), before);++ let mut other = state["accounts"][0].clone();+ other["storage_id"] = json!("f6579aae-83ef-4f28-965e-8d34883d3fe5");+ other["name"] = json!("other");+ other["sessions"] = json!({"locker": {"token": [1]}});+ state["selected"] = other["storage_id"].clone();+ state["accounts"][0]["sessions"]["auth"] = json!({"token": [255]});+ state["accounts"].as_array_mut().unwrap().push(other);+ home.write_vault(&state);+ let before = fs::read(&vault).unwrap();+ assert_eq!(+ home.json(&["account", "token", "--app", "locker"]),+ json!({"token": "AQ=="})+ );+ assert_eq!(+ home.json(&["account", "token", "--account", "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\""+ ));+ assert!(missing_login.stdout.is_empty());+ let explicit_login = home.run(&[+ "account",+ "token",+ "--app",+ "locker",+ "--account",+ "fixture",+ ]);+ assert!(failure(&explicit_login).contains(+ "account \"fixture\" is not logged into Ente Locker; use locker login --account \"fixture\""+ ));+ assert!(explicit_login.stdout.is_empty());+ let missing_account = home+ .command(&args)+ .args(["--account", "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);++ state["selected"] = Value::Null;+ home.write_vault(&state);+ 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>")+ );+ assert!(ambiguous.stdout.is_empty());+ let (reader, writer) = std::io::pipe().unwrap();+ drop(reader);+ let write_failure = home+ .command(&args)+ .args(["--account", "fixture"])+ .stdout(writer)+ .output()+ .unwrap();+ let error = failure(&write_failure);+ assert!(!error.contains("--8="));+ assert_eq!(fs::read(&vault).unwrap(), before);+}+struct TestHome {dir: TempDir,key: Key,diff --git a/rust/apps/cli-next/tests/support/auth.rs b/rust/apps/cli-next/tests/support/auth.rsindex 45e4bcecda..927712f7db 100644--- a/rust/apps/cli-next/tests/support/auth.rs+++ b/rust/apps/cli-next/tests/support/auth.rs@@ -45,7 +45,7 @@ fn page(server: &mut Server, since: i64, rows: Vec<Value>) -> Mock {}#[test]-fn refresh_keeps_progress_and_refuses_unreadable_records_until_updated() {+fn refresh_keeps_progress_and_refuses_unreadable_codes_until_updated() {let mut server = Server::new();let home = TestHome::new();seed(&home, &server.url());@@ -99,13 +99,13 @@ fn refresh_keeps_progress_and_refuses_unreadable_records_until_updated() {"--json",]);let stderr = failure(&failed);- assert!(stderr.contains("2 unreadable Auth records"));+ assert!(stderr.contains("2 unreadable Auth codes"));assert!(stderr.contains(&Uuid::from_u128(1).to_string()));assert!(!stderr.contains("private-secret"));assert!(!stderr.contains("JBSWY3DPEHPK3PXP"));assert_eq!(serde_json::from_slice::<Value>(&failed.stdout).unwrap(),- json!({"output": null, "records": 0, "failed": 2})+ json!({"output": null, "codes": 0, "failures": 2}));assert_eq!(fs::read_dir(output_dir.path()).unwrap().count(), 1);changed.assert();@@ -308,7 +308,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari"--output",plaintext_file.to_str().unwrap(),]);- assert_eq!(plain_summary["records"], 1);+ assert_eq!(plain_summary["codes"], 1);assert_eq!(fs::read(plaintext_file).unwrap(), plain);let password = " independent export password ";let result = success(@@ -326,8 +326,8 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari.unwrap(),);let summary: Value = serde_json::from_slice(&result.stdout).unwrap();- assert_eq!(summary["records"], 1);- assert_eq!(summary["failed"], 0);+ assert_eq!(summary["codes"], 1);+ assert_eq!(summary["failures"], 0);let encoded = fs::read(&encrypted).unwrap();let stream = success(home.command(&["auth", "export", "--offline", "--output", "-", "--json"])@@ -337,7 +337,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari);let stream: Value = serde_json::from_slice(&stream.stdout).unwrap();assert_eq!(stream["version"], 1);- assert!(stream.get("records").is_none());+ assert!(stream.get("codes").is_none());assert!(stream["encryptedData"].is_string());let restore = TestHome::new();let absent_home = restore.dir.path().join("absent");diff --git a/rust/apps/cli-next/tests/support/export_maintenance.rs b/rust/apps/cli-next/tests/support/export_maintenance.rsindex 1e58775d1b..ce250cbd81 100644--- a/rust/apps/cli-next/tests/support/export_maintenance.rs+++ b/rust/apps/cli-next/tests/support/export_maintenance.rs@@ -83,7 +83,7 @@ fn export_and_download_preserve_non_utf8_paths() {assert_eq!(result["complete"], true);assert_eq!(result["changes"]["exported"], exported);assert_eq!(- result["destination"],+ result["output"],fs::canonicalize(&root).unwrap().to_string_lossy().as_ref());assert_component(&root, "First", "Photo.jpg", b"original");diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rsindex f3d954a67b..f3f4c89d63 100644--- a/rust/apps/cli-next/tests/support/museum.rs+++ b/rust/apps/cli-next/tests/support/museum.rs@@ -379,7 +379,9 @@ async fn exercise(origin: String) -> TestResult {assert_eq!(home.read_vault()["accounts"][0]["storage_id"], first_id);login(&home, "auth", &bob_email, &["--host", &origin]);- assert!(failure(&home.run(&["photos", "album", "list"])).contains("no photos session"));+ assert!(+ failure(&home.run(&["photos", "album", "list"])).contains("is not logged into Ente Photos")+ );login(&home, "locker", &alice_email, &["--account", "work"]);let accounts = home.json(&["account", "list"]);assert!(@@ -394,7 +396,7 @@ async fn exercise(origin: String) -> TestResult {.as_array().unwrap().iter()- .any(|a| a["name"] == "work" && a["products"] == json!(["photos", "locker"]))+ .any(|a| a["name"] == "work" && a["apps"] == json!(["photos", "locker"])));login(&home, "photos", &bob_email, &["--account", &bob_email]);@@ -609,7 +611,10 @@ async fn exercise(origin: String) -> TestResult {let token: Vec<u8> =serde_json::from_value(state["accounts"][0]["sessions"]["photos"]["token"].clone()).unwrap();- success(home.run(&["photos", "logout"]));+ assert_eq!(+ success(home.run(&["photos", "logout"])).stdout,+ b"Logged out of Ente Photos for \"work\".\n"+ );let response = reqwest::Client::new().get(format!("{origin}/collections/v2")).header("x-auth-token", b64::encode_url_safe(&token))@@ -620,7 +625,7 @@ async fn exercise(origin: String) -> TestResult {assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);failure(&home.run(&["photos", "album", "list"]));assert_eq!(- home.json(&["account", "view", "work"])["products"],+ home.json(&["account", "view", "work"])["apps"],json!(["locker"]));let account_dir = home@@ -658,12 +663,20 @@ async fn exercise(origin: String) -> TestResult {Ok(())}-fn login(home: &TestHome, product: &str, email: &str, options: &[&str]) {- let mut args = vec![product, "login", "--input", "-", "--json"];+fn login(home: &TestHome, app: &str, email: &str, options: &[&str]) {+ let mut args = vec![app, "login", "--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();- assert_eq!(result["product"], product);+ assert_eq!(result["app"], app);+ assert_eq!(+ result["account"],+ home.json(&[+ "account",+ "view",+ result["account"]["name"].as_str().unwrap()+ ])+ );}fn credentials(email: &str) -> Vec<u8> {diff --git a/rust/crates/photos-export/src/lib.rs b/rust/crates/photos-export/src/lib.rsindex bbcd815bbb..643b4c3a5a 100644--- a/rust/crates/photos-export/src/lib.rs+++ b/rust/crates/photos-export/src/lib.rs@@ -825,7 +825,7 @@ fn summary(store: &Store, destination: &Path, prepared: bool) -> Result<Summary>.db.query_row("SELECT bound FROM export WHERE id=1", [], |r| r.get(0))?;let complete = bound && work_complete(store, prepared)?;- let result = json!({"destination":destination.to_string_lossy(),"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"retained":retained},"failures":failures,"conflicts":conflicts});+ let result = json!({"output":destination.to_string_lossy(),"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"retained":retained},"failures":failures,"conflicts":conflicts});Ok(Summary {json: result,complete,