π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Finish Auth export compatibility and command handling
Manav Rathif750953c38e4
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex 5219ef60ef..64e52131b3 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -106,7 +106,7 @@ pub enum AuthCommand {Export(AuthExportArgs),#[command(about = "Decrypt an Auth export without an account")]Decrypt {- #[arg(value_name = "PATH")]+ #[arg(value_name = "PATH", help = "Encrypted Auth backup to decrypt")]input: PathBuf,#[arg(long,@@ -122,7 +122,8 @@ pub struct AuthExportArgs {#[arg(value_name = "DIR",required_unless_present = "output",- conflicts_with = "output"+ conflicts_with = "output",+ help = "Directory for dated backups")]pub directory: Option<PathBuf>,#[arg(diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rsindex 9e8cc44208..b86c756012 100644--- a/rust/apps/cli-next/src/auth/mod.rs+++ b/rust/apps/cli-next/src/auth/mod.rs@@ -29,8 +29,10 @@ pub async fn run(command: AuthCommand, selected: Option<&str>, options: &OptionsAuthCommand::Decrypt { input, output } => {let destination = Destination::file(output.unwrap_or_else(|| PathBuf::from("-")));destination.prepare()?;+ let encrypted =+ fs::read(&input).with_context(|| format!("cannot read {}", input.display()))?;let password = export_password(false)?;- let plaintext = backup::decrypt(&fs::read(input)?, &password)?;+ let plaintext = backup::decrypt(&encrypted, &password)?;let published = destination.publish(&plaintext)?;if let Some(path) = published.path {crate::output::action(@@ -130,9 +132,7 @@ fn export_password(confirm: bool) -> Result<Zeroizing<String>> {io::stdin().is_terminal() && io::stderr().is_terminal(),"set ENTE_CLI_EXPORT_PASSWORD for noninteractive encrypted export or decryption");- let mut prompt = Password::new()- .with_prompt("Export password")- .allow_empty_password(true);+ let mut prompt = Password::new().with_prompt("Export password");if confirm {prompt =prompt.with_confirmation("Confirm export password", "Passwords do not match");diff --git a/rust/apps/cli-next/src/auth/output.rs b/rust/apps/cli-next/src/auth/output.rsindex f51d1d2987..0197bb232d 100644--- a/rust/apps/cli-next/src/auth/output.rs+++ b/rust/apps/cli-next/src/auth/output.rs@@ -51,6 +51,13 @@ impl Destination {Ok(())}Self::Directory { path, .. } => {+ let mut missing = Vec::new();+ for directory in path.ancestors() {+ if directory.as_os_str().is_empty() || directory.try_exists()? {+ break;+ }+ missing.push(directory);+ }let mut builder = fs::DirBuilder::new();builder.recursive(true);#[cfg(unix)]@@ -58,9 +65,18 @@ impl Destination {use std::os::unix::fs::DirBuilderExt;builder.mode(0o700);}- builder- .create(path)- .with_context(|| format!("cannot create export directory {}", path.display()))+ builder.create(path).with_context(|| {+ format!("cannot create export directory {}", path.display())+ })?;+ for directory in missing.into_iter().rev() {+ sync_directory(parent(directory)).with_context(|| {+ format!(+ "cannot sync parent of export directory {}",+ directory.display()+ )+ })?;+ }+ Ok(())}}}diff --git a/rust/apps/cli-next/tests/support/auth.rs b/rust/apps/cli-next/tests/support/auth.rsindex 457aec3c26..8197df84fc 100644--- a/rust/apps/cli-next/tests/support/auth.rs+++ b/rust/apps/cli-next/tests/support/auth.rs@@ -281,6 +281,24 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summariinitial.assert();initial.remove();let directory = tempfile::tempdir().unwrap();+ let nested = success(+ home.command(&[+ "auth",+ "export",+ "nested/backups",+ "--offline",+ "--plaintext",+ "--json",+ ])+ .current_dir(directory.path())+ .output()+ .unwrap(),+ );+ let nested: Value = serde_json::from_slice(&nested.stdout).unwrap();+ assert_eq!(+ fs::read(directory.path().join(nested["output"].as_str().unwrap())).unwrap(),+ plain+ );let encrypted = directory.path().join("backup.json");let plaintext_file = directory.path().join("backup.txt");let plain_summary = home.json(&[@@ -406,6 +424,10 @@ fn password_and_destination_errors_are_resolved_before_account_access() {.unwrap();assert!(failure(&output).contains("must be UTF-8"));}+ let missing = home.run(&["auth", "decrypt", path.to_str().unwrap()]);+ assert!(failure(&missing).contains(&format!("cannot read {}", path.display())));+ assert!(!failure(&missing).contains("ENTE_CLI_EXPORT_PASSWORD"));+ assert!(missing.stdout.is_empty());fs::write(&path, "existing").unwrap();let occupied = home.run(&["auth", "export", "--output", path.to_str().unwrap()]);assert!(failure(&occupied).contains("already exists"));diff --git a/rust/crates/auth/src/record.rs b/rust/crates/auth/src/record.rsindex db42f5ece4..e75cae9bc8 100644--- a/rust/crates/auth/src/record.rs+++ b/rust/crates/auth/src/record.rs@@ -42,7 +42,6 @@ fn interpret(plaintext: &[u8]) -> Result<Zeroizing<String>> {let legacy: Legacy<'_> =serde_json::from_str(value.get()).map_err(|_| Error::InvalidRecord)?;let raw = Zeroizing::new(legacy.raw_data);- let raw = Zeroizing::new(raw.replace('#', "%23"));validate_uri(&raw)?;let display = match legacy.display {Some(display) if display.get().starts_with('{') => display.get(),@@ -70,6 +69,7 @@ fn interpret(plaintext: &[u8]) -> Result<Zeroizing<String>> {}_ => return Err(Error::InvalidRecord),};+ line = Zeroizing::new(line.replace(',', "%2C"));line.push('\n');Ok(line)}@@ -78,7 +78,8 @@ fn validate_uri(uri: &str) -> Result<()> {if !uri.starts_with("otpauth://") || uri.chars().any(char::is_control) {return Err(Error::InvalidRecord);}- let parsed = Url::parse(uri).map_err(|_| Error::InvalidRecord)?;+ let validation_uri = Zeroizing::new(uri.replace('#', "%23"));+ let parsed = Url::parse(&validation_uri).map_err(|_| Error::InvalidRecord)?;if parsed.host_str().is_none()|| !parsed.query_pairs()@@ -97,26 +98,29 @@ mod tests {#[test]fn records_preserve_uri_text_and_legacy_display() {- let uri = "otpauth://hotp/Issuer:label?secret=JBSWY3DPEHPK3PXP&counter=19&digits=8&algorithm=SHA512&x=%252C&x=two&codeDisplay=%7B%22note%22%3A%22literal%252C%22%7D";+ let uri = "otpauth://hotp/Work#login,otpauth://label?secret=JBSWY3DPEHPK3PXP&counter=19&digits=8&algorithm=Algorithm.SHA256&x=%2C&x=%252C&x=two&codeDisplay=%7B%22note%22%3A%22literal%252C%22%7D";+ let expected = "otpauth://hotp/Work#login%2Cotpauth://label?secret=JBSWY3DPEHPK3PXP&counter=19&digits=8&algorithm=Algorithm.SHA256&x=%2C&x=%252C&x=two&codeDisplay=%7B%22note%22%3A%22literal%252C%22%7D";assert_eq!(interpret(&serde_json::to_vec(uri).unwrap()).unwrap().as_str(),- format!("{uri}\n")+ format!("{expected}\n"));let display = json!({"note": "literal%2C, + # π", "tags": ["one,two", "%2C"], "pinned": true,"trashed": true, "position": 45, "lastUsedAt": 123, "tapCount": 7,"iconSrc": "custom", "iconID": "saved", "future": {"unknown": true}});for kind in ["totp", "hotp", "steam"] {let raw = format!(- "otpauth://{kind}/Issuer:label?secret=JBSWY3DPEHPK3PXP&period=60&counter=19&digits=8&algorithm=SHA512&x=%252C&x=two&codeDisplay=old"+ "otpauth://{kind}/Work#login,otpauth://label?secret=JBSWY3DPEHPK3PXP&period=60&counter=19&digits=8&algorithm=Algorithm.SHA512&x=%2C&x=%252C&x=two&codeDisplay=old");let line = interpret(&serde_json::to_vec(&json!({"rawData": raw, "display": display})).unwrap(),).unwrap();- assert!(line.starts_with(raw.strip_suffix("&codeDisplay=old").unwrap()));- let parsed = Url::parse(line.trim_end()).unwrap();+ assert!(line.starts_with(&format!(+ "otpauth://{kind}/Work#login%2Cotpauth://label?secret=JBSWY3DPEHPK3PXP&period=60&counter=19&digits=8&algorithm=Algorithm.SHA512&x=%2C&x=%252C&x=two&"+ )));+ let parsed = Url::parse(&line.trim_end().replace('#', "%23")).unwrap();let metadata: Vec<_> = parsed.query_pairs().filter(|(name, _)| name == "codeDisplay")@@ -132,7 +136,7 @@ mod tests {json!({"rawData": uri, "display": null}),] {let line = interpret(&serde_json::to_vec(&object).unwrap()).unwrap();- let parsed = Url::parse(line.trim_end()).unwrap();+ let parsed = Url::parse(&line.trim_end().replace('#', "%23")).unwrap();let display = parsed.query_pairs().find(|(name, _)| name == "codeDisplay")@@ -149,7 +153,7 @@ mod tests {let display = r#"{"unknown":184467440737095516160001,"decimal":0.123456789012345678901}"#;let legacy = format!(r#"{{"rawData":"{uri}","display":{display}}}"#);let line = interpret(legacy.as_bytes()).unwrap();- let parsed = Url::parse(line.trim_end()).unwrap();+ let parsed = Url::parse(&line.trim_end().replace('#', "%23")).unwrap();assert_eq!(parsed.query_pairs()@@ -171,7 +175,7 @@ mod tests {).unwrap().as_str(),- format!("{uri}\n")+ format!("{expected}\n"));}diff --git a/web/apps/auth/src/services/code.ts b/web/apps/auth/src/services/code.tsindex 4dbdd549da..d033e18ac9 100644--- a/web/apps/auth/src/services/code.ts+++ b/web/apps/auth/src/services/code.ts@@ -71,11 +71,11 @@ const parsePathname = (url: URL): [type: Code["type"], path: string] => {switch (url.host.toLowerCase()) {case "totp":- return ["totp", url.pathname.toLowerCase()];+ return ["totp", url.pathname];case "hotp":- return ["hotp", url.pathname.toLowerCase()];+ return ["hotp", url.pathname];case "steam":- return ["steam", url.pathname.toLowerCase()];+ return ["steam", url.pathname];default:break;}@@ -135,8 +135,10 @@ const parsePeriod = (url: URL): number =>const parseAlgorithm = (url: URL): Code["algorithm"] => {switch (url.searchParams.get("algorithm")?.toLowerCase()) {case "sha256":+ case "algorithm.sha256":return "sha256";case "sha512":+ case "algorithm.sha512":return "sha512";default:return "sha1";@@ -191,6 +193,7 @@ export const generateOTPs = (secret: code.secret,counter: counter,algorithm: code.algorithm,+ digits: code.length,});otp = hotp.generate({ counter });nextOTP = hotp.generate({ counter: counter + 1 });