π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add OTP Auth import support
Neeraj Gupta10408ea392f9
diff --git a/mobile/apps/auth/lib/l10n/arb/app_en.arb b/mobile/apps/auth/lib/l10n/arb/app_en.arbindex 3caef0cee2..30e3f39ff5 100644--- a/mobile/apps/auth/lib/l10n/arb/app_en.arb+++ b/mobile/apps/auth/lib/l10n/arb/app_en.arb@@ -124,6 +124,7 @@"import2FasGuide": "Use the \"Settings->Backup -Export\" option in 2FAS.\n\nIf your backup is encrypted, you will need to enter the password to decrypt the backup","importLastpassGuide": "Use the \"Transfer accounts\" option within Lastpass Authenticator Settings and press \"Export accounts to file\". Import the JSON downloaded.","importProtonAuthGuide": "Use the \"Export\" option in Proton Authenticator Settings to export your codes.\n\nIf your export is password protected, you will need to enter the password to decrypt it.",+ "importOtpAuthGuide": "Export an encrypted backup from OTP Auth, then select the .otpauthdb or .otpauthdp file. Single-account .otpauth exports are also supported.","invalidProtonExportTitle": "Invalid Proton export","invalidProtonExportMessage": "The selected file is not a valid Proton Authenticator export.","exportCodes": "Export codes",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 8f411eb41f..a737e5ff95 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@@ -4,6 +4,7 @@ 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';import 'package:ente_auth/ui/settings/data/import/lastpass_import.dart';+import 'package:ente_auth/ui/settings/data/import/otp_auth_import.dart';import 'package:ente_auth/ui/settings/data/import/plain_text_import.dart';import 'package:ente_auth/ui/settings/data/import/proton_import.dart';import 'package:ente_auth/ui/settings/data/import/raivo_plain_text_import.dart';@@ -49,6 +50,9 @@ class ImportService {case ImportType.andOTP:await showAndOTPImportInstruction(context);return false;+ case ImportType.otpAuth:+ await showOtpAuthImportInstruction(context);+ return false;}}}diff --git a/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import.dartnew file mode 100644index 0000000000..aed417d5e2--- /dev/null+++ b/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import.dart@@ -0,0 +1,93 @@+import 'package:ente_auth/l10n/l10n.dart';+import 'package:ente_auth/models/code.dart';+import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';+import 'package:ente_auth/ui/settings/data/import/otp_auth_import_parser.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/foundation.dart';+import 'package:flutter/material.dart';+import 'package:logging/logging.dart';++final _logger = Logger('OtpAuthImport');++Future<void> showOtpAuthImportInstruction(BuildContext context) async {+ final l10n = context.l10n;+ await showFileImportInstruction(+ context: context,+ title: 'OTP Auth',+ body: l10n.importOtpAuthGuide,+ actionLabel: l10n.importSelectAppExport('OTP Auth'),+ semanticsIdentifier: 'auth_import_instruction_otp_auth',+ onImport: () => _pickOtpAuthFile(context),+ );+}++Future<void> _pickOtpAuthFile(BuildContext context) async {+ await pickAndProcessImportFile(+ context: context,+ dialogTitle: context.l10n.importSelectAppExport('OTP Auth'),+ type: FileType.custom,+ allowedExtensions: ['otpauthdb', 'otpauthdp', 'otpauth'],+ showProgressBeforeProcessing: false,+ logger: _logger,+ logMessage: 'Exception while processing OTP Auth import',+ process: (path, progressDialog) =>+ _processOtpAuthFile(context, path, progressDialog),+ );+}++Future<int?> _processOtpAuthFile(+ BuildContext context,+ String path,+ ProgressDialog dialog,+) async {+ final fileBytes = await readPickedImportFileAsBytes(path);+ if (!context.mounted) return null;+ final l10n = context.l10n;+ while (true) {+ if (!context.mounted) return null;+ final password = await promptForImportPassword(+ context,+ title: l10n.passwordForDecryptingExport,+ );+ if (password == null) return null;++ await dialog.show();+ final result = await compute(_parseOtpAuthExport, {+ 'fileBytes': fileBytes,+ 'password': password,+ });+ if (result['status'] == 'incorrect_password') {+ await dialog.hide();+ if (!context.mounted) return null;+ await showErrorDialog(+ context,+ l10n.incorrectPasswordTitle,+ l10n.pleaseCheckPasswordAndTryAgain,+ );+ continue;+ }++ final codes = (result['otpUris'] as List).cast<String>().map(+ Code.fromOTPAuthUrl,+ );+ return saveImportedCodes(codes);+ }+}++Map<String, Object> _parseOtpAuthExport(Map<String, Object> params) {+ try {+ final codes = parseOtpAuthExport(+ params['fileBytes'] as Uint8List,+ password: params['password'] as String,+ );+ return {+ 'status': 'ok',+ 'otpUris': codes.map((code) => code.rawData).toList(),+ };+ } on IncorrectOtpAuthPasswordException {+ return {'status': 'incorrect_password'};+ }+}diff --git a/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import_parser.dartnew file mode 100644index 0000000000..e87b33d7e8--- /dev/null+++ b/mobile/apps/auth/lib/ui/settings/data/import/otp_auth_import_parser.dart@@ -0,0 +1,511 @@+import 'dart:convert';+import 'dart:typed_data';++import 'package:base32/base32.dart';+import 'package:ente_auth/models/code.dart';+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';+import 'package:logging/logging.dart';+import 'package:pointycastle/export.dart' hide Algorithm;++final _logger = Logger('OtpAuthImportParser');++class IncorrectOtpAuthPasswordException implements Exception {+ const IncorrectOtpAuthPasswordException();+}++List<Code> parseOtpAuthExport(Uint8List fileBytes, {required String password}) {+ final outer = _decryptOuterArchive(fileBytes);+ final isBackup = outer.containsKey('WrappedData');+ final encryptedData = _bytes(outer[isBackup ? 'WrappedData' : 'Data']);+ final version = (outer['Version'] as num?)?.toDouble();+ final isLegacy =+ (isBackup && version == 1.0) || (!isBackup && version == 1.1);++ late final Uint8List decryptedData;+ if (isLegacy) {+ try {+ final ivSource = isBackup+ ? utf8.encode(outer['IV'] as String)+ : _bytes(outer['IV']);+ final key = _sha256(utf8.encode('${outer['Salt']}-$password'));+ decryptedData = _decryptAesCbc(+ encryptedData,+ key,+ _sha1(ivSource).sublist(0, 16),+ );+ } catch (_) {+ throw const IncorrectOtpAuthPasswordException();+ }+ } else if ((isBackup && version == 1.1) || (!isBackup && version == 1.2)) {+ decryptedData = _decryptRncCryptor(encryptedData, password);+ } else {+ throw FormatException('Unsupported OTP Auth export version: $version');+ }++ late final Map<String, Object?> root;+ try {+ root = _asMap(_unarchive(decryptedData));+ } catch (_) {+ if (isLegacy) throw const IncorrectOtpAuthPasswordException();+ rethrow;+ }+ final accounts = isBackup ? _backupAccounts(root) : [root];+ final codes = <Code>[];+ for (final account in accounts) {+ try {+ codes.add(_accountToCode(_asMap(account)));+ } catch (error, stackTrace) {+ _logger.warning('Skipping unsupported OTP Auth entry', error, stackTrace);+ }+ }+ return codes;+}++Map<String, Object?> _decryptOuterArchive(Uint8List fileBytes) {+ for (final magic in ['Authenticator', 'OTPAuth']) {+ try {+ final decrypted = _decryptAesCbc(+ fileBytes,+ _sha256(utf8.encode(magic)),+ Uint8List(16),+ );+ final archive = _asMap(_unarchive(decrypted));+ if (archive.containsKey('WrappedData') || archive.containsKey('Data')) {+ return archive;+ }+ } catch (_) {}+ }+ throw const FormatException('Invalid OTP Auth export');+}++List<Object?> _backupAccounts(Map<String, Object?> root) {+ final folders = root['Folders'];+ if (folders is! List) {+ throw const FormatException('Invalid OTP Auth backup');+ }+ return [+ for (final folder in folders)+ ...(_asMap(folder)['accounts'] as List? ?? const []),+ ];+}++Code _accountToCode(Map<String, Object?> account) {+ final type = switch (account['type']) {+ 1 => Type.hotp,+ 2 => Type.totp,+ _ => throw const FormatException('Unsupported OTP type'),+ };+ final algorithm = switch (account['algorithm']) {+ 0 || 1 => Algorithm.sha1,+ 2 => Algorithm.sha256,+ 3 => Algorithm.sha512,+ _ => throw const FormatException('Unsupported OTP algorithm'),+ };+ final issuer = account['issuer'] as String;+ final label = account['label'] as String;+ final secret = base32.encode(_bytes(account['secret'])).replaceAll('=', '');+ final digits = (account['digits'] as int?) ?? 0;+ final period = (account['period'] as int?) ?? 0;+ final counter = (account['counter'] as int?) ?? 0;++ return Code.fromOTPAuthUrl(+ buildImportOtpUri(+ kind: type.name,+ issuer: Uri.encodeComponent(issuer),+ account: Uri.encodeComponent(label),+ secret: secret,+ algorithm: algorithm.name.toUpperCase(),+ digits: digits == 0 ? Code.defaultDigits : digits,+ period: period == 0 ? Code.defaultPeriod : period,+ counter: counter,+ ),+ );+}++Uint8List _decryptRncCryptor(Uint8List data, String password) {+ const headerLength = 34;+ const hmacLength = 32;+ if (data.length < headerLength + 16 + hmacLength ||+ data[0] != 3 ||+ data[1] != 1) {+ throw const FormatException('Invalid OTP Auth encryption');+ }++ final encryptionKey = _deriveRncCryptorKey(password, data.sublist(2, 10));+ final hmacKey = _deriveRncCryptorKey(password, data.sublist(10, 18));+ final authenticatedData = data.sublist(0, data.length - hmacLength);+ final expectedHmac = data.sublist(data.length - hmacLength);+ final actualHmac = (HMac(+ SHA256Digest(),+ 64,+ )..init(KeyParameter(hmacKey))).process(authenticatedData);+ if (!_constantTimeEquals(actualHmac, expectedHmac)) {+ throw const IncorrectOtpAuthPasswordException();+ }++ return _decryptAesCbc(+ data.sublist(headerLength, data.length - hmacLength),+ encryptionKey,+ data.sublist(18, headerLength),+ );+}++Uint8List _deriveRncCryptorKey(String password, Uint8List salt) {+ final derivator = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64))+ ..init(Pbkdf2Parameters(salt, 10000, 32));+ final key = Uint8List(32);+ derivator.deriveKey(Uint8List.fromList(utf8.encode(password)), 0, key, 0);+ return key;+}++Uint8List _decryptAesCbc(Uint8List data, Uint8List key, Uint8List iv) {+ if (data.isEmpty || data.length % 16 != 0) {+ throw const FormatException('Invalid encrypted data');+ }+ final cipher = CBCBlockCipher(AESEngine())+ ..init(false, ParametersWithIV(KeyParameter(key), iv));+ final decrypted = Uint8List(data.length);+ for (var offset = 0; offset < data.length; offset += cipher.blockSize) {+ cipher.processBlock(data, offset, decrypted, offset);+ }++ final padding = decrypted.last;+ if (padding == 0 ||+ padding > cipher.blockSize ||+ decrypted+ .sublist(decrypted.length - padding)+ .any((value) => value != padding)) {+ throw const FormatException('Invalid encrypted data padding');+ }+ return decrypted.sublist(0, decrypted.length - padding);+}++Uint8List _sha1(List<int> data) =>+ SHA1Digest().process(Uint8List.fromList(data));++Uint8List _sha256(List<int> data) =>+ SHA256Digest().process(Uint8List.fromList(data));++bool _constantTimeEquals(Uint8List first, Uint8List second) {+ if (first.length != second.length) return false;+ var difference = 0;+ for (var index = 0; index < first.length; index++) {+ difference |= first[index] ^ second[index];+ }+ return difference == 0;+}++Object? _unarchive(Uint8List data) {+ return _KeyedArchive(_asMap(_BinaryPlistReader(data).parse())).root;+}++class _KeyedArchive {+ late final List<Object?> _objects;+ final _cache = <int, Object?>{};+ final _resolving = <int>{};+ final Map<String, Object?> archive;++ _KeyedArchive(this.archive) {+ if (archive[r'$archiver'] != 'NSKeyedArchiver' ||+ archive[r'$objects'] is! List) {+ throw const FormatException('Invalid keyed archive');+ }+ _objects = List<Object?>.from(archive[r'$objects'] as List);+ }++ Object? get root {+ final top = _asMap(archive[r'$top']);+ return _resolve(top['root']);+ }++ Object? _resolve(Object? value) {+ if (value is _PlistUid) return _resolveUid(value.value);+ if (value is Uint8List) return value;+ if (value is List) return value.map(_resolve).toList();+ if (value is Map) {+ return {+ for (final entry in value.entries)+ entry.key.toString(): _resolve(entry.value),+ };+ }+ return value;+ }++ Object? _resolveUid(int index) {+ if (index == 0) return null;+ if (index < 0 || index >= _objects.length || !_resolving.add(index)) {+ throw const FormatException('Invalid keyed archive reference');+ }+ if (_cache.containsKey(index)) {+ _resolving.remove(index);+ return _cache[index];+ }++ try {+ final raw = _objects[index];+ if (raw is! Map) {+ return _cache[index] = _resolve(raw);+ }+ final classUid = raw[r'$class'];+ if (classUid is! _PlistUid) {+ throw const FormatException('Missing keyed archive class');+ }+ final classMetadata = _asMap(_objects[classUid.value]);+ final className = classMetadata[r'$classname'];+ final result = switch (className) {+ 'NSDictionary' || 'NSMutableDictionary' => _resolveDictionary(raw),+ 'NSArray' ||+ 'NSMutableArray' ||+ 'NSSet' ||+ 'NSMutableSet' => _resolve(raw['NS.objects']),+ 'NSData' ||+ 'NSMutableData' => _bytes(_resolve(raw['NS.data'] ?? raw['NS.bytes'])),+ 'NSString' || 'NSMutableString' => _resolve(raw['NS.string']),+ 'NSDate' => _resolve(raw['NS.time']),+ 'ACOTPAccount' || 'ACOTPFolder' => {+ for (final entry in raw.entries)+ if (entry.key != r'$class')+ entry.key.toString(): _resolve(entry.value),+ },+ _ => throw FormatException(+ 'Unsupported keyed archive class: $className',+ ),+ };+ _cache[index] = result;+ return result;+ } finally {+ _resolving.remove(index);+ }+ }++ Map<String, Object?> _resolveDictionary(Map raw) {+ final keys = _resolve(raw['NS.keys']) as List;+ final values = _resolve(raw['NS.objects']) as List;+ if (keys.length != values.length) {+ throw const FormatException('Invalid keyed archive dictionary');+ }+ return {+ for (var index = 0; index < keys.length; index++)+ keys[index] as String: values[index],+ };+ }+}++Map<String, Object?> _asMap(Object? value) {+ if (value is! Map) throw const FormatException('Expected a dictionary');+ return {for (final entry in value.entries) entry.key.toString(): entry.value};+}++Uint8List _bytes(Object? value) {+ if (value is Uint8List) return value;+ if (value is List<int>) return Uint8List.fromList(value);+ throw const FormatException('Expected binary data');+}++class _PlistUid {+ final int value;++ const _PlistUid(this.value);+}++class _Length {+ final int count;+ final int offset;++ const _Length(this.count, this.offset);+}++class _BinaryPlistReader {+ static const _header = [0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30];++ final Uint8List _data;+ late final ByteData _bytes;+ late final int _objectRefSize;+ late final List<int> _offsets;+ final _cache = <int, Object?>{};+ final _reading = <int>{};++ _BinaryPlistReader(this._data);++ Object? parse() {+ _bytes = ByteData.sublistView(_data);+ if (_data.length < _header.length + 32 ||+ !_header.indexed.every((entry) => _data[entry.$1] == entry.$2)) {+ throw const FormatException('Invalid binary plist');+ }++ final trailerOffset = _data.length - 32;+ final offsetSize = _readByte(trailerOffset + 6);+ _objectRefSize = _readByte(trailerOffset + 7);+ final objectCount = _readUInt(trailerOffset + 8, 8);+ final rootObject = _readUInt(trailerOffset + 16, 8);+ final offsetTableOffset = _readUInt(trailerOffset + 24, 8);++ if (offsetSize < 1 ||+ offsetSize > 8 ||+ _objectRefSize < 1 ||+ _objectRefSize > 8 ||+ objectCount < 1 ||+ objectCount > _data.length ||+ rootObject >= objectCount ||+ offsetTableOffset < _header.length ||+ offsetTableOffset >= trailerOffset ||+ offsetTableOffset + (objectCount * offsetSize) > trailerOffset) {+ throw const FormatException('Invalid binary plist trailer');+ }++ _offsets = List.generate(+ objectCount,+ (index) =>+ _readUInt(offsetTableOffset + (index * offsetSize), offsetSize),+ );+ if (_offsets.any(+ (offset) => offset < _header.length || offset >= offsetTableOffset,+ )) {+ throw const FormatException('Invalid binary plist offset table');+ }++ return _readObject(rootObject);+ }++ Object? _readObject(int objectId) {+ if (objectId < 0 || objectId >= _offsets.length) {+ throw const FormatException('Invalid binary plist reference');+ }+ if (_cache.containsKey(objectId)) return _cache[objectId];+ if (!_reading.add(objectId)) {+ throw const FormatException('Recursive binary plist reference');+ }++ try {+ final offset = _offsets[objectId];+ final marker = _readByte(offset);+ final type = marker >> 4;+ final info = marker & 0x0F;+ final result = switch (type) {+ 0x0 => _readSimple(info),+ 0x1 => _readUInt(offset + 1, _intSize(info)),+ 0x2 => _readReal(offset + 1, _intSize(info)),+ 0x4 => _readData(offset, info),+ 0x5 => _readAscii(offset, info),+ 0x6 => _readUtf16(offset, info),+ 0x8 => _PlistUid(_readUInt(offset + 1, info + 1)),+ 0xA => _readArray(offset, info),+ 0xD => _readDictionary(offset, info),+ _ => throw FormatException('Unsupported binary plist type: $type'),+ };+ _cache[objectId] = result;+ return result;+ } finally {+ _reading.remove(objectId);+ }+ }++ Object? _readSimple(int info) {+ return switch (info) {+ 0x0 => null,+ 0x8 => false,+ 0x9 => true,+ _ => throw FormatException('Unsupported binary plist value: $info'),+ };+ }++ double _readReal(int offset, int length) {+ _checkRange(offset, length);+ return switch (length) {+ 4 => _bytes.getFloat32(offset, Endian.big),+ 8 => _bytes.getFloat64(offset, Endian.big),+ _ => throw FormatException('Unsupported binary plist real size: $length'),+ };+ }++ Uint8List _readData(int offset, int info) {+ final length = _readLength(offset, info);+ _checkRange(length.offset, length.count);+ return _data.sublist(length.offset, length.offset + length.count);+ }++ String _readAscii(int offset, int info) {+ final length = _readLength(offset, info);+ _checkRange(length.offset, length.count);+ return ascii.decode(+ _data.sublist(length.offset, length.offset + length.count),+ );+ }++ String _readUtf16(int offset, int info) {+ final length = _readLength(offset, info);+ final byteLength = length.count * 2;+ _checkRange(length.offset, byteLength);+ final buffer = StringBuffer();+ for (var index = 0; index < byteLength; index += 2) {+ buffer.writeCharCode(_bytes.getUint16(length.offset + index, Endian.big));+ }+ return buffer.toString();+ }++ List<Object?> _readArray(int offset, int info) {+ final length = _readLength(offset, info);+ _checkRange(length.offset, length.count * _objectRefSize);+ return [+ for (var index = 0; index < length.count; index++)+ _readObject(+ _readUInt(length.offset + (index * _objectRefSize), _objectRefSize),+ ),+ ];+ }++ Map<String, Object?> _readDictionary(int offset, int info) {+ final length = _readLength(offset, info);+ final valuesOffset = length.offset + (length.count * _objectRefSize);+ _checkRange(length.offset, length.count * _objectRefSize * 2);+ return {+ for (var index = 0; index < length.count; index++)+ _readObject(+ _readUInt(+ length.offset + (index * _objectRefSize),+ _objectRefSize,+ ),+ )+ as String: _readObject(+ _readUInt(valuesOffset + (index * _objectRefSize), _objectRefSize),+ ),+ };+ }++ _Length _readLength(int offset, int info) {+ if (info < 0xF) return _Length(info, offset + 1);++ final marker = _readByte(offset + 1);+ if (marker >> 4 != 0x1) {+ throw const FormatException('Invalid binary plist length');+ }+ final intSize = _intSize(marker & 0x0F);+ return _Length(_readUInt(offset + 2, intSize), offset + 2 + intSize);+ }++ int _intSize(int info) {+ if (info > 3) throw const FormatException('Unsupported binary plist size');+ return 1 << info;+ }++ int _readByte(int offset) {+ _checkRange(offset, 1);+ return _data[offset];+ }++ int _readUInt(int offset, int length) {+ _checkRange(offset, length);+ var value = 0;+ for (var index = 0; index < length; index++) {+ value = (value << 8) | _data[offset + index];+ }+ return value;+ }++ void _checkRange(int offset, int length) {+ if (offset < 0 || length < 0 || offset + length > _data.length) {+ throw const FormatException('Truncated binary plist');+ }+ }+}diff --git a/mobile/apps/auth/lib/ui/settings/data/import_page.dart b/mobile/apps/auth/lib/ui/settings/data/import_page.dartindex b2a62437d3..514d1076b8 100644--- a/mobile/apps/auth/lib/ui/settings/data/import_page.dart+++ b/mobile/apps/auth/lib/ui/settings/data/import_page.dart@@ -16,6 +16,7 @@ enum ImportType {lastpass,proton,andOTP,+ otpAuth,}class ImportCodePage extends StatelessWidget {@@ -32,6 +33,7 @@ class ImportCodePage extends StatelessWidget {ImportType.proton,ImportType.ravio,ImportType.lastpass,+ ImportType.otpAuth,];String getTitle(BuildContext context, ImportType type) {@@ -56,6 +58,8 @@ class ImportCodePage extends StatelessWidget {return 'Proton Authenticator';case ImportType.andOTP:return 'andOTP';+ case ImportType.otpAuth:+ return 'OTP Auth';}}diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.1.otpauth.b64 b/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.1.otpauth.b64new file mode 100644index 0000000000..cc3e6273bf--- /dev/null+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.1.otpauth.b64@@ -0,0 +1 @@+vPpZTR551tpxtoXMHnZRn5nFYZTxgBCQCTYPb6P6s38y3U0ZkO6ofRox5zcU/uopjnscDzmuducJSJYggakxQZ1LhQ2ViFLTd8I7LQnvKRB+65caEicMVi0WNmMo+/4j2dMpDff+O8m75p/lM60tfktIS2DPE1d8hHkgnC34eVpH2wi00WY7ZxnUUkTzoa2gn7HiUGTA7vMeTa0im5unpRoA3cEt2yE4yLwgKEazA8IJ0uicEePsiZQJleGTH7KPSGn4sGQdvqfhCn6ddwlXXPXX04QnwMSek/38I2i27JMURgc6jJVqfei3OtssKSXY4dYCapuC1X/nLpCWfYRF+Zef0RdeuBLEH5rjP4ME+iNhO4aTX30JnSC1PLoX9Z/AR7Yvrv5IFGF3hxESucmgJiCDdyMC5iDGR2+/eVVQdUV43gJvvMr9C6HmC3S+4CsSwteSpje22kUFkUVP862siSVPZA145XWsSmcbC95Gx4UNmidvxzzS3ToxafwsYz+xqJ8w2+a6JVOR+Z1pZN6Ap7QV4r4uzGlkkIbX1+k6zPCqR0E6SYQFOtsmK4dS1Zk0PuTeP7cW1350w/VJ1Al6VmmScGkSROg9pLhD0bgpk+0sv3fpC3gD1JCf9DzdrtZhb5Vt3d1E1RIy50yRBaExqShZt/1DbFYV6WmOBwZ1zJAz0+Rg0Lge+dup05qncRjM85au+mSAqk97iPv+ro2fTrhF0FWAn0agd09xnp+Er+X5RtkXX8kRGOBjfWE7gJuKNEKrM9XwfkPnoqa90rGEWM3Sc7LEE72tQvtuBti9gofj3OMV+t0rOEllPlaFsUxcM1WAuwVg7hkyAErlpXD8o9sTrxwUWWPue8fKn0upd+mJ4SryEeiqzbLbSWFnggSwJMLt8IrZFYkRp8sDq0EuQvVDJxrExkrIICNUm1EyuRlOfbT/+XMTkWqMTdYjmu9dcYPZnIj78uihw0pUPU/ZIJL8uC/gl4BhgM69GYQoymuVX5WcrxSjtVuLKVu+utugS352Xh03UqOTrc2+ebHiBzEfKtm4qXUq3uvzafTtTIBQsqjYd/VLQu9lHi882CUnrk11RATZ+d88aig6bbZj94peoVXmCmozEXvLvC+NsFO5iT9pbUVwgjokYlVP+xfcdiff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.2.otpauth.b64 b/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.2.otpauth.b64new file mode 100644index 0000000000..6e0dd56bd5--- /dev/null+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/account-1.2.otpauth.b64@@ -0,0 +1 @@+6B7TbRpKxBWAbgx6gC0LqXP4tdaJkmiRWyWKVdD/3Xj+Z/kskrD6oDZQvTY+LeExaYRbrfJQ6mLazdgRRGPLb5WUVOaDbNYrm2+1qtOy7TSMXitIZdmeklPhKH/AbGIXmdnfaPV3NOUj4M9csMYta+gkV4XAF3aydaHGY7emAAUoQbZSpHQdd4xIZqampyNXsJpA1aTk/x7Z6lE882RbjbjNvHCP8HZV7pld4/3Y1xpQ8qYiYxBgkipceSfYN/NFnkilr1PE8+ftzwlqa2i/4DBwN7aJqWpfqfhcPjjCnNkKJ+21WQEFtuKen0mzcWoCtvx8ISrcfD7cSPRCY/9hXVMPy6MRu+Yis3z1qk0gIqeuIfQxZid1OqHtyf3BKyXB4R2Htu+TMWZEC6NP8wCiQ3zKWAGQz9BewxXT8uHYm/Gdwqb+ASrvFfLrFGIFidPLsGh7OKzDhx/B7YT5cymT3nZjk41cHJyRl7qn1kpVQXp3CU5WCNiOUsRrVx6W1BGgtiVshikjGTT8L/NKWIXkcc5+xQO6j67/tP+DD8S7rDGpUhUmuMqpgOapT51ZaLHMDUp3ZKsUH+P9ieA+jmCbL+81/gmID5uEkALuYITdkb7dGMtTiktG2ht/tc7ae9sUdTpyhJmhLmaqFu2C60lbm+PORUCAGSFmy0SIve7141d7GI5B4QrAl0aXwBE/BukdBe2/PuqA+PyV4AFwFBbkMjpgQVoWpITC3SW/hJUqq6byrQULOfCccqPNcQiCSguSaPqYMV7TmUJrMblIpGMaSSopiCfaksLOkwL4VK+mCkqiAzEz9zUclyVWgEJcKzrzJUaE0z6g9wClfejo1EEun4Iut3mdW27W+L6zmtGLVFzmdX7XZUby/7+61wEexQLllkKMJ/fjor/ZVpGth2Wm+9V37peJ2HealCT/0XYvVElixwid1nzSRs8ZNvOmmSXe8XOLXKRMYyy/ntE1P9BNHrbfGmUmhSH6YVK7l5BzReUETnZHgDFzZ7K0A4MTSWFhC5CRQKUXR0G15ZsY1fXHNE9hoZgLnxcB6Kzyt+M5JD5ZmTPHLgubusFUDGdLSczN0vGtscJNzUInOI+aCDexNVleEdyQ9kgTMa0Ug4AQInwFqQqYko+LBecsPeFmGCwNdiff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.0.otpauthdb.b64 b/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.0.otpauthdb.b64new file mode 100644index 0000000000..1d05a0ba62--- /dev/null+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.0.otpauthdb.b64@@ -0,0 +1 @@+WlczAK6JaEq0M0qfB5XzwTAMzMcc2lwoHJeUz33MSemJoleIQgh7RTeN7LzSv8m3bDt0RmpkLy7fAa0P3nevT7w2VTbmGrPZu0lPjShFuCc7+Z4U88qGcffzDRzJxlsnHnk5nN1NITxthny1UoulJEJiBgptM9IWUO2U7uRCLUu2CIWYeKboCiL/zVHQrrKxc+uiPDTHreWu1iVx7lVuzo0j4LEr6msqaZyHELW3ZRCUtJTuWisYUcRTjjKjn0OKXnjrd6a4dN/yAwOmkmf9Y1BS6ZzP6ypBlqOJmoxdyCXUMGZAlESlBOZnUaOMBHtphJ8YQEXr2T7VsuBVxb1RStu35HNbkes/4k94sWjB1S+ZKAVe25P5iw5YX6dUxhPhow1+BgiCIAw62ZlyL+J0jUX/j+544wqDlndFqh96i95TSZ66jBS0m5ncxbDszaCJDw/8ikG9x1s50dcl89Sp4upMR/PVpx/nzhabUeook987qw//Bs+xMbuD4CJkI6JmQdKxzHPC+RWxOMPlYL2W1OteqTkTpkLlGF1ko2GiMeuMTEWggXDvdvz9GP3FUntf4LVzyFtHIWPNKEvsIqAZAzRXPaWDBgp+hhmNqQp6OARTpyzCj0G0BKn1SEl6L1TlhPuWpM72wbMG4NFltGoTA/vuVQ7E/JKt8gILilDE9sB+GQ21r1LAou8Ce8jDAo55WoNC5FuzJ68I7l2SJOWHVbMazrbLh+Hq79vVVsF7lEn/4T/y636xae4QkYTRV6lL6VaaiSqnm8rOSkJUZt5uQV6MhvgwLItGYa/TQVjC6eQwo/W7F2v8QJpPearOaq0Zdj4cZk6+7LEG4H5GUXGDxpF0MZl3yBChUDK7MHfw6UQbAGP04fil1zEC9u8qcyWE4jYjf9RvPIxEn44lGJ0dNK6giKCnsW7TDeaFUMBMM9U3APewCgKz06MlwrjXGn3Cwfj+jm9jXP3Sa7L5G5FVLaT68bl5A0QnhU2PCqzhYknR8gHAM4gWZcphXiQk7QW+s+xdtph4h0lZif6WE1NDsFWjWT2i7DSXi+/yCfagoNMl/Qa5Z+KdgPXtNgJiVHpQZAmt8ZEs3SFwuVYU+FdP5ZAzL1Adb9mREBx0k3iXKRfKidxJYan8TQsQYC4IblrB1bHHiWMNcTZiIBjWKbudKgwllMUPYra58kmCw9Yxtm14E87bpB3Lf1cfFq+KexnWp5uPCDIwcfoUySSwDkEN20KfStpRBu70YrDD3GsGQJaMDQOq7SZ7RpCW0b0JWYfOjDKOm0nqVDddcyqKwha+4hrZVYW3N90WM7uJNsMxJ5Xvd30T0PkypzNhrpubLLR+w7O8DsK/mhWdfXCVdVAvLqM7bORUOOEpm5vFZZGczWsLfH46XJj40QawOP45HYvebS0kLuHGAyToIi6XYWaB7sXgCKKa0P+wX/gY/VhTx5odCfVgTPfZJlqK3Oyh9fCLOBKtUKh5dlaykMv4M/QS361J/NsuhkKcjhSPuch8THjM/fLkF6AoqX38Mw4xhYgFWbxMUTKENBN5tVsh5f3Xw+KVvrEb4FViLE3GXyMdl1M=diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.1.otpauthdb.b64 b/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.1.otpauthdb.b64new file mode 100644index 0000000000..3de7200057--- /dev/null+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/backup-1.1.otpauthdb.b64@@ -0,0 +1 @@+0JFoxrF9x6Mf5243XHhzyjZmFoJKcvaRc/PnYb4G2lcWMyPXEmuoC0fIzQlYH1mOIqyc8DsZaorw2P8xIunZVtzREC3xm+A4fvXiaqZIAdPtIf0hXUxi9xdGTXVrlEzlfVQksCiQA0lKfi3X8YNIAQp3f5R5qRWMj5C1mrNhO5t2Ax9cj6+LK+Md66uynCEBD6Nd30pcfrU6e+NrjlcnyUKDts0QXwoJv/1U3gCniUOx/NGKOhfHiTQET3hGfoKR4cqDaYNNNXj29IDqAGAfsSehSxhjvBCgb/dSMNsFxl3rGmR9yvsw2xkFOZjP1nYpZX8KKlsR9dS3DFiPanvNEdZ/m0JJRF/h5meWnuK3mLOE0H0G4PD6nvhx0LJINZsZtuGKJ4egOBClBlR4NfXZsqGW3IzbaUkyDNSxMhK8LzMtOdUy2lXkeSl+enQZFPFXNlY3KYXSDx8cbLw6baw+8yg2QQCu9PBaUhVmM4JDDYWQzJzWMMACnhJ07kH7nZ09+p8SKuRkqbmcaEMNQp/dSAHdvGWQkzqHLB9TShPtNtAafrm1BaG4GbL0J7F/+Y4BMJY25xe+bc/P0aPKw6W5e2d+DAjVgrjpNmFf4xDGtYF7xkh91YqwiK0iV8C/Mp6UG3OK7uQNIWNXPWHle1CWGxIdXSDCJQHgneTFq5Vik9RbHyIqCyzoMOw/bgdBi+UPmLKeURz/BTc5voks/wJX8XGmEZ8I3hj7NILCgkPCMEBfuyUgbh2U1eWrXDFgEqE2hBSVv48tl3dU/aq1/fXR76q/j9F876qRJ02H7GuDL5ZY5iox3UY2MbFbrtO6wAZaPW91io4B+bQCMpJJxoTV3OIOvtHxPfqcOz9qEOzGShYjJ/BssWZYwyb7pLOoORbeNrP7B4ZF1JVjB6AKN9P69j7oVmSlca6l78wYOMcZ3kpgPUxVBNfu2jkUA8naY3dtwqMwgF8S/Y9z1/nnoUZCFkW8evltG86YdCseeLIXEAHs7PRNjTXMmJwGICkX+az1NY4pPX6+nNI1FHmi3WC+pSNJhs8fCQa+H/awxh/0V9ITiR6zKBHt2dRpN/ZsB/Pq/VUB9EQK2ybnMkIrGwsXFneFAouBEeOTjZJ+/20Nv2jp3GDlIDx8xnwRpIil2uIF6wpcUt1ExuwZHzIAAyNACdYF4avxllsteUAxLQ2ymXOmFk71drV+LvnTsxgvEYVs2Qbt3mFvk0nkOBnF3iwlEWm02OaIxClAzq8fS3AUBYVO3u23AVkWTkKJbmI7sdV1XQjkiZusjioIH935vH1No6DDJ95OT5wA0X+xnfhhcyG8OmFgKkWAXnfbC2wo4jA3xE79mv7PP7aONV5IAchzHDuT7q90rfU01MbYV/ygKsBVdqVHNZRSiv/fYahNjmK6X/Y2EK/wSKCmLLRXOcPGrlRetICVFWnxq1pHvL/yjq7hWgM/UfrvCKB5NTxka4V/5fVwyvfdSqzsy4mZaUw1DhPhbrLBlIfafMR+AupWaUetc7gbT5pGuFxpDnSg7HUFhTtp9fZjOziNb6nX9b8oqQ==diff --git a/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart b/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dartindex f19ff4bc5e..13e37ba9e0 100644--- a/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart+++ b/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart@@ -21,6 +21,7 @@ void main() {expect(find.byType(MenuGroupComponent), findsOneWidget);expect(find.text('Plain text'), findsOneWidget);expect(find.text('Ente Encrypted export'), findsOneWidget);+ expect(find.text('OTP Auth'), findsOneWidget);expect(find.byWidgetPredicate((widget) =>diff --git a/mobile/apps/auth/test/ui/settings/data/import/otp_auth_import_parser_test.dart b/mobile/apps/auth/test/ui/settings/data/import/otp_auth_import_parser_test.dartnew file mode 100644index 0000000000..532e3777b7--- /dev/null+++ b/mobile/apps/auth/test/ui/settings/data/import/otp_auth_import_parser_test.dart@@ -0,0 +1,104 @@+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:ente_auth/models/code.dart';+import 'package:ente_auth/ui/settings/data/import/otp_auth_import_parser.dart';+import 'package:flutter_test/flutter_test.dart';++void main() {+ group('OTP Auth import parser', () {+ for (final version in ['1.0', '1.1']) {+ test('decrypts backup version $version', () async {+ final codes = parseOtpAuthExport(+ await _fixture('backup-$version.otpauthdb'),+ password: 'abc123',+ );++ expect(codes, hasLength(2));+ _expectCode(+ codes.first,+ type: Type.totp,+ issuer: 'Example TOTP',+ account: '[email protected]',+ secret: 'MJQWG23VOAWXI33UOAWXGZLDOJSXI',+ );+ _expectCode(+ codes.last,+ type: Type.hotp,+ issuer: 'Example HOTP',+ account: '[email protected]',+ secret: 'MJQWG23VOAWWQ33UOAWXGZLDOJSXI',+ );+ expect(codes.last.counter, 7);+ });+ }++ test('decrypts single-account version 1.1', () async {+ final codes = parseOtpAuthExport(+ await _fixture('account-1.1.otpauth'),+ password: 'abc123',+ );++ expect(codes, hasLength(1));+ _expectCode(+ codes.single,+ type: Type.totp,+ issuer: 'Legacy Account',+ account: '[email protected]',+ secret: 'ONUW4Z3MMUWWYZLHMFRXSLLTMVRXEZLU',+ );+ });++ test('decrypts single-account version 1.2', () async {+ final codes = parseOtpAuthExport(+ await _fixture('account-1.2.otpauth'),+ password: 'abc123',+ );++ expect(codes, hasLength(1));+ _expectCode(+ codes.single,+ type: Type.totp,+ issuer: 'Modern Account',+ account: '[email protected]',+ secret: 'ONUW4Z3MMUWW233EMVZG4LLTMVRXEZLU',+ );+ });++ for (final version in ['1.0', '1.1']) {+ test('rejects an incorrect password for backup version $version', () {+ expect(+ () async => parseOtpAuthExport(+ await _fixture('backup-$version.otpauthdb'),+ password: 'wrong-password',+ ),+ throwsA(isA<IncorrectOtpAuthPasswordException>()),+ );+ });+ }+ });+}++void _expectCode(+ Code code, {+ required Type type,+ required String issuer,+ required String account,+ required String secret,+}) {+ expect(code.type, type);+ expect(code.issuer, issuer);+ expect(code.account, account);+ expect(code.secret, secret);+ expect(code.algorithm, Algorithm.sha1);+ expect(code.digits, Code.defaultDigits);+ expect(code.period, Code.defaultPeriod);+}++Future<Uint8List> _fixture(String name) async {+ final encoded = await File(+ 'test/ui/settings/data/import/fixtures/$name.b64',+ ).readAsString();+ return base64Decode(encoded.replaceAll(RegExp(r'\s'), ''));+}