π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add andOTP import support with encrypted backup handling
Joice Josephefbaaad3a39a
diff --git a/mobile/apps/auth/lib/l10n/arb/app_en.arb b/mobile/apps/auth/lib/l10n/arb/app_en.arbindex 86bcd2ce62..49fbb50daf 100644--- a/mobile/apps/auth/lib/l10n/arb/app_en.arb+++ b/mobile/apps/auth/lib/l10n/arb/app_en.arb@@ -623,5 +623,20 @@"chooseIcon": "Choose icon","customOrder": "Custom order","selectAnOption": "Select an option",- "todaysLogs": "Today's logs"+ "todaysLogs": "Today's logs",+ "importAndOTPGuide": "Export your backup from andOTP using the \"Backup\" option in Settings.\n\nIf your backup is encrypted, you will need to enter the backup password to decrypt it.",+ "enterPasswordToDecryptAndOTP": "Enter password to decrypt andOTP backup",+ "failedToDecryptAndOTPBackup": "Failed to decrypt andOTP backup",+ "andOTPSkippedEntriesTitle": "{count, plural, =1{1 entry skipped} other{{count} entries skipped}}",+ "@andOTPSkippedEntriesTitle": {+ "description": "Title showing how many entries were skipped during andOTP import",+ "placeholders": {+ "count": {+ "description": "Number of entries skipped",+ "type": "int",+ "example": "2"+ }+ }+ },+ "andOTPSkippedEntriesReason": "These entries use unsupported formats (such as MOTP) and could not be imported."}diff --git a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dartnew file mode 100644index 0000000000..eac7c285bb--- /dev/null+++ b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart@@ -0,0 +1,295 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:ente_auth/l10n/l10n.dart';+import 'package:ente_auth/models/code.dart';+import 'package:ente_auth/models/code_display.dart';+import 'package:ente_auth/services/authenticator_service.dart';+import 'package:ente_auth/store/code_store.dart';+import 'package:ente_auth/ui/components/buttons/button_widget.dart';+import 'package:ente_auth/ui/components/dialog_widget.dart';+import 'package:ente_auth/ui/components/models/button_type.dart';+import 'package:ente_auth/ui/settings/data/import/import_success.dart';+import 'package:ente_auth/utils/dialog_util.dart';+import 'package:ente_ui/components/progress_dialog.dart';+import 'package:file_picker/file_picker.dart';+import 'package:flutter/material.dart';+import 'package:logging/logging.dart';+import 'package:pointycastle/export.dart';++final _logger = Logger('AndOTPImport');++Future<void> showAndOTPImportInstruction(BuildContext context) async {+ final l10n = context.l10n;+ final result = await showDialogWidget(+ context: context,+ title: l10n.importFromApp("andOTP"),+ body: l10n.importAndOTPGuide,+ buttons: [+ ButtonWidget(+ buttonType: ButtonType.primary,+ labelText: l10n.importSelectAppExport("andOTP"),+ isInAlert: true,+ buttonSize: ButtonSize.large,+ buttonAction: ButtonAction.first,+ ),+ ButtonWidget(+ buttonType: ButtonType.secondary,+ labelText: l10n.cancel,+ buttonSize: ButtonSize.large,+ isInAlert: true,+ buttonAction: ButtonAction.second,+ ),+ ],+ );+ if (result?.action != null && result!.action != ButtonAction.cancel) {+ if (result.action == ButtonAction.first) {+ await _pickAndOTPFile(context);+ }+ }+}++Future<void> _pickAndOTPFile(BuildContext context) async {+ final l10n = context.l10n;+ FilePickerResult? result = await FilePicker.platform.pickFiles(+ dialogTitle: l10n.importSelectAppExport("andOTP"),+ allowMultiple: false,+ type: FileType.custom,+ allowedExtensions: ['json', 'aes'],+ );+ if (result == null) {+ return;+ }+ final ProgressDialog progressDialog =+ createProgressDialog(context, l10n.pleaseWait);++ try {+ String path = result.files.single.path!;+ final importResult = await _processAndOTPFile(context, path, progressDialog);+ await progressDialog.hide();+ if (importResult != null) {+ await importSuccessDialog(context, importResult.importedCount);+ if (importResult.skippedEntries.isNotEmpty) {+ await _showSkippedEntriesDialog(context, importResult.skippedEntries);+ }+ }+ } catch (e, s) {+ _logger.severe('Exception while processing andOTP import', e, s);+ await progressDialog.hide();+ await showErrorDialog(+ context,+ l10n.sorry,+ "${l10n.importFailureDescNew}\n Error: ${e.toString()}",+ );+ }+}++class _ImportResult {+ final int importedCount;+ final List<String> skippedEntries;++ _ImportResult({required this.importedCount, required this.skippedEntries});+}++Future<_ImportResult?> _processAndOTPFile(+ BuildContext context,+ String path,+ ProgressDialog dialog,+) async {+ File file = File(path);+ List<dynamic> entries;++ // Try to detect if file is encrypted or plain text+ // Plain text files are valid JSON arrays, encrypted files are binary+ final Uint8List fileBytes = await file.readAsBytes();++ try {+ // Try to parse as JSON (plain text format)+ final jsonString = utf8.decode(fileBytes);+ entries = jsonDecode(jsonString) as List<dynamic>;+ await dialog.show();+ } catch (e) {+ // If JSON parsing fails, assume it's encrypted+ String? password;+ try {+ await showTextInputDialog(+ context,+ title: context.l10n.enterPasswordToDecryptAndOTP,+ submitButtonLabel: context.l10n.submit,+ isPasswordInput: true,+ onSubmit: (value) async {+ password = value;+ },+ );+ if (password == null) {+ return null;+ }+ await dialog.show();+ final decryptedContent = _decryptAndOTPBackup(fileBytes, password!);+ entries = jsonDecode(decryptedContent) as List<dynamic>;+ } catch (e, s) {+ _logger.warning("Exception while decrypting andOTP backup", e, s);+ await dialog.hide();+ if (password != null) {+ await showErrorDialog(+ context,+ context.l10n.failedToDecryptAndOTPBackup,+ context.l10n.pleaseCheckPasswordAndTryAgain,+ );+ }+ return null;+ }+ }++ final List<Code> parsedCodes = [];+ final List<String> skippedEntries = [];++ for (var item in entries) {+ final String type = (item['type'] as String).toUpperCase();+ final String issuer = item['issuer'] ?? '';+ final String label = item['label'] ?? '';+ final String displayName = issuer.isNotEmpty+ ? (label.isNotEmpty ? '$issuer ($label)' : issuer)+ : label;++ // Skip unsupported types (MOTP)+ if (type == 'MOTP') {+ skippedEntries.add(displayName.isNotEmpty ? displayName : 'Unknown MOTP');+ continue;+ }++ // Validate supported types+ if (type != 'TOTP' && type != 'HOTP' && type != 'STEAM') {+ skippedEntries+ .add(displayName.isNotEmpty ? displayName : 'Unknown ($type)');+ continue;+ }++ try {+ final String secret = item['secret'];+ final String algorithm = item['algorithm'] ?? 'SHA1';+ final int digits = item['digits'] ?? 6;+ final int period = item['period'] ?? 30;+ final int counter = item['counter'] ?? 0;+ final List<dynamic>? tagsList = item['tags'];+ final List<String> tags =+ tagsList?.map((t) => t.toString()).toList() ?? [];++ final String encodedIssuer = Uri.encodeComponent(issuer);+ final String encodedLabel = Uri.encodeComponent(label);++ String otpUrl;+ if (type == 'TOTP' || type == 'STEAM') {+ final String otpType = type.toLowerCase();+ otpUrl =+ 'otpauth://$otpType/$encodedIssuer:$encodedLabel?secret=$secret&issuer=$encodedIssuer&algorithm=$algorithm&digits=$digits&period=$period';+ } else {+ // HOTP+ otpUrl =+ 'otpauth://hotp/$encodedIssuer:$encodedLabel?secret=$secret&issuer=$encodedIssuer&algorithm=$algorithm&digits=$digits&counter=$counter';+ }++ Code code = Code.fromOTPAuthUrl(otpUrl);+ if (tags.isNotEmpty) {+ code = code.copyWith(display: CodeDisplay(tags: tags));+ }+ parsedCodes.add(code);+ } catch (e, s) {+ _logger.warning('Failed to parse andOTP entry: $displayName', e, s);+ skippedEntries.add(displayName.isNotEmpty ? displayName : 'Parse error');+ }+ }++ for (final code in parsedCodes) {+ await CodeStore.instance.addCode(code, shouldSync: false);+ }+ unawaited(AuthenticatorService.instance.onlineSync());++ return _ImportResult(+ importedCount: parsedCodes.length,+ skippedEntries: skippedEntries,+ );+}++String _decryptAndOTPBackup(Uint8List fileBytes, String password) {+ // andOTP encrypted file structure:+ // [iterations: 4 bytes][salt: 12 bytes][IV + ciphertext + auth tag]+ const int intLength = 4;+ const int saltLength = 12;+ const int ivLength = 12;++ if (fileBytes.length < intLength + saltLength + ivLength) {+ throw Exception('Invalid andOTP encrypted file: file too small');+ }++ // Extract iterations (4 bytes, big-endian)+ final ByteData byteData = ByteData.sublistView(fileBytes, 0, intLength);+ final int iterations = byteData.getInt32(0, Endian.big);++ // Extract salt (12 bytes)+ final Uint8List salt =+ Uint8List.sublistView(fileBytes, intLength, intLength + saltLength);++ // Extract encrypted payload (IV + ciphertext + auth tag)+ final Uint8List encryptedPayload =+ Uint8List.sublistView(fileBytes, intLength + saltLength);++ // Extract IV from encrypted payload (first 12 bytes)+ final Uint8List iv = Uint8List.sublistView(encryptedPayload, 0, ivLength);++ // Extract ciphertext + auth tag (remaining bytes)+ final Uint8List ciphertextWithTag =+ Uint8List.sublistView(encryptedPayload, ivLength);++ // Derive key using PBKDF2 with HMAC-SHA1+ const int keyLength = 32; // 256 bits+ final pbkdf2 = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64));+ pbkdf2.init(Pbkdf2Parameters(salt, iterations, keyLength));++ final Uint8List derivedKey = Uint8List(keyLength);+ pbkdf2.deriveKey(+ Uint8List.fromList(utf8.encode(password)),+ 0,+ derivedKey,+ 0,+ );++ // Decrypt using AES-GCM+ final cipher = GCMBlockCipher(AESEngine())+ ..init(+ false,+ AEADParameters(+ KeyParameter(derivedKey),+ 128, // auth tag length in bits+ iv,+ Uint8List(0), // no additional authenticated data+ ),+ );++ final Uint8List decryptedBytes = cipher.process(ciphertextWithTag);+ return utf8.decode(decryptedBytes);+}++Future<void> _showSkippedEntriesDialog(+ BuildContext context,+ List<String> skippedEntries,+) async {+ final l10n = context.l10n;+ final String entriesList = skippedEntries.join('\n');+ await showDialogWidget(+ context: context,+ title: l10n.andOTPSkippedEntriesTitle(skippedEntries.length),+ body: '$entriesList\n\n${l10n.andOTPSkippedEntriesReason}',+ buttons: [+ ButtonWidget(+ buttonType: ButtonType.primary,+ labelText: l10n.ok,+ isInAlert: true,+ buttonSize: ButtonSize.large,+ buttonAction: ButtonAction.first,+ ),+ ],+ );+}diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dartindex ee5cd7eb68..3656569c12 100644--- a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart@@ -1,4 +1,5 @@import 'package:ente_auth/ui/settings/data/import/aegis_import.dart';+import 'package:ente_auth/ui/settings/data/import/andotp_import.dart';import 'package:ente_auth/ui/settings/data/import/bitwarden_import.dart';import 'package:ente_auth/ui/settings/data/import/encrypted_ente_import.dart';import 'package:ente_auth/ui/settings/data/import/google_auth_import.dart';@@ -47,6 +48,9 @@ class ImportService {case ImportType.proton:await showProtonImportInstruction(context);break;+ case ImportType.andOTP:+ await showAndOTPImportInstruction(context);+ break;}}}diff --git a/mobile/apps/auth/lib/ui/settings/data/import_page.dart b/mobile/apps/auth/lib/ui/settings/data/import_page.dartindex 031b61bd8f..8309d59e3d 100644--- a/mobile/apps/auth/lib/ui/settings/data/import_page.dart+++ b/mobile/apps/auth/lib/ui/settings/data/import_page.dart@@ -19,6 +19,7 @@ enum ImportType {bitwarden,lastpass,proton,+ andOTP,}class ImportCodePage extends StatelessWidget {@@ -29,6 +30,7 @@ class ImportCodePage extends StatelessWidget {ImportType.encrypted,ImportType.twoFas,ImportType.aegis,+ ImportType.andOTP,ImportType.bitwarden,ImportType.googleAuthenticator,ImportType.proton,@@ -56,6 +58,8 @@ class ImportCodePage extends StatelessWidget {return 'LastPass Authenticator';case ImportType.proton:return 'Proton Authenticator';+ case ImportType.andOTP:+ return 'andOTP';}}