Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[auth] add macOS security-scoped bookmark support for local backups

Prateek Sunalcd47ad51a704
diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dart
index 2afd8c5188..1a780c7843 100644
--- a/mobile/apps/auth/lib/services/local_backup_service.dart
+++ b/mobile/apps/auth/lib/services/local_backup_service.dart
@@ -153,15 +153,15 @@ class LocalBackupService {
return success;
}
- // iOS with bookmark - write directly to the selected directory
- if (Platform.isIOS && target.iosBookmark != null) {
+ // iOS/macOS with bookmark - write directly to the selected directory
+ if ((Platform.isIOS || Platform.isMacOS) && target.iosBookmark != null) {
final dir = PickedDirectory(
path: target.path!,
bookmark: target.iosBookmark,
);
final result = await dirUtils.withAccess(dir, (path) async {
final success = await dirUtils.writeFile(
- PickedDirectory(path: path),
+ PickedDirectory(path: path, bookmark: target.iosBookmark),
fileName,
contentBytes,
);
@@ -173,7 +173,7 @@ class LocalBackupService {
return result ?? false;
}
- // Other platforms: direct file write
+ // Other platforms (Windows, Linux): direct file write
final basePath = target.path!;
await Directory(basePath).create(recursive: true);
final filePath = '$basePath/$fileName';
@@ -270,8 +270,10 @@ class LocalBackupService {
}
}
- // On iOS, use scoped access via bookmark
- if (Platform.isIOS && iosBookmark != null && iosBookmark.isNotEmpty) {
+ // On iOS/macOS, use scoped access via bookmark
+ if ((Platform.isIOS || Platform.isMacOS) &&
+ iosBookmark != null &&
+ iosBookmark.isNotEmpty) {
final dir = PickedDirectory(path: path, bookmark: iosBookmark);
await dirUtils.withAccess(dir, (_) async {
await doDelete();
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.dart
index fc1c4f9b63..622c057128 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
@@ -182,13 +182,13 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
return;
}
- // On iOS, check if we have a bookmark - if not, we need to re-pick
- if (Platform.isIOS) {
+ // On iOS/macOS, check if we have a bookmark - if not, we need to re-pick
+ if (Platform.isIOS || Platform.isMacOS) {
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',
+ '${Platform.operatingSystem}: No bookmark found, need to re-select backup location',
);
if (showSnackBar) {
_showSnackBar(context.l10n.selectFolderToContinue);
@@ -261,7 +261,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
return true;
}
- // On iOS, just check if we have a path configured.
+ // On iOS/macOS, 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) {
@@ -274,9 +274,12 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
resolvedPath = _backupPath;
}
- // On iOS, don't try to create directory here - it requires scoped access
+ // On iOS/macOS, 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) {
+ if (!Platform.isIOS &&
+ !Platform.isMacOS &&
+ resolvedPath != null &&
+ resolvedPath.isNotEmpty) {
await Directory(resolvedPath).create(recursive: true);
}
return true;
@@ -589,6 +592,20 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
return false;
}
+ if (Platform.isMacOS) {
+ // On macOS, use DirUtils which creates a security-scoped bookmark
+ final picked = await DirUtils.instance.pickDirectory();
+ if (picked != null && picked.path.isNotEmpty && picked.bookmark != null) {
+ return _persistLocationWithBookmark(
+ picked.path,
+ picked.bookmark!,
+ successMessage: context.l10n.initialBackupCreated,
+ );
+ }
+ return false;
+ }
+
+ // Other platforms (Windows, Linux, etc.)
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty) {
return _persistLocation(
@@ -726,8 +743,24 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
_showSnackBar(context.l10n.selectFolderToContinue);
}
return false;
+ } else if (Platform.isMacOS) {
+ // On macOS, use DirUtils which creates a security-scoped bookmark
+ final picked = await DirUtils.instance.pickDirectory();
+ if (picked != null && picked.path.isNotEmpty && picked.bookmark != null) {
+ final saved = await _persistLocationWithBookmark(
+ picked.path,
+ picked.bookmark!,
+ successMessage:
+ successMessage ?? context.l10n.locationUpdatedAndBackupCreated,
+ );
+ return saved;
+ }
+ if (requireSelection) {
+ _showSnackBar(context.l10n.selectFolderToContinue);
+ }
+ return false;
} else {
- // Other platforms (macOS, etc.)
+ // Other platforms (Windows, Linux, etc.)
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty) {
@@ -752,19 +785,23 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
}
- /// iOS-specific: Persist location with pre-created bookmark
+ /// iOS/macOS: Persist location with pre-created bookmark
Future<bool> _persistLocationWithBookmark(
String path,
String bookmark, {
String? successMessage,
}) async {
final prefs = await SharedPreferences.getInstance();
+ final dirUtils = DirUtils.instance;
+ final pickedDir = PickedDirectory(path: path, bookmark: bookmark);
+
try {
// Start accessing using the bookmark
- final accessResult = await SecurityBookmarkService.instance
- .startAccessingBookmark(bookmark);
+ final accessResult = await dirUtils.startAccess(pickedDir);
if (accessResult == null || !accessResult.success) {
- _logger.severe('iOS: Failed to start accessing bookmark for: $path');
+ _logger.severe(
+ '${Platform.operatingSystem}: Failed to start accessing bookmark for: $path',
+ );
return false;
}
@@ -772,7 +809,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
// Write backup directly to the selected directory
await LocalBackupService.instance.writeBackupToDirectory(path);
} finally {
- await SecurityBookmarkService.instance.stopAccessingBookmark(bookmark);
+ await dirUtils.stopAccess(pickedDir);
}
await prefs.setString('autoBackupPath', path);
@@ -790,7 +827,11 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
return true;
} catch (e, s) {
- _logger.severe('Failed to persist iOS location with bookmark', e, s);
+ _logger.severe(
+ 'Failed to persist ${Platform.operatingSystem} location with bookmark',
+ e,
+ s,
+ );
return false;
}
}
@@ -802,12 +843,12 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
final prefs = await SharedPreferences.getInstance();
Future<bool> savePath(String target) async {
try {
- if (Platform.isIOS) {
- // On iOS, use native picker with bookmark via _persistLocationWithBookmark.
+ if (Platform.isIOS || Platform.isMacOS) {
+ // On iOS/macOS, 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.',
+ '${Platform.operatingSystem}: _persistLocation called without bookmark. '
+ 'Use native picker for ${Platform.operatingSystem}.',
);
return false;
} else {
diff --git a/mobile/apps/auth/macos/Flutter/GeneratedPluginRegistrant.swift b/mobile/apps/auth/macos/Flutter/GeneratedPluginRegistrant.swift
index 252cea1b9d..abf9bc2f97 100644
--- a/mobile/apps/auth/macos/Flutter/GeneratedPluginRegistrant.swift
+++ b/mobile/apps/auth/macos/Flutter/GeneratedPluginRegistrant.swift
@@ -8,6 +8,7 @@ import Foundation
import app_links
import connectivity_plus
import device_info_plus
+import dir_utils
import file_picker
import file_saver
import flutter_inappwebview_macos
@@ -32,6 +33,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin"))
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
+ DirUtilsPlugin.register(with: registry.registrar(forPlugin: "DirUtilsPlugin"))
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
FileSaverPlugin.register(with: registry.registrar(forPlugin: "FileSaverPlugin"))
InAppWebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "InAppWebViewFlutterPlugin"))
diff --git a/mobile/apps/auth/macos/Podfile.lock b/mobile/apps/auth/macos/Podfile.lock
index 2f62e9ebf8..107e33493b 100644
--- a/mobile/apps/auth/macos/Podfile.lock
+++ b/mobile/apps/auth/macos/Podfile.lock
@@ -8,6 +8,8 @@ PODS:
- FlutterMacOS
- device_info_plus (0.0.1):
- FlutterMacOS
+ - dir_utils (1.0.0):
+ - FlutterMacOS
- file_picker (0.0.1):
- FlutterMacOS
- file_saver (0.0.1):
@@ -84,6 +86,7 @@ DEPENDENCIES:
- connectivity_plus (from `Flutter/ephemeral/.symlinks/plugins/connectivity_plus/macos`)
- cupertino_http (from `Flutter/ephemeral/.symlinks/plugins/cupertino_http/darwin`)
- device_info_plus (from `Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos`)
+ - dir_utils (from `Flutter/ephemeral/.symlinks/plugins/dir_utils/macos`)
- file_picker (from `Flutter/ephemeral/.symlinks/plugins/file_picker/macos`)
- file_saver (from `Flutter/ephemeral/.symlinks/plugins/file_saver/macos`)
- flutter_inappwebview_macos (from `Flutter/ephemeral/.symlinks/plugins/flutter_inappwebview_macos/macos`)
@@ -121,6 +124,8 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/cupertino_http/darwin
device_info_plus:
:path: Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos
+ dir_utils:
+ :path: Flutter/ephemeral/.symlinks/plugins/dir_utils/macos
file_picker:
:path: Flutter/ephemeral/.symlinks/plugins/file_picker/macos
file_saver:
@@ -169,6 +174,7 @@ SPEC CHECKSUMS:
connectivity_plus: 4adf20a405e25b42b9c9f87feff8f4b6fde18a4e
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
device_info_plus: b0fafc687fb901e2af612763340f1b0d4352f8e5
+ dir_utils: 632f90d78e628e9474b549235fe0f8eab79cf7c2
file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a
file_saver: e35bd97de451dde55ff8c38862ed7ad0f3418d0f
flutter_inappwebview_macos: c2d68649f9f8f1831bfcd98d73fd6256366d9d1d
diff --git a/mobile/apps/auth/macos/Runner/DebugProfile.entitlements b/mobile/apps/auth/macos/Runner/DebugProfile.entitlements
index 094be41732..7fd3249a10 100644
--- a/mobile/apps/auth/macos/Runner/DebugProfile.entitlements
+++ b/mobile/apps/auth/macos/Runner/DebugProfile.entitlements
@@ -12,6 +12,8 @@
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
+ <key>com.apple.security.files.bookmarks.app-scope</key>
+ <true/>
<key>keychain-access-groups</key>
<array/>
<key>com.apple.security.files.downloads.read-write</key>
diff --git a/mobile/apps/auth/macos/Runner/Release.entitlements b/mobile/apps/auth/macos/Runner/Release.entitlements
index f9f0dc66a2..27aed6bb2d 100644
--- a/mobile/apps/auth/macos/Runner/Release.entitlements
+++ b/mobile/apps/auth/macos/Runner/Release.entitlements
@@ -8,6 +8,8 @@
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
+ <key>com.apple.security.files.bookmarks.app-scope</key>
+ <true/>
<key>com.apple.security.network.client</key>
<true/>
<key>keychain-access-groups</key>
diff --git a/mobile/packages/dir_utils/lib/dir_utils.dart b/mobile/packages/dir_utils/lib/dir_utils.dart
index 7b51093fb0..973106ac93 100644
--- a/mobile/packages/dir_utils/lib/dir_utils.dart
+++ b/mobile/packages/dir_utils/lib/dir_utils.dart
@@ -32,7 +32,8 @@ class PickedDirectory {
/// Android SAF tree URI. Null on other platforms.
final String? treeUri;
- bool get isIos => bookmark != null;
+ /// Returns true if this directory has a security-scoped bookmark (iOS or macOS).
+ bool get hasBookmark => bookmark != null;
bool get isAndroid => treeUri != null;
}
@@ -94,6 +95,8 @@ class DirUtils {
return _pickDirectoryIos();
} else if (Platform.isAndroid) {
return _pickDirectoryAndroid();
+ } else if (Platform.isMacOS) {
+ return _pickDirectoryMacOS();
} else {
return _pickDirectoryOther();
}
@@ -140,6 +143,40 @@ class DirUtils {
}
}
+ Future<PickedDirectory?> _pickDirectoryMacOS() async {
+ try {
+ // Use file_picker to pick the directory
+ final path = await FilePicker.platform.getDirectoryPath();
+ if (path == null) return null;
+
+ // Create a security-scoped bookmark from the picked path
+ // This must be done while we still have access (same session as picker)
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'createBookmarkFromPath',
+ {'path': path},
+ );
+
+ if (result == null) {
+ _logger.severe('macOS: Failed to create bookmark for path: $path');
+ return null;
+ }
+
+ final bookmark = result['bookmark'] as String?;
+ if (bookmark == null) {
+ _logger.severe('macOS: Invalid result from createBookmarkFromPath');
+ return null;
+ }
+
+ return PickedDirectory(path: path, bookmark: bookmark);
+ } on PlatformException catch (e) {
+ _logger.severe('macOS: Failed to pick directory: ${e.message}');
+ return null;
+ } catch (e) {
+ _logger.severe('macOS: Failed to pick directory: $e');
+ return null;
+ }
+ }
+
Future<PickedDirectory?> _pickDirectoryOther() async {
try {
final path = await FilePicker.platform.getDirectoryPath();
@@ -153,20 +190,22 @@ class DirUtils {
}
// ============================================================
- // Security-Scoped Access (iOS only)
+ // Security-Scoped Access (iOS/macOS)
// ============================================================
- /// Start accessing a security-scoped resource (iOS only).
+ /// Start accessing a security-scoped resource (iOS/macOS).
///
/// You MUST call [stopAccess] when done to balance this call.
- /// On non-iOS platforms, this is a no-op that returns success.
+ /// On platforms without bookmark support, this is a no-op that returns success.
Future<AccessResult?> startAccess(PickedDirectory dir) async {
- if (!Platform.isIOS) {
+ if (!Platform.isIOS && !Platform.isMacOS) {
return AccessResult(success: true, path: dir.path, isStale: false);
}
if (dir.bookmark == null) {
- _logger.severe('iOS: No bookmark available for startAccess');
+ _logger.severe(
+ '${Platform.operatingSystem}: No bookmark available for startAccess',
+ );
return null;
}
@@ -183,19 +222,22 @@ class DirUtils {
isStale: result['isStale'] as bool,
);
} on PlatformException catch (e) {
- _logger.severe('iOS: Failed to start access: ${e.message}');
+ _logger
+ .severe('${Platform.operatingSystem}: Failed to start access: $e');
return null;
}
}
- /// Stop accessing a security-scoped resource (iOS only).
+ /// Stop accessing a security-scoped resource (iOS/macOS).
///
- /// On non-iOS platforms, this is a no-op.
+ /// On platforms without bookmark support, this is a no-op.
Future<bool> stopAccess(PickedDirectory dir) async {
- if (!Platform.isIOS) return true;
+ if (!Platform.isIOS && !Platform.isMacOS) return true;
if (dir.bookmark == null) {
- _logger.severe('iOS: No bookmark available for stopAccess');
+ _logger.severe(
+ '${Platform.operatingSystem}: No bookmark available for stopAccess',
+ );
return false;
}
@@ -206,7 +248,8 @@ class DirUtils {
);
return result ?? false;
} on PlatformException catch (e) {
- _logger.severe('iOS: Failed to stop access: ${e.message}');
+ _logger
+ .severe('${Platform.operatingSystem}: Failed to stop access: $e');
return false;
}
}
@@ -214,7 +257,7 @@ class DirUtils {
/// Execute a function with security-scoped access.
///
/// Automatically calls startAccess before and stopAccess after.
- /// On non-iOS platforms, just executes the function directly.
+ /// On platforms without bookmark support, just executes the function directly.
Future<T?> withAccess<T>(
PickedDirectory dir,
Future<T> Function(String path) action,
@@ -250,8 +293,8 @@ class DirUtils {
}) async {
if (Platform.isAndroid && dir.treeUri != null) {
return _writeFileAndroid(dir.treeUri!, fileName, content);
- } else if (Platform.isIOS && dir.bookmark != null) {
- return _writeFileIos(dir, fileName, content, subPath: subPath);
+ } else if ((Platform.isIOS || Platform.isMacOS) && dir.bookmark != null) {
+ return _writeFileWithBookmark(dir, fileName, content, subPath: subPath);
} else {
return _writeFileOther(dir.path, fileName, content, subPath: subPath);
}
@@ -278,7 +321,7 @@ class DirUtils {
}
}
- Future<bool> _writeFileIos(
+ Future<bool> _writeFileWithBookmark(
PickedDirectory dir,
String fileName,
Uint8List content, {
@@ -294,7 +337,9 @@ class DirUtils {
);
return result ?? false;
} on PlatformException catch (e) {
- _logger.severe('iOS: Failed to write file: ${e.message}');
+ _logger.severe(
+ '${Platform.operatingSystem}: Failed to write file: ${e.message}',
+ );
return false;
}
}
@@ -323,8 +368,8 @@ class DirUtils {
}) async {
if (Platform.isAndroid && dir.treeUri != null) {
return _listFilesAndroid(dir.treeUri!);
- } else if (Platform.isIOS && dir.bookmark != null) {
- return _listFilesIos(dir, subPath: subPath);
+ } else if ((Platform.isIOS || Platform.isMacOS) && dir.bookmark != null) {
+ return _listFilesWithBookmark(dir, subPath: subPath);
} else {
return _listFilesOther(dir.path, subPath: subPath);
}
@@ -351,7 +396,7 @@ class DirUtils {
}
}
- Future<List<FileInfo>> _listFilesIos(
+ Future<List<FileInfo>> _listFilesWithBookmark(
PickedDirectory dir, {
String? subPath,
}) async {
@@ -375,7 +420,9 @@ class DirUtils {
);
}).toList();
} on PlatformException catch (e) {
- _logger.severe('iOS: Failed to list files: ${e.message}');
+ _logger.severe(
+ '${Platform.operatingSystem}: Failed to list files: ${e.message}',
+ );
return [];
}
}
@@ -431,7 +478,7 @@ class DirUtils {
Future<bool> _deleteFileOther(String path) async {
try {
- if (Platform.isIOS) {
+ if (Platform.isIOS || Platform.isMacOS) {
final result = await _channel.invokeMethod<bool>(
'deleteFile',
{'path': path},
diff --git a/mobile/packages/dir_utils/macos/Classes/DirUtilsPlugin.swift b/mobile/packages/dir_utils/macos/Classes/DirUtilsPlugin.swift
new file mode 100644
index 0000000000..d9dfc06b4f
--- /dev/null
+++ b/mobile/packages/dir_utils/macos/Classes/DirUtilsPlugin.swift
@@ -0,0 +1,260 @@
+import FlutterMacOS
+import Foundation
+
+public class DirUtilsPlugin: NSObject, FlutterPlugin {
+ public static func register(with registrar: FlutterPluginRegistrar) {
+ let channel = FlutterMethodChannel(
+ name: "io.ente.dir_utils",
+ binaryMessenger: registrar.messenger
+ )
+ let instance = DirUtilsPlugin()
+ registrar.addMethodCallDelegate(instance, channel: channel)
+ }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case "createBookmarkFromPath":
+ handleCreateBookmarkFromPath(call: call, result: result)
+ case "startAccess":
+ handleStartAccess(call: call, result: result)
+ case "stopAccess":
+ handleStopAccess(call: call, result: result)
+ case "writeFile":
+ handleWriteFile(call: call, result: result)
+ case "readFile":
+ handleReadFile(call: call, result: result)
+ case "deleteFile":
+ handleDeleteFile(call: call, result: result)
+ case "listFiles":
+ handleListFiles(call: call, result: result)
+ case "exists":
+ handleExists(call: call, result: result)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
+ // MARK: - Bookmark Creation
+
+ /// Creates a security-scoped bookmark from a path that was obtained from a file picker.
+ /// This must be called while the app still has access (during the same session as the picker).
+ private func handleCreateBookmarkFromPath(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)
+
+ do {
+ // On macOS, we must use .withSecurityScope for app-scoped bookmarks
+ let bookmarkData = try url.bookmarkData(
+ options: .withSecurityScope,
+ includingResourceValuesForKeys: nil,
+ relativeTo: nil
+ )
+
+ let base64Bookmark = bookmarkData.base64EncodedString()
+ NSLog("DirUtilsPlugin (macOS): Bookmark created successfully for path: \(path), length: \(base64Bookmark.count)")
+
+ result([
+ "path": url.path,
+ "bookmark": base64Bookmark
+ ])
+ } catch {
+ NSLog("DirUtilsPlugin (macOS): Failed to create bookmark: \(error)")
+ result(FlutterError(
+ code: "BOOKMARK_ERROR",
+ message: "Failed to create bookmark: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ // MARK: - Security-Scoped Access
+
+ private func handleStartAccess(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
+ // On macOS, we must use .withSecurityScope when resolving
+ let url = try URL(
+ resolvingBookmarkData: bookmarkData,
+ options: .withSecurityScope,
+ relativeTo: nil,
+ bookmarkDataIsStale: &isStale
+ )
+
+ // Critical: must call startAccessingSecurityScopedResource on the resolved URL
+ let success = url.startAccessingSecurityScopedResource()
+ NSLog("DirUtilsPlugin (macOS): startAccess for \(url.path), success: \(success), isStale: \(isStale)")
+
+ result([
+ "success": success,
+ "path": url.path,
+ "isStale": isStale
+ ])
+ } catch {
+ NSLog("DirUtilsPlugin (macOS): Failed to start access: \(error)")
+ result(FlutterError(
+ code: "ACCESS_ERROR",
+ message: "Failed to start access: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ private func handleStopAccess(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: .withSecurityScope,
+ relativeTo: nil,
+ bookmarkDataIsStale: &isStale
+ )
+
+ url.stopAccessingSecurityScopedResource()
+ NSLog("DirUtilsPlugin (macOS): stopAccess for \(url.path)")
+ result(true)
+ } catch {
+ NSLog("DirUtilsPlugin (macOS): Failed to stop access: \(error)")
+ result(FlutterError(
+ code: "ACCESS_ERROR",
+ message: "Failed to stop access: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ // MARK: - File Operations
+
+ private func handleWriteFile(call: FlutterMethodCall, result: @escaping FlutterResult) {
+ guard let args = call.arguments as? [String: Any],
+ let path = args["path"] as? String,
+ let content = args["content"] as? FlutterStandardTypedData else {
+ result(FlutterError(code: "INVALID_ARGS", message: "Missing 'path' or 'content' argument", details: nil))
+ return
+ }
+
+ let url = URL(fileURLWithPath: path)
+
+ do {
+ try content.data.write(to: url)
+ result(true)
+ } catch {
+ result(FlutterError(
+ code: "WRITE_ERROR",
+ message: "Failed to write file: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ private func handleReadFile(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)
+
+ do {
+ let data = try Data(contentsOf: url)
+ result(FlutterStandardTypedData(bytes: data))
+ } catch {
+ result(FlutterError(
+ code: "READ_ERROR",
+ message: "Failed to read file: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ private func handleDeleteFile(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)
+
+ do {
+ try FileManager.default.removeItem(at: url)
+ result(true)
+ } catch {
+ result(FlutterError(
+ code: "DELETE_ERROR",
+ message: "Failed to delete: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ private func handleListFiles(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)
+
+ do {
+ let contents = try FileManager.default.contentsOfDirectory(
+ at: url,
+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],
+ options: [.skipsHiddenFiles]
+ )
+
+ var files: [[String: Any]] = []
+ for fileURL in contents {
+ let resourceValues = try fileURL.resourceValues(forKeys: [.isDirectoryKey, .contentModificationDateKey])
+ let isDirectory = resourceValues.isDirectory ?? false
+ let modDate = resourceValues.contentModificationDate ?? Date()
+
+ files.append([
+ "name": fileURL.lastPathComponent,
+ "path": fileURL.path,
+ "isDirectory": isDirectory,
+ "lastModified": Int64(modDate.timeIntervalSince1970 * 1000)
+ ])
+ }
+
+ result(files)
+ } catch {
+ result(FlutterError(
+ code: "LIST_ERROR",
+ message: "Failed to list files: \(error.localizedDescription)",
+ details: nil
+ ))
+ }
+ }
+
+ private func handleExists(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 exists = FileManager.default.fileExists(atPath: path)
+ result(exists)
+ }
+}
diff --git a/mobile/packages/dir_utils/macos/dir_utils.podspec b/mobile/packages/dir_utils/macos/dir_utils.podspec
new file mode 100644
index 0000000000..9e617cdaf8
--- /dev/null
+++ b/mobile/packages/dir_utils/macos/dir_utils.podspec
@@ -0,0 +1,19 @@
+Pod::Spec.new do |s|
+ s.name = 'dir_utils'
+ s.version = '1.0.0'
+ s.summary = 'Cross-platform directory utilities with persistent access support'
+ s.description = <<-DESC
+Cross-platform directory utilities providing security-scoped bookmark support on macOS
+for persistent file access to user-selected directories outside the app sandbox.
+ DESC
+ s.homepage = 'https://github.com/ente-io/ente'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Ente' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'Classes/**/*'
+ s.dependency 'FlutterMacOS'
+ s.platform = :osx, '10.14'
+ s.swift_version = '5.0'
+
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
+end
diff --git a/mobile/packages/dir_utils/pubspec.yaml b/mobile/packages/dir_utils/pubspec.yaml
index 2be34999e9..5e159c632e 100644
--- a/mobile/packages/dir_utils/pubspec.yaml
+++ b/mobile/packages/dir_utils/pubspec.yaml
@@ -25,3 +25,5 @@ flutter:
platforms:
ios:
pluginClass: DirUtilsPlugin
+ macos:
+ pluginClass: DirUtilsPlugin