π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
working secure bookmark
Prateek Sunal74418fdcf1a0
diff --git a/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxprojindex 131451ff95..44a7bbfc1e 100644--- a/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj+++ b/mobile/apps/auth/ios/Runner.xcodeproj/project.pbxproj@@ -10,6 +10,7 @@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 */; };@@ -37,6 +38,7 @@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>"; };@@ -125,6 +127,7 @@1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,74858FAE1ED2DC5600515810 /* AppDelegate.swift */,+ SECBKMK0123456789ABCDE00 /* SecurityBookmarkPlugin.swift */,74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,);path = Runner;@@ -280,6 +283,7 @@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 3c8ec3ec68..f1f70accb3 100644--- a/mobile/apps/auth/ios/Runner/AppDelegate.swift+++ b/mobile/apps/auth/ios/Runner/AppDelegate.swift@@ -10,6 +10,11 @@ import app_links) -> 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.swiftnew file mode 100644index 0000000000..fa4ce134dc--- /dev/null+++ b/mobile/apps/auth/ios/Runner/SecurityBookmarkPlugin.swift@@ -0,0 +1,253 @@+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/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dartindex 4568f0a51c..2e1535fb0d 100644--- a/mobile/apps/auth/lib/services/local_backup_service.dart+++ b/mobile/apps/auth/lib/services/local_backup_service.dart@@ -4,6 +4,7 @@ import 'dart:typed_data';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';@@ -21,6 +22,7 @@ class LocalBackupService {static const int _maxBackups = 5;static const _lastBackupDayKey = 'lastBackupDay';+ static const _iosBookmarkKey = 'autoBackupIosBookmark';Future<bool> triggerAutomaticBackup({bool isManual = false}) async {try {@@ -68,6 +70,43 @@ class LocalBackupService {return triggerAutomaticBackup();}+ /// Write backup to a directory that we already have scoped access to.+ /// Used on iOS where security-scoped access is held by caller.+ Future<bool> writeBackupToDirectory(String directoryPath) async {+ try {+ final String? password = await _readPassword();+ if (password == null || password.isEmpty) {+ _logger.warning('Backup skipped: password not set.');+ return false;+ }++ final String? encryptedJson = await _buildEncryptedPayload(password);+ if (encryptedJson == null) {+ _logger.warning('Backup skipped: no data to backup.');+ return false;+ }++ final now = DateTime.now();+ final fileName = _buildFileName(now, isManual: true);+ final filePath = '$directoryPath/$fileName';++ _logger.info('Writing backup to: $filePath');+ final backupFile = File(filePath);+ await backupFile.writeAsString(encryptedJson);+ _logger.info('Backup written successfully');++ await _manageOldBackups(directoryPath);++ final prefs = await SharedPreferences.getInstance();+ await _recordBackupDay(prefs, now);++ return true;+ } catch (e, s) {+ _logger.severe('Failed to write backup to directory: $e', e, s);+ return false;+ }+ }+Future<bool> _writeBackup({required _BackupTarget target,required String fileName,@@ -81,36 +120,84 @@ class LocalBackupService {}final scopedDir = Directory(target.path!);- // On iOS, create EnteAuthBackups subdirectory inside the user-selected folder+ // On iOS, saved path is the parent; we write to EnteAuthBackups subdirectoryfinal backupDir = Platform.isIOS? Directory('${scopedDir.path}/EnteAuthBackups'): scopedDir;- // On iOS, we need to access security-scoped resources for directories- // outside the app sandbox (e.g., user-selected folders).- if (Platform.isIOS) {- await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(scopedDir);- }-- try {+ 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.create(recursive: true);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;- } finally {- if (Platform.isIOS) {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(scopedDir);+ }++ // 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');+ }++ if (!hasAccess) {+ _logger+ .severe('iOS: All access methods failed for: ${scopedDir.path}');+ return false;+ }++ try {+ return await doWrite();+ } finally {+ if (usingBookmark && bookmark != null) {+ await SecurityBookmarkService.instance+ .stopAccessingBookmark(bookmark);+ } else {+ await SecurityScopedResource.instance+ .stopAccessingSecurityScopedResource(scopedDir);+ }}}++ return await doWrite();} catch (e, s) {- _logger.severe('Failed to write backup', e, s);+ _logger.severe('Failed to write backup: $e', e, s);return false;}}@@ -187,20 +274,14 @@ class LocalBackupService {}}- Future<void> deleteAllBackupsIn(String path) async {+ Future<void> deleteAllBackupsIn(String path, {String? iosBookmark}) async {try {final scopedDir = Directory(path);- // On iOS, backups are in EnteAuthBackups subdirectory+ // On iOS, saved path is the parent; backups are in EnteAuthBackups subdirectoryfinal backupDir =Platform.isIOS ? Directory('$path/EnteAuthBackups') : scopedDir;- // On iOS, we need to access security-scoped resources.- if (Platform.isIOS) {- await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(scopedDir);- }-- try {+ Future<void> doDelete() async {if (!await backupDir.exists()) {_logger.warning('Old backup directory not found. Nothing to delete.');return;@@ -225,11 +306,54 @@ class LocalBackupService {_logger.info('Deleted: ${file.path}');}_logger.info('Successfully cleaned up old backup location.');- } finally {- if (Platform.isIOS) {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(scopedDir);+ }++ // 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 {+ await doDelete();+ } finally {+ if (usingBookmark && iosBookmark != null) {+ await SecurityBookmarkService.instance+ .stopAccessingBookmark(iosBookmark);+ } else {+ await SecurityScopedResource.instance+ .stopAccessingSecurityScopedResource(scopedDir);+ }}+ } else {+ await doDelete();}} catch (e, s) {_logger.severe('Error during full backup cleanup of old directory', e, s);@@ -242,12 +366,13 @@ class LocalBackupService {_BackupTarget? _resolveTarget(SharedPreferences prefs) {final path = prefs.getString('autoBackupPath');final treeUri = prefs.getString('autoBackupTreeUri');+ final iosBookmark = prefs.getString(_iosBookmarkKey);if (treeUri != null && treeUri.isNotEmpty) {return _BackupTarget.saf(treeUri);}if (path != null && path.isNotEmpty) {- return _BackupTarget.file(path);+ return _BackupTarget.file(path, iosBookmark: iosBookmark);}return null;}@@ -336,11 +461,14 @@ class LocalBackupService {}class _BackupTarget {- const _BackupTarget.file(this.path) : treeUri = null;- const _BackupTarget.saf(this.treeUri) : path = null;+ const _BackupTarget.file(this.path, {this.iosBookmark}) : treeUri = null;+ const _BackupTarget.saf(this.treeUri)+ : path = null,+ iosBookmark = null;final String? path;final String? treeUri;+ final String? iosBookmark;bool get isSaf => treeUri != null;}diff --git a/mobile/apps/auth/lib/services/security_bookmark_service.dart b/mobile/apps/auth/lib/services/security_bookmark_service.dartnew file mode 100644index 0000000000..d1a036738c--- /dev/null+++ b/mobile/apps/auth/lib/services/security_bookmark_service.dart@@ -0,0 +1,182 @@+import 'dart:io';++import 'package:flutter/services.dart';+import 'package:logging/logging.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.+class SecurityBookmarkService {+ SecurityBookmarkService._();++ static final SecurityBookmarkService instance = SecurityBookmarkService._();+ static const _channel = MethodChannel('io.ente.auth/security_bookmark');+ final _logger = Logger('SecurityBookmarkService');++ /// Opens native iOS directory picker and creates a bookmark immediately.+ ///+ /// Returns a [DirectoryPickResult] with both path and bookmark, or null if cancelled.+ /// This is the preferred method on iOS as it creates the bookmark while we still+ /// have the security-scoped URL from the picker.+ 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;++ 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;+ }+ }++ /// Starts accessing a security-scoped resource using a stored bookmark.+ ///+ /// Returns a [BookmarkAccessResult] containing the success status,+ /// resolved path, and whether the bookmark is stale.+ ///+ /// You MUST call [stopAccessingBookmark] when done to balance the call.+ 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;+ }+ }++ /// Stops accessing a security-scoped resource.+ ///+ /// Always call this after you're done with file operations to+ /// balance the [startAccessingBookmark] call.+ 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;+ }+ }+}++class DirectoryPickResult {+ const DirectoryPickResult({+ required this.path,+ required this.bookmark,+ });++ final String path;+ 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,+ required this.path,+ required this.isStale,+ });++ final bool success;+ final String path;+ final bool isStale;+}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 18e70eebac..2170e4f982 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@@ -3,6 +3,7 @@ import 'dart:io';import 'package:ente_auth/l10n/l10n.dart';import 'package:ente_auth/services/local_backup_service.dart';import 'package:ente_auth/services/secure_storage_service.dart';+import 'package:ente_auth/services/security_bookmark_service.dart';import 'package:ente_auth/theme/ente_theme.dart';import 'package:ente_auth/ui/components/buttons/button_widget.dart';import 'package:ente_auth/ui/components/dialog_widget.dart';@@ -10,6 +11,7 @@ import 'package:ente_auth/ui/components/models/button_type.dart';import 'package:ente_lock_screen/local_authentication_service.dart';import 'package:file_picker/file_picker.dart';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';@@ -72,6 +74,8 @@ class LocalBackupExperienceController {class _LocalBackupExperienceState extends State<LocalBackupExperience> {static const _locationConfiguredKey = 'hasConfiguredBackupLocation';static const _treeUriKey = 'autoBackupTreeUri';+ static const _iosBookmarkKey = 'autoBackupIosBookmark';+ final _logger = Logger('LocalBackupExperience');bool _isBackupEnabled = false;String? _backupPath;@@ -172,25 +176,63 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {try {final hasPassword =await _ensurePasswordConfigured(disableOnCancel: false);- if (!hasPassword) return;+ if (!hasPassword) {+ _logger.info('Manual backup cancelled: no password configured');+ return;+ }final hasLocation = await _ensureBackupLocationSelected();- if (!hasLocation) return;+ if (!hasLocation) {+ _logger.info('Manual backup cancelled: no location selected');+ return;+ }++ // On iOS, check if we have a bookmark - if not, we need to re-pick+ if (Platform.isIOS) {+ final prefs = await SharedPreferences.getInstance();+ final bookmark = prefs.getString(_iosBookmarkKey);+ if (bookmark == null || bookmark.isEmpty) {+ _logger.warning(+ 'iOS: No bookmark found, need to re-select backup location',+ );+ if (showSnackBar) {+ _showSnackBar(context.l10n.selectFolderToContinue);+ }+ // Clear the path and prompt user to re-select+ await prefs.remove('autoBackupPath');+ if (mounted) {+ setState(() {+ _backupPath = null;+ });+ }+ final saved = await _pickAndSaveBackupLocation(+ requireSelection: true,+ shouldTriggerBackup: false,+ );+ if (!saved) {+ _logger.info('Manual backup cancelled: user did not select folder');+ return;+ }+ }+ }try {+ _logger.info('Starting manual backup...');final success = await LocalBackupService.instance.triggerAutomaticBackup(isManual: true);- if (!success && showSnackBar) {- _showSnackBar(context.l10n.somethingWentWrongPleaseTryAgain);+ _logger.info('Manual backup result: $success');+ if (showSnackBar) {+ _showSnackBar(+ success+ ? context.l10n.backupCreated+ : context.l10n.somethingWentWrongPleaseTryAgain,+ );}- } catch (_) {+ } catch (e) {+ _logger.severe('Manual backup failed with error: $e');if (showSnackBar) {_showSnackBar(context.l10n.somethingWentWrongPleaseTryAgain);}- return;- }- if (showSnackBar) {- _showSnackBar(context.l10n.backupCreated);}} finally {if (mounted) {@@ -226,6 +268,8 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {return true;}+ // On iOS, just check if we have a path configured.+ // Directory creation happens in the backup service with proper scoped access.var resolvedPath = _backupPath;if (resolvedPath == null || resolvedPath.isEmpty) {final saved = await _pickAndSaveBackupLocation(@@ -237,7 +281,9 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {}resolvedPath = _backupPath;}- if (resolvedPath != null && resolvedPath.isNotEmpty) {+ // On iOS, don't try to create directory here - it requires scoped access+ // which is handled by the backup service.+ if (!Platform.isIOS && resolvedPath != null && resolvedPath.isNotEmpty) {await Directory(resolvedPath).create(recursive: true);}return true;@@ -332,7 +378,9 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {Future<bool> _hasStoredPassword() async {final stored = await _readStoredPassword();- return stored != null && stored.isNotEmpty;+ final hasPassword = stored != null && stored.isNotEmpty;+ _logger.info('_hasStoredPassword check: $hasPassword');+ return hasPassword;}Future<bool> _clearBackupPassword() async {@@ -347,9 +395,14 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {Future<String?> _readStoredPassword() async {try {- return SecureStorageService.instance+ final password = await SecureStorageService.instance.read(SecureStorageService.autoBackupPasswordKey);- } catch (_) {+ _logger.info(+ '_readStoredPassword: ${password != null ? "found (length: ${password.length})" : "null"}',+ );+ return password;+ } catch (e) {+ _logger.severe('_readStoredPassword error: $e');return null;}}@@ -361,6 +414,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {final prefs = await SharedPreferences.getInstance();await prefs.remove('autoBackupPath');await prefs.remove(_treeUriKey);+ await prefs.remove(_iosBookmarkKey);await prefs.remove(_locationConfiguredKey);if (!mounted) return false;setState(() {@@ -530,9 +584,14 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {);if (result?.action == ButtonAction.second) {- final pickedPath = await FilePicker.platform.getDirectoryPath();- if (pickedPath != null) {- final saved = await _persistLocation(pickedPath);+ // Use our native picker that creates bookmark immediately+ final pickResult = await SecurityBookmarkService.instance+ .pickDirectoryAndCreateBookmark();+ if (pickResult != null) {+ final saved = await _persistLocationWithBookmark(+ pickResult.path,+ pickResult.bookmark,+ );if (saved) {final backupSuccess = await LocalBackupService.instance.triggerAutomaticBackup(isManual: true);@@ -665,7 +724,30 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {_showSnackBar(context.l10n.selectFolderToContinue);}return saved;+ } else if (Platform.isIOS) {+ // On iOS, use our native picker that creates bookmark immediately+ final result = await SecurityBookmarkService.instance+ .pickDirectoryAndCreateBookmark();+ if (result != null) {+ final saved = await _persistLocationWithBookmark(+ result.path,+ result.bookmark,+ successMessage:+ successMessage ?? context.l10n.locationUpdatedAndBackupCreated,+ );+ if (saved && shouldTriggerBackup) {+ await LocalBackupService.instance.triggerAutomaticBackup(+ isManual: true,+ );+ }+ return saved;+ }+ if (requireSelection) {+ _showSnackBar(context.l10n.selectFolderToContinue);+ }+ return false;} else {+ // Other platforms (macOS, etc.)String? directoryPath = await FilePicker.platform.getDirectoryPath();if (directoryPath != null) {@@ -690,6 +772,60 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {}}+ /// iOS-specific: Persist location with pre-created bookmark+ Future<bool> _persistLocationWithBookmark(+ String path,+ String bookmark, {+ String? successMessage,+ }) async {+ final prefs = await SharedPreferences.getInstance();+ try {+ _logger.info('iOS: Using pre-created bookmark for: $path');++ // Start accessing using the bookmark+ final accessResult = await SecurityBookmarkService.instance+ .startAccessingBookmark(bookmark);+ if (accessResult == null || !accessResult.success) {+ _logger.severe('iOS: Failed to start accessing bookmark');+ return false;+ }+ _logger.info('iOS: Scoped access granted via bookmark');++ try {+ final backupDir = Directory('$path/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 {+ await SecurityBookmarkService.instance.stopAccessingBookmark(bookmark);+ }++ // Save both the path (for display) and bookmark (for access)+ _logger.info('iOS: Saving backup path and bookmark to preferences');+ await prefs.setString('autoBackupPath', path);+ await prefs.setString(_iosBookmarkKey, bookmark);+ await prefs.remove(_treeUriKey);+ await prefs.setBool(_locationConfiguredKey, true);+ if (!mounted) return false;+ setState(() {+ _backupPath = path;+ _backupTreeUri = null;+ });++ if (successMessage != null) {+ _showSnackBar(successMessage);+ }+ return true;+ } catch (e, s) {+ _logger.severe('Failed to persist iOS location with bookmark', e, s);+ return false;+ }+ }+Future<bool> _persistLocation(String path, {String? successMessage,@@ -697,13 +833,87 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {final prefs = await SharedPreferences.getInstance();Future<bool> savePath(String target) async {try {- // On iOS, we need security-scoped access to the user-selected directoryif (Platform.isIOS) {- await SecurityScopedResource.instance- .startAccessingSecurityScopedResource(Directory(target));- }+ // 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');+ }- try {+ 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;+ });+ } else {+ // Non-iOS: just save the path directlyawait Directory(target).create(recursive: true);await prefs.setString('autoBackupPath', target);await prefs.remove(_treeUriKey);@@ -713,21 +923,19 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {_backupPath = target;_backupTreeUri = null;});- if (successMessage != null) {- _showSnackBar(successMessage);- }- return true;- } finally {- if (Platform.isIOS) {- await SecurityScopedResource.instance- .stopAccessingSecurityScopedResource(Directory(target));- }}- } catch (_) {++ if (successMessage != null) {+ _showSnackBar(successMessage);+ }+ return true;+ } catch (e, s) {+ _logger.severe('Failed to save backup path: $target', e, s);return false;}}+ _logger.info('Attempting to save backup path: $path');if (await savePath(path)) {return true;}@@ -735,6 +943,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {if (Platform.isAndroid) {final fallbackPath = await _androidPrivateBackupPath();if (fallbackPath != null && fallbackPath != path) {+ _logger.info('Primary path failed, trying fallback: $fallbackPath');final savedFallback = await savePath(fallbackPath);if (savedFallback) {return true;@@ -742,6 +951,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {}}+ _logger.warning('All backup path options failed for: $path');_showSnackBar(context.l10n.noDefaultBackupFolder);return false;}