π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[auth] use dir_utils plugin for local backup directory access
Prateek Sunal2ff573fbdee5
diff --git a/mobile/apps/auth/ios/Podfile.lock b/mobile/apps/auth/ios/Podfile.lockindex 985a9edc8d..41c0103a16 100644--- a/mobile/apps/auth/ios/Podfile.lock+++ b/mobile/apps/auth/ios/Podfile.lock@@ -8,6 +8,8 @@ PODS:- FlutterMacOS- device_info_plus (0.0.1):- Flutter+ - dir_utils (1.0.0):+ - Flutter- DKImagePickerController/Core (4.3.9):- DKImagePickerController/ImageDataManager- DKImagePickerController/Resource@@ -90,8 +92,6 @@ PODS:- SDWebImage (5.21.2):- SDWebImage/Core (= 5.21.2)- SDWebImage/Core (5.21.2)- - security_scoped_resource (0.0.1):- - Flutter- Sentry/HybridSDK (8.46.0)- sentry_flutter (8.14.2):- Flutter@@ -140,6 +140,7 @@ DEPENDENCIES:- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)+ - dir_utils (from `.symlinks/plugins/dir_utils/ios`)- ente_qr (from `.symlinks/plugins/ente_qr/ios`)- file_picker (from `.symlinks/plugins/file_picker/ios`)- file_saver (from `.symlinks/plugins/file_saver/ios`)@@ -159,7 +160,6 @@ DEPENDENCIES:- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)- privacy_screen (from `.symlinks/plugins/privacy_screen/ios`)- qr_code_scanner (from `.symlinks/plugins/qr_code_scanner/ios`)- - security_scoped_resource (from `.symlinks/plugins/security_scoped_resource/ios`)- sentry_flutter (from `.symlinks/plugins/sentry_flutter/ios`)- share_plus (from `.symlinks/plugins/share_plus/ios`)- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)@@ -189,6 +189,8 @@ EXTERNAL SOURCES::path: ".symlinks/plugins/cupertino_http/darwin"device_info_plus::path: ".symlinks/plugins/device_info_plus/ios"+ dir_utils:+ :path: ".symlinks/plugins/dir_utils/ios"ente_qr::path: ".symlinks/plugins/ente_qr/ios"file_picker:@@ -227,8 +229,6 @@ EXTERNAL SOURCES::path: ".symlinks/plugins/privacy_screen/ios"qr_code_scanner::path: ".symlinks/plugins/qr_code_scanner/ios"- security_scoped_resource:- :path: ".symlinks/plugins/security_scoped_resource/ios"sentry_flutter::path: ".symlinks/plugins/sentry_flutter/ios"share_plus:@@ -251,6 +251,7 @@ SPEC CHECKSUMS:connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7ddcupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86cdevice_info_plus: 335f3ce08d2e174b9fdc3db3db0f4e3b1f66bd89+ dir_utils: c668f14c9a72a5087d11c4722cb272de0a87ce10DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3cDKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60ente_qr: 2a30f91f9e938c229ebcbc98a6f8f018d1ac665d@@ -275,7 +276,6 @@ SPEC CHECKSUMS:privacy_screen: 3159a541f5d3a31bea916cfd4e58f9dc722b3fd4qr_code_scanner: d77f94ecc9abf96d9b9b8fc04ef13f611e5a147aSDWebImage: 9f177d83116802728e122410fb25ad88f5c7608a- security_scoped_resource: 8b95b9c0e93ae4e03b60e9b6be9c2d61e3751ec1Sentry: da60d980b197a46db0b35ea12cb8f39af48d8854sentry_flutter: 27892878729f42701297c628eb90e7c6529f3684share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58adiff --git a/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxprojindex 44a7bbfc1e..131451ff95 100644--- a/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj+++ b/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj@@ -10,7 +10,6 @@1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };- SECBKMK0123456789ABCDE01 /* SecurityBookmarkPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = SECBKMK0123456789ABCDE00 /* SecurityBookmarkPlugin.swift */; };80417A98453207A394AAD2D5 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D28AA20446BAC82150599AAF /* Pods_Runner.framework */; };97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };@@ -38,7 +37,6 @@41BDE1E3C8C8C388B911D127 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };- SECBKMK0123456789ABCDE00 /* SecurityBookmarkPlugin.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecurityBookmarkPlugin.swift; sourceTree = "<group>"; };7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };@@ -127,7 +125,6 @@1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,74858FAE1ED2DC5600515810 /* AppDelegate.swift */,- SECBKMK0123456789ABCDE00 /* SecurityBookmarkPlugin.swift */,74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,);path = Runner;@@ -283,7 +280,6 @@buildActionMask = 2147483647;files = (74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,- SECBKMK0123456789ABCDE01 /* SecurityBookmarkPlugin.swift in Sources */,1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,);runOnlyForDeploymentPostprocessing = 0;diff --git a/mobile/apps/auth/ios/Runner/AppDelegate.swift b/mobile/apps/auth/ios/Runner/AppDelegate.swiftindex f1f70accb3..f0a6599d7f 100644--- a/mobile/apps/auth/ios/Runner/AppDelegate.swift+++ b/mobile/apps/auth/ios/Runner/AppDelegate.swift@@ -9,12 +9,6 @@ import app_linksdidFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {GeneratedPluginRegistrant.register(with: self)-- // Register custom security bookmark plugin for persistent directory access- if let registrar = self.registrar(forPlugin: "SecurityBookmarkPlugin") {- SecurityBookmarkPlugin.register(with: registrar)- }-super.application(application, didFinishLaunchingWithOptions: launchOptions)if let url = AppLinks.shared.getLink(launchOptions: launchOptions) {diff --git a/mobile/apps/auth/ios/Runner/SecurityBookmarkPlugin.swift b/mobile/apps/auth/ios/Runner/SecurityBookmarkPlugin.swiftdeleted file mode 100644index fa4ce134dc..0000000000--- a/mobile/apps/auth/ios/Runner/SecurityBookmarkPlugin.swift+++ /dev/null@@ -1,253 +0,0 @@-import Flutter-import Foundation-import UIKit-import UniformTypeIdentifiers--public class SecurityBookmarkPlugin: NSObject, FlutterPlugin {- private var pendingResult: FlutterResult?-- public static func register(with registrar: FlutterPluginRegistrar) {- let channel = FlutterMethodChannel(- name: "io.ente.auth/security_bookmark",- binaryMessenger: registrar.messenger()- )- let instance = SecurityBookmarkPlugin()- registrar.addMethodCallDelegate(instance, channel: channel)- }-- public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {- switch call.method {- case "pickDirectoryAndCreateBookmark":- handlePickDirectoryAndCreateBookmark(result: result)- case "createBookmark":- handleCreateBookmark(call: call, result: result)- case "resolveBookmark":- handleResolveBookmark(call: call, result: result)- case "startAccessingBookmark":- handleStartAccessingBookmark(call: call, result: result)- case "stopAccessingBookmark":- handleStopAccessingBookmark(call: call, result: result)- default:- result(FlutterMethodNotImplemented)- }- }-- /// Pick a directory using native iOS picker and create a bookmark immediately- /// while we still have the security-scoped URL.- private func handlePickDirectoryAndCreateBookmark(result: @escaping FlutterResult) {- guard let viewController = UIApplication.shared.windows.first?.rootViewController else {- result(FlutterError(code: "NO_VIEW_CONTROLLER", message: "Could not find root view controller", details: nil))- return- }-- pendingResult = result-- let picker: UIDocumentPickerViewController- if #available(iOS 14.0, *) {- picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder])- } else {- // Fallback for iOS 13- picker = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open)- }- picker.delegate = self- picker.allowsMultipleSelection = false-- viewController.present(picker, animated: true)- }-- private func handleCreateBookmark(call: FlutterMethodCall, result: @escaping FlutterResult) {- guard let args = call.arguments as? [String: Any],- let path = args["path"] as? String else {- result(FlutterError(code: "INVALID_ARGS", message: "Missing 'path' argument", details: nil))- return- }-- let url = URL(fileURLWithPath: path, isDirectory: true)-- // Check if path exists- let fileManager = FileManager.default- var isDirectory: ObjCBool = false- let exists = fileManager.fileExists(atPath: path, isDirectory: &isDirectory)-- NSLog("SecurityBookmarkPlugin: Creating bookmark for path: \(path)")- NSLog("SecurityBookmarkPlugin: URL: \(url.absoluteString)")- NSLog("SecurityBookmarkPlugin: Path exists: \(exists), isDirectory: \(isDirectory.boolValue)")-- // Must start accessing the security-scoped resource before creating a bookmark- let didStartAccessing = url.startAccessingSecurityScopedResource()- NSLog("SecurityBookmarkPlugin: startAccessingSecurityScopedResource returned: \(didStartAccessing)")-- defer {- if didStartAccessing {- url.stopAccessingSecurityScopedResource()- }- }-- do {- // Create a minimal bookmark that can be persisted- let bookmarkData = try url.bookmarkData(- options: .minimalBookmark,- includingResourceValuesForKeys: nil,- relativeTo: nil- )-- // Return as base64 string for easy storage- let base64String = bookmarkData.base64EncodedString()- NSLog("SecurityBookmarkPlugin: Bookmark created successfully, length: \(base64String.count)")- result(base64String)- } catch {- NSLog("SecurityBookmarkPlugin: Failed to create bookmark: \(error)")- result(FlutterError(- code: "BOOKMARK_ERROR",- message: "Failed to create bookmark: \(error.localizedDescription)",- details: "path=\(path), exists=\(exists), didStartAccessing=\(didStartAccessing)"- ))- }- }-- private func handleResolveBookmark(call: FlutterMethodCall, result: @escaping FlutterResult) {- guard let args = call.arguments as? [String: Any],- let base64Bookmark = args["bookmark"] as? String,- let bookmarkData = Data(base64Encoded: base64Bookmark) else {- result(FlutterError(code: "INVALID_ARGS", message: "Missing or invalid 'bookmark' argument", details: nil))- return- }-- do {- var isStale = false- let url = try URL(- resolvingBookmarkData: bookmarkData,- options: [],- relativeTo: nil,- bookmarkDataIsStale: &isStale- )-- // Return both the path and stale status- result([- "path": url.path,- "isStale": isStale- ])- } catch {- result(FlutterError(- code: "RESOLVE_ERROR",- message: "Failed to resolve bookmark: \(error.localizedDescription)",- details: nil- ))- }- }-- private func handleStartAccessingBookmark(call: FlutterMethodCall, result: @escaping FlutterResult) {- guard let args = call.arguments as? [String: Any],- let base64Bookmark = args["bookmark"] as? String,- let bookmarkData = Data(base64Encoded: base64Bookmark) else {- result(FlutterError(code: "INVALID_ARGS", message: "Missing or invalid 'bookmark' argument", details: nil))- return- }-- do {- var isStale = false- let url = try URL(- resolvingBookmarkData: bookmarkData,- options: [],- relativeTo: nil,- bookmarkDataIsStale: &isStale- )-- let success = url.startAccessingSecurityScopedResource()- result([- "success": success,- "path": url.path,- "isStale": isStale- ])- } catch {- result(FlutterError(- code: "ACCESS_ERROR",- message: "Failed to start accessing bookmark: \(error.localizedDescription)",- details: nil- ))- }- }-- private func handleStopAccessingBookmark(call: FlutterMethodCall, result: @escaping FlutterResult) {- guard let args = call.arguments as? [String: Any],- let base64Bookmark = args["bookmark"] as? String,- let bookmarkData = Data(base64Encoded: base64Bookmark) else {- result(FlutterError(code: "INVALID_ARGS", message: "Missing or invalid 'bookmark' argument", details: nil))- return- }-- do {- var isStale = false- let url = try URL(- resolvingBookmarkData: bookmarkData,- options: [],- relativeTo: nil,- bookmarkDataIsStale: &isStale- )-- url.stopAccessingSecurityScopedResource()- result(true)- } catch {- result(FlutterError(- code: "ACCESS_ERROR",- message: "Failed to stop accessing bookmark: \(error.localizedDescription)",- details: nil- ))- }- }-}--// MARK: - UIDocumentPickerDelegate-extension SecurityBookmarkPlugin: UIDocumentPickerDelegate {- public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {- guard let result = pendingResult else { return }- pendingResult = nil-- guard let url = urls.first else {- result(FlutterError(code: "NO_SELECTION", message: "No directory selected", details: nil))- return- }-- NSLog("SecurityBookmarkPlugin: Picked directory URL: \(url.absoluteString)")-- // Start accessing the security-scoped resource- let didStartAccessing = url.startAccessingSecurityScopedResource()- NSLog("SecurityBookmarkPlugin: startAccessingSecurityScopedResource: \(didStartAccessing)")-- defer {- if didStartAccessing {- url.stopAccessingSecurityScopedResource()- }- }-- do {- // Create bookmark while we have security-scoped access- let bookmarkData = try url.bookmarkData(- options: .minimalBookmark,- includingResourceValuesForKeys: nil,- relativeTo: nil- )-- let base64Bookmark = bookmarkData.base64EncodedString()- NSLog("SecurityBookmarkPlugin: Bookmark created successfully, length: \(base64Bookmark.count)")-- result([- "path": url.path,- "bookmark": base64Bookmark- ])- } catch {- NSLog("SecurityBookmarkPlugin: Failed to create bookmark: \(error)")- result(FlutterError(- code: "BOOKMARK_ERROR",- message: "Failed to create bookmark: \(error.localizedDescription)",- details: nil- ))- }- }-- public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {- guard let result = pendingResult else { return }- pendingResult = nil- result(nil) // User cancelled- }-}diff --git a/mobile/apps/auth/lib/core/configuration.dart b/mobile/apps/auth/lib/core/configuration.dartindex c1baee13e8..ef200eaba2 100644--- a/mobile/apps/auth/lib/core/configuration.dart+++ b/mobile/apps/auth/lib/core/configuration.dart@@ -52,14 +52,19 @@ class Configuration extends BaseConfiguration {@override// This includes both base keys (key, secretKey) and auth-specific keys.- List<String> get secureStorageKeys => [- BaseConfiguration.keyKey,- BaseConfiguration.secretKeyKey,- authSecretKeyKey,- SecureStorageService.autoBackupPasswordKey,- // Note: offlineAuthSecretKey is intentionally not included here- // as it persists across logouts- ];+ List<String> get secureStorageKeys {+ final keys = [+ BaseConfiguration.keyKey,+ BaseConfiguration.secretKeyKey,+ authSecretKeyKey,+ ];+ if (!_shouldPreserveLocalBackupPassword()) {+ keys.add(SecureStorageService.autoBackupPasswordKey);+ }+ // Note: offlineAuthSecretKey is intentionally not included here+ // as it persists across logouts+ return keys;+ }@overrideFuture<void> logout({bool autoLogout = false}) async {@@ -107,4 +112,8 @@ class Configuration extends BaseConfiguration {}await _preferences.setBool(hasOptedForOfflineModeKey, true);}++ bool _shouldPreserveLocalBackupPassword() {+ return hasOptedForOfflineMode() && !hasConfiguredAccount();+ }}diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dartindex 2e1535fb0d..e410a9d17d 100644--- a/mobile/apps/auth/lib/services/local_backup_service.dart+++ b/mobile/apps/auth/lib/services/local_backup_service.dart@@ -2,16 +2,13 @@ import 'dart:convert';import 'dart:io';import 'dart:typed_data';+import 'package:dir_utils/dir_utils.dart';import 'package:ente_auth/models/export/ente.dart';import 'package:ente_auth/services/secure_storage_service.dart';-import 'package:ente_auth/services/security_bookmark_service.dart';import 'package:ente_auth/store/code_store.dart';import 'package:ente_crypto_dart/ente_crypto_dart.dart';import 'package:intl/intl.dart';import 'package:logging/logging.dart';-import 'package:saf_stream/saf_stream.dart';-import 'package:saf_util/saf_util.dart';-import 'package:security_scoped_resource/security_scoped_resource.dart';import 'package:shared_preferences/shared_preferences.dart';class LocalBackupService {@@ -113,117 +110,64 @@ class LocalBackupService {required String content,}) async {try {- if (target.treeUri != null) {- await _writeBackupWithSaf(target.treeUri!, fileName, content);- await _pruneSafBackups(target.treeUri!, limit: _maxBackups);- return true;- }-- final scopedDir = Directory(target.path!);- // On iOS, saved path is the parent; we write to EnteAuthBackups subdirectory- final backupDir = Platform.isIOS- ? Directory('${scopedDir.path}/EnteAuthBackups')- : scopedDir;-- Future<bool> doWrite() async {- _logger.info('Creating backup directory: ${backupDir.path}');- await backupDir.create(recursive: true);- _logger.info('Backup directory created/exists');-- final filePath = '${backupDir.path}/$fileName';-- _logger.info('Writing backup file: $filePath');- final backupFile = File(filePath);- await backupFile.writeAsString(content);- _logger.info('Backup file written successfully');-- await _manageOldBackups(backupDir.path);- _logger- .info('Automatic encrypted backup successful! Saved to: $filePath');- return true;- }+ final dirUtils = DirUtils.instance;+ final contentBytes = Uint8List.fromList(utf8.encode(content));- // On iOS, we need to use security-scoped access- if (Platform.isIOS) {- final bookmark = target.iosBookmark;- bool hasAccess = false;- bool usingBookmark = false;-- // Try bookmark-based access first- if (bookmark != null && bookmark.isNotEmpty) {- _logger.info('iOS: Starting access via bookmark');- final accessResult = await SecurityBookmarkService.instance- .startAccessingBookmark(bookmark);- if (accessResult != null && accessResult.success) {- hasAccess = true;- usingBookmark = true;- if (accessResult.isStale) {- _logger.warning(- 'iOS: Bookmark is stale, user may need to re-select directory',- );- }- _logger.info('iOS: Scoped access granted via bookmark');- } else {- _logger.warning('iOS: Bookmark access failed, trying path-based');- }- }-- // Fallback to path-based access- if (!hasAccess) {- _logger.info('iOS: Trying path-based access for: ${scopedDir.path}');- hasAccess = await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(scopedDir);- _logger.info('iOS: Path-based access result: $hasAccess');+ // Android SAF+ if (target.treeUri != null) {+ final dir = PickedDirectory(path: '', treeUri: target.treeUri);+ final success = await dirUtils.writeFile(dir, fileName, contentBytes);+ if (success) {+ await _pruneBackups(dir, limit: _maxBackups);}+ return success;+ }- if (!hasAccess) {- _logger- .severe('iOS: All access methods failed for: ${scopedDir.path}');- return false;- }+ // iOS with bookmark or other platforms+ final subPath = Platform.isIOS ? 'EnteAuthBackups' : null;+ final dir = PickedDirectory(+ path: target.path!,+ bookmark: target.iosBookmark,+ );- try {- return await doWrite();- } finally {- if (usingBookmark && bookmark != null) {- await SecurityBookmarkService.instance- .stopAccessingBookmark(bookmark);- } else {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(scopedDir);+ // On iOS, use withAccess for scoped access+ if (Platform.isIOS && target.iosBookmark != null) {+ final result = await dirUtils.withAccess(dir, (path) async {+ final fullPath = subPath != null ? '$path/$subPath' : path;+ await dirUtils.createDirectory(dir, subPath!);+ final success = await dirUtils.writeFile(+ PickedDirectory(path: fullPath),+ fileName,+ contentBytes,+ );+ if (success) {+ await _manageOldBackups(fullPath);}- }+ return success;+ });+ return result ?? false;}- return await doWrite();+ // Non-iOS: direct file write+ final basePath = subPath != null ? '${target.path}/$subPath' : target.path!;+ await Directory(basePath).create(recursive: true);+ final filePath = '$basePath/$fileName';+ await File(filePath).writeAsBytes(contentBytes);+ await _manageOldBackups(basePath);+ _logger.info('Backup written to: $filePath');+ return true;} catch (e, s) {_logger.severe('Failed to write backup: $e', e, s);return false;}}- Future<void> _writeBackupWithSaf(- String treeUri,- String fileName,- String content,- ) async {- 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> _pruneSafBackups(String treeUri, {required int limit}) async {+ Future<void> _pruneBackups(PickedDirectory dir, {required int limit}) async {try {- final safUtil = SafUtil();- final entries = await safUtil.list(treeUri);- final backupFiles = entries- .where((file) => !file.isDir && _isBackupFile(file.name))+ final dirUtils = DirUtils.instance;+ final files = await dirUtils.listFiles(dir);+ final backupFiles = files+ .where((file) => !file.isDirectory && _isBackupFile(file.name)).toList();backupFiles.sort((a, b) {@@ -234,11 +178,11 @@ class LocalBackupService {while (backupFiles.length > limit) {final file = backupFiles.removeAt(0);- await safUtil.delete(file.uri, file.isDir);- _logger.info('Deleted old backup via SAF: ${file.name}');+ await dirUtils.deleteFile(dir, file);+ _logger.info('Deleted old backup: ${file.name}');}} catch (e, s) {- _logger.severe('Error pruning SAF backups', e, s);+ _logger.severe('Error pruning backups', e, s);}}@@ -276,12 +220,12 @@ class LocalBackupService {Future<void> deleteAllBackupsIn(String path, {String? iosBookmark}) async {try {- final scopedDir = Directory(path);- // On iOS, saved path is the parent; backups are in EnteAuthBackups subdirectory- final backupDir =- Platform.isIOS ? Directory('$path/EnteAuthBackups') : scopedDir;+ final dirUtils = DirUtils.instance;+ final subPath = Platform.isIOS ? 'EnteAuthBackups' : null;+ final backupPath = subPath != null ? '$path/$subPath' : path;Future<void> doDelete() async {+ final backupDir = Directory(backupPath);if (!await backupDir.exists()) {_logger.warning('Old backup directory not found. Nothing to delete.');return;@@ -308,50 +252,13 @@ class LocalBackupService {_logger.info('Successfully cleaned up old backup location.');}- // On iOS, we need to use security-scoped access- if (Platform.isIOS) {- bool hasAccess = false;- bool usingBookmark = false;-- // Try bookmark-based access first- if (iosBookmark != null && iosBookmark.isNotEmpty) {- _logger.info('iOS: Starting access via bookmark for deletion');- final accessResult = await SecurityBookmarkService.instance- .startAccessingBookmark(iosBookmark);- if (accessResult != null && accessResult.success) {- hasAccess = true;- usingBookmark = true;- _logger.info('iOS: Scoped access granted via bookmark');- } else {- _logger.warning('iOS: Bookmark access failed, trying path-based');- }- }-- // Fallback to path-based access- if (!hasAccess) {- _logger.info('iOS: Trying path-based access for: ${scopedDir.path}');- hasAccess = await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(scopedDir);- _logger.info('iOS: Path-based access result: $hasAccess');- }-- if (!hasAccess) {- _logger- .severe('iOS: All access methods failed for: ${scopedDir.path}');- return;- }-- try {+ // On iOS, use scoped access via bookmark+ if (Platform.isIOS && iosBookmark != null && iosBookmark.isNotEmpty) {+ final dir = PickedDirectory(path: path, bookmark: iosBookmark);+ await dirUtils.withAccess(dir, (_) async {await doDelete();- } finally {- if (usingBookmark && iosBookmark != null) {- await SecurityBookmarkService.instance- .stopAccessingBookmark(iosBookmark);- } else {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(scopedDir);- }- }+ return true;+ });} else {await doDelete();}diff --git a/mobile/apps/auth/lib/services/security_bookmark_service.dart b/mobile/apps/auth/lib/services/security_bookmark_service.dartindex d1a036738c..41a84f2b6b 100644--- a/mobile/apps/auth/lib/services/security_bookmark_service.dart+++ b/mobile/apps/auth/lib/services/security_bookmark_service.dart@@ -1,19 +1,17 @@import 'dart:io';-import 'package:flutter/services.dart';-import 'package:logging/logging.dart';+import 'package:dir_utils/dir_utils.dart';/// Service for managing iOS security-scoped bookmarks.///-/// On iOS, when a user picks a directory outside the app sandbox,-/// the app receives temporary security-scoped access. To persist-/// this access across app launches, we must create a bookmark.+/// This is a thin wrapper around [DirUtils] for backward compatibility.+/// You can use [DirUtils.instance] directly if you prefer.class SecurityBookmarkService {SecurityBookmarkService._();static final SecurityBookmarkService instance = SecurityBookmarkService._();- static const _channel = MethodChannel('io.ente.auth/security_bookmark');- final _logger = Logger('SecurityBookmarkService');++ final _dirUtils = DirUtils.instance;/// Opens native iOS directory picker and creates a bookmark immediately.///@@ -23,77 +21,13 @@ class SecurityBookmarkService {Future<DirectoryPickResult?> pickDirectoryAndCreateBookmark() async {if (!Platform.isIOS) return null;- try {- final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(- 'pickDirectoryAndCreateBookmark',- );- if (result == null) {- _logger.info('Directory picker cancelled');- return null;- }-- final path = result['path'] as String?;- final bookmark = result['bookmark'] as String?;-- if (path == null || bookmark == null) {- _logger.severe('Invalid result from directory picker');- return null;- }-- _logger- .info('Picked directory: $path, bookmark length: ${bookmark.length}');- return DirectoryPickResult(path: path, bookmark: bookmark);- } on PlatformException catch (e) {- _logger.severe('Failed to pick directory: ${e.message}');- return null;- }- }-- /// Creates a security-scoped bookmark for the given directory path.- ///- /// NOTE: This typically doesn't work on iOS because the path from FilePicker- /// doesn't have security-scoped access. Use [pickDirectoryAndCreateBookmark] instead.- ///- /// Returns the bookmark as a base64-encoded string, or null on failure.- Future<String?> createBookmark(String directoryPath) async {- if (!Platform.isIOS) return null;-- try {- final result = await _channel.invokeMethod<String>(- 'createBookmark',- {'path': directoryPath},- );- _logger.info('Created bookmark for: $directoryPath');- return result;- } on PlatformException catch (e) {- _logger.severe('Failed to create bookmark: ${e.message}');- return null;- }- }-- /// Resolves a bookmark to get the directory path.- ///- /// Returns a [BookmarkResolveResult] with the path and stale status.- /// If the bookmark is stale (directory was moved/renamed), you should- /// prompt the user to re-select the directory.- Future<BookmarkResolveResult?> resolveBookmark(String bookmark) async {- if (!Platform.isIOS) return null;+ final result = await _dirUtils.pickDirectory();+ if (result == null) return null;- try {- final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(- 'resolveBookmark',- {'bookmark': bookmark},- );- if (result == null) return null;-- return BookmarkResolveResult(- path: result['path'] as String,- isStale: result['isStale'] as bool,- );- } on PlatformException catch (e) {- _logger.severe('Failed to resolve bookmark: ${e.message}');- return null;- }+ return DirectoryPickResult(+ path: result.path,+ bookmark: result.bookmark ?? '',+ );}/// Starts accessing a security-scoped resource using a stored bookmark.@@ -105,27 +39,15 @@ class SecurityBookmarkService {Future<BookmarkAccessResult?> startAccessingBookmark(String bookmark) async {if (!Platform.isIOS) return null;- try {- final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(- 'startAccessingBookmark',- {'bookmark': bookmark},- );- if (result == null) return null;-- final accessResult = BookmarkAccessResult(- success: result['success'] as bool,- path: result['path'] as String,- isStale: result['isStale'] as bool,- );- _logger.info(- 'Start accessing bookmark: success=${accessResult.success}, '- 'path=${accessResult.path}, isStale=${accessResult.isStale}',- );- return accessResult;- } on PlatformException catch (e) {- _logger.severe('Failed to start accessing bookmark: ${e.message}');- return null;- }+ final dir = PickedDirectory(path: '', bookmark: bookmark);+ final result = await _dirUtils.startAccess(dir);+ if (result == null) return null;++ return BookmarkAccessResult(+ success: result.success,+ path: result.path,+ isStale: result.isStale,+ );}/// Stops accessing a security-scoped resource.@@ -135,17 +57,8 @@ class SecurityBookmarkService {Future<bool> stopAccessingBookmark(String bookmark) async {if (!Platform.isIOS) return true;- try {- final result = await _channel.invokeMethod<bool>(- 'stopAccessingBookmark',- {'bookmark': bookmark},- );- _logger.info('Stopped accessing bookmark');- return result ?? false;- } on PlatformException catch (e) {- _logger.severe('Failed to stop accessing bookmark: ${e.message}');- return false;- }+ final dir = PickedDirectory(path: '', bookmark: bookmark);+ return _dirUtils.stopAccess(dir);}}@@ -159,16 +72,6 @@ class DirectoryPickResult {final String bookmark;}-class BookmarkResolveResult {- const BookmarkResolveResult({- required this.path,- required this.isStale,- });-- final String path;- final bool isStale;-}-class BookmarkAccessResult {const BookmarkAccessResult({required this.success,diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dartindex 2170e4f982..a9fccbfaf8 100644--- a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart@@ -14,7 +14,6 @@ import 'package:flutter/material.dart';import 'package:logging/logging.dart';import 'package:path_provider/path_provider.dart';import 'package:saf_util/saf_util.dart';-import 'package:security_scoped_resource/security_scoped_resource.dart';import 'package:shared_preferences/shared_preferences.dart';typedef LocalBackupVariantBuilder = Widget Function(@@ -134,13 +133,10 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {}Future<bool> _startEnableFlow() async {- // Always prompt for password when enabling backups, even if one exists.- // This ensures the user knows/remembers the password they'll need for restore.- final hasPassword = await _promptPassword(- forcePrompt: true,+ final hasPassword = await _ensurePasswordConfigured(disableOnCancel: true,- isUpdateFlow: false,);+ // We only require a password to exist; re-enabling skips re-entry if already set.if (!hasPassword) {return false;}@@ -588,19 +584,11 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {final pickResult = await SecurityBookmarkService.instance.pickDirectoryAndCreateBookmark();if (pickResult != null) {- final saved = await _persistLocationWithBookmark(+ return _persistLocationWithBookmark(pickResult.path,pickResult.bookmark,+ successMessage: context.l10n.initialBackupCreated,);- if (saved) {- final backupSuccess = await LocalBackupService.instance- .triggerAutomaticBackup(isManual: true);- if (backupSuccess) {- _showSnackBar(context.l10n.initialBackupCreated);- }- // If backup fails, location is still saved - UI will reflect the change- }- return saved;}}return false;@@ -735,11 +723,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {successMessage:successMessage ?? context.l10n.locationUpdatedAndBackupCreated,);- if (saved && shouldTriggerBackup) {- await LocalBackupService.instance.triggerAutomaticBackup(- isManual: true,- );- }return saved;}if (requireSelection) {@@ -834,84 +817,13 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {Future<bool> savePath(String target) async {try {if (Platform.isIOS) {- // On iOS: try to create a security-scoped bookmark for persistent access.- // If bookmark creation fails, we still save the path and hope for the best- // (the old approach relied on security_scoped_resource plugin).- _logger.info('iOS: Creating security-scoped bookmark for: $target');- final bookmark =- await SecurityBookmarkService.instance.createBookmark(target);-- String? activeBookmark = bookmark;- if (bookmark == null) {- _logger.warning(- 'iOS: Failed to create bookmark, will try path-based access',- );- } else {- _logger.info('iOS: Bookmark created successfully');- }-- // Start accessing - try bookmark first, then fall back to path-based- bool hasAccess = false;- if (activeBookmark != null) {- final accessResult = await SecurityBookmarkService.instance- .startAccessingBookmark(activeBookmark);- hasAccess = accessResult?.success ?? false;- if (!hasAccess) {- _logger.warning('iOS: Bookmark access failed, trying path-based');- activeBookmark = null;- }- }-- // Fallback to path-based access using security_scoped_resource- if (!hasAccess) {- final parentDir = Directory(target);- hasAccess = await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(parentDir);- _logger.info('iOS: Path-based access result: $hasAccess');- }-- if (!hasAccess) {- _logger.severe('iOS: Failed to get any form of access to: $target');- return false;- }- _logger.info('iOS: Scoped access granted');-- try {- final backupDir = Directory('$target/EnteAuthBackups');- _logger.info('iOS: Creating backup dir');- await backupDir.create(recursive: true);- _logger.info('iOS: Backup dir created, writing initial backup');- await LocalBackupService.instance.writeBackupToDirectory(- backupDir.path,- );- _logger.info('iOS: Initial backup written successfully');- } finally {- if (activeBookmark != null) {- await SecurityBookmarkService.instance- .stopAccessingBookmark(activeBookmark);- } else {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(Directory(target));- }- }-- // Save both the path (for display) and bookmark (for access) if available- _logger.info('iOS: Saving backup path to preferences');- await prefs.setString('autoBackupPath', target);- if (activeBookmark != null) {- await prefs.setString(_iosBookmarkKey, activeBookmark);- _logger.info('iOS: Bookmark saved');- } else {- await prefs.remove(_iosBookmarkKey);- _logger.warning('iOS: No bookmark saved, relying on path only');- }- await prefs.remove(_treeUriKey);- await prefs.setBool(_locationConfiguredKey, true);- if (!mounted) return false;- setState(() {- _backupPath = target;- _backupTreeUri = null;- });+ // On iOS, use native picker with bookmark via _persistLocationWithBookmark.+ // This path is only for non-native picker which won't have scoped access.+ _logger.warning(+ 'iOS: _persistLocation called without bookmark. '+ 'Use native picker for iOS.',+ );+ return false;} else {// Non-iOS: just save the path directlyawait Directory(target).create(recursive: true);diff --git a/mobile/apps/auth/pubspec.lock b/mobile/apps/auth/pubspec.lockindex 789955c69b..9571ae068c 100644--- a/mobile/apps/auth/pubspec.lock+++ b/mobile/apps/auth/pubspec.lock@@ -361,6 +361,13 @@ packages:url: "https://pub.dev"source: hostedversion: "2.1.1"+ dir_utils:+ dependency: "direct main"+ description:+ path: "../../packages/dir_utils"+ relative: true+ source: path+ version: "1.0.0"dots_indicator:dependency: "direct main"description:@@ -1455,14 +1462,6 @@ packages:url: "https://pub.dev"source: hostedversion: "0.2.0"- security_scoped_resource:- dependency: "direct main"- description:- name: security_scoped_resource- sha256: "82279652f4932530f67cf848a55117bb2dcb5a542cb95a84b6ee78ecec9ee31f"- url: "https://pub.dev"- source: hosted- version: "0.0.2"sentry:dependency: "direct main"description:diff --git a/mobile/apps/auth/pubspec.yaml b/mobile/apps/auth/pubspec.yamlindex d5ff7bd079..890faf5956 100644--- a/mobile/apps/auth/pubspec.yaml+++ b/mobile/apps/auth/pubspec.yaml@@ -20,6 +20,8 @@ dependencies:convert: ^3.1.1device_info_plus: ^9.1.1dio: ^5.8.0+1+ dir_utils:+ path: ../../packages/dir_utilsdots_indicator: ^3.0.0dotted_border: ^3.1.0dropdown_button2: ^2.3.9@@ -34,7 +36,7 @@ dependencies:git:url: https://github.com/ente-io/ente_crypto_dart.gitente_events:- path: ../../packages/events+ path: ../../packages/eventsente_lock_screen:path: ../../packages/lock_screenente_logging:@@ -54,7 +56,6 @@ dependencies:figma_squircle: ^0.6.3file_picker: ^10.3.2file_saver: ^0.3.1- security_scoped_resource: ^0.0.2fixnum: ^1.1.0fk_user_agent: # no package updates on pub.devgit: