π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refactor backup service for daily/manual flow
Prateek Sunalc2c9de4ad43f
diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dartindex 4d347199f6..23410dfa21 100644--- a/mobile/apps/auth/lib/services/local_backup_service.dart+++ b/mobile/apps/auth/lib/services/local_backup_service.dart@@ -6,151 +6,86 @@ import 'package:ente_auth/models/export/ente.dart';import 'package:ente_auth/store/code_store.dart';import 'package:ente_crypto_dart/ente_crypto_dart.dart';import 'package:flutter_secure_storage/flutter_secure_storage.dart';-import 'package:intl/intl.dart'; // for time based file naming+import 'package:intl/intl.dart';import 'package:logging/logging.dart';import 'package:saf_stream/saf_stream.dart';import 'package:shared_preferences/shared_preferences.dart';-//we gonn changeclass LocalBackupService {+ LocalBackupService._();+final _logger = Logger('LocalBackupService');- static final LocalBackupService instance =- LocalBackupService._privateConstructor();- LocalBackupService._privateConstructor();+ static final LocalBackupService instance = LocalBackupService._();static const int _maxBackups = 5;static const _lastBackupDayKey = 'lastBackupDay';- // to create an encrypted backup file if the toggle is onFuture<bool> triggerAutomaticBackup({bool isManual = false}) async {- bool success = false;try {final prefs = await SharedPreferences.getInstance();+ if (!_isBackupEnabled(prefs)) return false;+ if (!isManual && _hasBackedUpToday(prefs)) return false;- final isEnabled = prefs.getBool('isAutoBackupEnabled') ?? false;- if (!isEnabled) {- return false;- }-- final backupPath = prefs.getString('autoBackupPath');- final backupTreeUri = prefs.getString('autoBackupTreeUri');- if (backupPath == null && (backupTreeUri == null || backupTreeUri.isEmpty)) {- return false;- }-- if (!isManual && _hasBackedUpToday(prefs)) {- return false;- }+ final _BackupTarget? target = _resolveTarget(prefs);+ if (target == null) return false;- Directory? backupDirectory;- if (backupPath != null && backupPath.isNotEmpty) {- backupDirectory = Directory(backupPath);- await backupDirectory.create(recursive: true);- }-- const storage = FlutterSecureStorage();- final password = await storage.read(key: 'autoBackupPassword');+ final String? password = await _readPassword();if (password == null || password.isEmpty) {- _logger.warning("Automatic backup skipped: password not set.");- return false;- }-- _logger.info("Change detected, triggering automatic encrypted backup...");--- String rawContent = await CodeStore.instance.getCodesForExport();-- List<String> lines = rawContent.split('\n');- List<String> cleanedLines = [];-- for (String line in lines) {- if (line.trim().isEmpty) continue;-- String cleanUrl;- if (line.startsWith('"') && line.endsWith('"')) {- cleanUrl = jsonDecode(line);- }-- else {- cleanUrl = line;- }-- cleanedLines.add(cleanUrl);- }-- final plainTextContent = cleanedLines.join('\n');-- if (plainTextContent.trim().isEmpty) {+ _logger.warning('Automatic backup skipped: password not set.');return false;}- final kekSalt = CryptoUtil.getSaltToDeriveKey();- final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(- utf8.encode(password),- kekSalt,- );-- final encResult = await CryptoUtil.encryptData(- utf8.encode(plainTextContent),- derivedKeyResult.key,- );+ final String? encryptedJson = await _buildEncryptedPayload(password);+ if (encryptedJson == null) return false;- final encContent = CryptoUtil.bin2base64(encResult.encryptedData!);- final encNonce = CryptoUtil.bin2base64(encResult.header!);-- final EnteAuthExport data = EnteAuthExport(- version: 1,- encryptedData: encContent,- encryptionNonce: encNonce,- kdfParams: KDFParams(- memLimit: derivedKeyResult.memLimit,- opsLimit: derivedKeyResult.opsLimit,- salt: CryptoUtil.bin2base64(kekSalt),- ),+ final now = DateTime.now();+ final fileName = _buildFileName(now, isManual: isManual);+ final writeSuccess = await _writeBackup(+ target: target,+ fileName: fileName,+ content: encryptedJson,);-- final encryptedJson = jsonEncode(data.toJson());- final now = DateTime.now();- final formatter = DateFormat('yyyy-MM-dd_HH-mm-ss');- final formattedDate = formatter.format(now);- final fileName = isManual- ? 'ente-auth-manual-backup-$formattedDate.json'- : 'ente-auth-daily-backup-$formattedDate.json';-- if (backupTreeUri != null && backupTreeUri.isNotEmpty) {- await _writeBackupWithSaf(- backupTreeUri,- fileName,- encryptedJson,- );- success = true;- } else if (backupDirectory != null) {- final filePath = '${backupDirectory.path}/$fileName';- final backupFile = File(filePath);- await backupFile.create(recursive: true);- await backupFile.writeAsString(encryptedJson);- await _manageOldBackups(backupDirectory.path);- _logger.info(- 'Automatic encrypted backup successful! Saved to: $filePath',- );- success = true;- }- if (success && !isManual) {+ if (writeSuccess && !isManual) {await _recordBackupDay(prefs, now);}+ return writeSuccess;} catch (e, s) {_logger.severe('Silent error during automatic backup', e, s);+ return false;}- return success;}Future<bool> triggerDailyBackupIfNeeded() async {final prefs = await SharedPreferences.getInstance();- if (_hasBackedUpToday(prefs)) {+ if (_hasBackedUpToday(prefs)) return false;+ return triggerAutomaticBackup();+ }++ Future<bool> _writeBackup({+ required _BackupTarget target,+ required String fileName,+ required String content,+ }) async {+ try {+ if (target.treeUri != null) {+ await _writeBackupWithSaf(target.treeUri!, fileName, content);+ return true;+ }++ final dir = Directory(target.path!);+ await dir.create(recursive: true);+ final filePath = '${dir.path}/$fileName';+ final backupFile = File(filePath);+ await backupFile.create(recursive: true);+ await backupFile.writeAsString(content);+ await _manageOldBackups(dir.path);+ _logger.info('Automatic encrypted backup successful! Saved to: $filePath');+ return true;+ } catch (e, s) {+ _logger.severe('Failed to write backup', e, s);return false;}- return triggerAutomaticBackup();}Future<void> _writeBackupWithSaf(@@ -158,49 +93,40 @@ class LocalBackupService {String fileName,String content,) async {- try {- final safStream = SafStream();- await safStream.writeFileBytes(- treeUri,- fileName,- 'application/octet-stream',- Uint8List.fromList(utf8.encode(content)),- overwrite: true,- );- _logger.info('Automatic encrypted backup saved via SAF: $fileName');- } catch (e, s) {- _logger.severe('Failed to write backup via SAF', e, s);- rethrow;- }+ final safStream = SafStream();+ await safStream.writeFileBytes(+ treeUri,+ fileName,+ 'application/octet-stream',+ Uint8List.fromList(utf8.encode(content)),+ overwrite: true,+ );+ _logger.info('Automatic encrypted backup saved via SAF: $fileName');}Future<void> _manageOldBackups(String backupPath) async {try {- _logger.info("Checking for old backups to clean up...");final directory = Directory(backupPath);-- // fetch all filenames in the folder, filter out ente backup files- final files = directory.listSync()- .where((entity) =>- entity is File &&- _isBackupFile(entity.path.split('/').last),)+ final files = directory+ .listSync()+ .where(+ (entity) =>+ entity is File &&+ _isBackupFile(entity.path.split('/').last),+ ).map((entity) => entity as File).toList();- // sort by last modified (oldest first)files.sort((a, b) => a.lastModifiedSync().compareTo(b.lastModifiedSync()),);- // if we have more files than our limit, delete the oldest ones (current limit=_maxBackups)while (files.length > _maxBackups) {- // remove the oldest file (at index 0) from the list- final fileToDelete = files.removeAt(0);- // and delete it from the device's storage..- await fileToDelete.delete();- _logger.info('Deleted old backup: ${fileToDelete.path}');-}-_logger.info('Backup count is now ${files.length}. Cleanup complete.');+ final fileToDelete = files.removeAt(0);+ await fileToDelete.delete();+ _logger.info('Deleted old backup: ${fileToDelete.path}');+ }+ _logger.info('Backup count is now ${files.length}. Cleanup complete.');} catch (e, s) {_logger.severe('Error during old backup cleanup', e, s);}@@ -208,37 +134,118 @@ _logger.info('Backup count is now ${files.length}. Cleanup complete.');Future<void> deleteAllBackupsIn(String path) async {try {- _logger.info("Deleting all backups in old location: $path");final directory = Directory(path);-if (!await directory.exists()) {- _logger.warning("Old backup directory not found. Nothing to delete.");+ _logger.warning('Old backup directory not found. Nothing to delete.');return;}- final files = directory.listSync()- .where((entity) =>- entity is File &&- _isBackupFile(entity.path.split('/').last),)+ final files = directory+ .listSync()+ .where(+ (entity) =>+ entity is File &&+ _isBackupFile(entity.path.split('/').last),+ ).map((entity) => entity as File).toList();if (files.isEmpty) {- _logger.info("No old backup files found to delete.");+ _logger.info('No old backup files found to delete.');return;}-+for (final file in files) {await file.delete();_logger.info('Deleted: ${file.path}');}- _logger.info("Successfully cleaned up old backup location.");-+ _logger.info('Successfully cleaned up old backup location.');} catch (e, s) {_logger.severe('Error during full backup cleanup of old directory', e, s);}}+ bool _isBackupEnabled(SharedPreferences prefs) =>+ prefs.getBool('isAutoBackupEnabled') ?? false;++ _BackupTarget? _resolveTarget(SharedPreferences prefs) {+ final path = prefs.getString('autoBackupPath');+ final treeUri = prefs.getString('autoBackupTreeUri');++ if (treeUri != null && treeUri.isNotEmpty) {+ return _BackupTarget.saf(treeUri);+ }+ if (path != null && path.isNotEmpty) {+ return _BackupTarget.file(path);+ }+ return null;+ }++ Future<String?> _readPassword() async {+ const storage = FlutterSecureStorage();+ try {+ return storage.read(key: 'autoBackupPassword');+ } catch (e, s) {+ _logger.severe('Unable to read backup password', e, s);+ return null;+ }+ }++ Future<String?> _buildEncryptedPayload(String password) async {+ final rawContent = await CodeStore.instance.getCodesForExport();+ final cleanedLines = rawContent+ .split('\n')+ .map((line) {+ if (line.trim().isEmpty) return null;+ if (line.startsWith('"') && line.endsWith('"')) {+ return jsonDecode(line);+ }+ return line;+ })+ .whereType<String>()+ .toList();++ final plainTextContent = cleanedLines.join('\n');+ if (plainTextContent.trim().isEmpty) {+ return null;+ }++ final kekSalt = CryptoUtil.getSaltToDeriveKey();+ final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(+ utf8.encode(password),+ kekSalt,+ );++ final encResult = await CryptoUtil.encryptData(+ utf8.encode(plainTextContent),+ derivedKeyResult.key,+ );++ final encContent = CryptoUtil.bin2base64(encResult.encryptedData!);+ final encNonce = CryptoUtil.bin2base64(encResult.header!);++ final data = EnteAuthExport(+ version: 1,+ encryptedData: encContent,+ encryptionNonce: encNonce,+ kdfParams: KDFParams(+ memLimit: derivedKeyResult.memLimit,+ opsLimit: derivedKeyResult.opsLimit,+ salt: CryptoUtil.bin2base64(kekSalt),+ ),+ );++ return jsonEncode(data.toJson());+ }++ String _buildFileName(DateTime now, {required bool isManual}) {+ final formatter = DateFormat('yyyy-MM-dd_HH-mm-ss');+ final formattedDate = formatter.format(now);+ return isManual+ ? 'ente-auth-manual-backup-$formattedDate.json'+ : 'ente-auth-daily-backup-$formattedDate.json';+ }+bool _hasBackedUpToday(SharedPreferences prefs) {final todayKey = DateFormat('yyyy-MM-dd').format(DateTime.now());final last = prefs.getString(_lastBackupDayKey);@@ -256,3 +263,13 @@ _logger.info('Backup count is now ${files.length}. Cleanup complete.');fileName.startsWith('ente-auth-auto-backup-');}}++class _BackupTarget {+ const _BackupTarget.file(this.path) : treeUri = null;+ const _BackupTarget.saf(this.treeUri) : path = null;++ final String? path;+ final String? treeUri;++ bool get isSaf => treeUri != null;+}