react-native-cloud-sync 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +75 -86
  2. package/ios/CloudSyncError.swift +21 -0
  3. package/ios/CloudSyncImpl.swift +515 -95
  4. package/ios/RNCloudSync.mm +73 -1
  5. package/jest-mock.js +1 -0
  6. package/lib/commonjs/hooks.js +73 -9
  7. package/lib/commonjs/hooks.js.map +1 -1
  8. package/lib/commonjs/internal/autoFlush.js +10 -1
  9. package/lib/commonjs/internal/autoFlush.js.map +1 -1
  10. package/lib/commonjs/internal/base64.js +25 -5
  11. package/lib/commonjs/internal/base64.js.map +1 -1
  12. package/lib/commonjs/internal/cloudKitRest.js +91 -15
  13. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  14. package/lib/commonjs/internal/googleDriveRest.js +304 -38
  15. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  16. package/lib/commonjs/internal/keys.js +34 -17
  17. package/lib/commonjs/internal/keys.js.map +1 -1
  18. package/lib/commonjs/internal/records.js +48 -0
  19. package/lib/commonjs/internal/records.js.map +1 -0
  20. package/lib/commonjs/providers/cloudKit.js +85 -17
  21. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  22. package/lib/commonjs/providers/cloudKitEncrypted.js +30 -7
  23. package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -1
  24. package/lib/commonjs/providers/googleDrive.js +37 -2
  25. package/lib/commonjs/providers/googleDrive.js.map +1 -1
  26. package/lib/commonjs/providers/icloudDocuments.js +27 -0
  27. package/lib/commonjs/providers/icloudDocuments.js.map +1 -1
  28. package/lib/commonjs/providers/icloudKV.js +13 -3
  29. package/lib/commonjs/providers/icloudKV.js.map +1 -1
  30. package/lib/commonjs/providers/icloudKV.web.js +8 -1
  31. package/lib/commonjs/providers/icloudKV.web.js.map +1 -1
  32. package/lib/commonjs/providers/memory.js +10 -0
  33. package/lib/commonjs/providers/memory.js.map +1 -1
  34. package/lib/commonjs/resolvers.js +27 -13
  35. package/lib/commonjs/resolvers.js.map +1 -1
  36. package/lib/commonjs/specs/NativeRNCloudSync.js +3 -0
  37. package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -1
  38. package/lib/commonjs/store.js +360 -173
  39. package/lib/commonjs/store.js.map +1 -1
  40. package/lib/commonjs/types.js.map +1 -1
  41. package/lib/module/hooks.js +73 -9
  42. package/lib/module/hooks.js.map +1 -1
  43. package/lib/module/internal/autoFlush.js +10 -1
  44. package/lib/module/internal/autoFlush.js.map +1 -1
  45. package/lib/module/internal/base64.js +25 -5
  46. package/lib/module/internal/base64.js.map +1 -1
  47. package/lib/module/internal/cloudKitRest.js +89 -13
  48. package/lib/module/internal/cloudKitRest.js.map +1 -1
  49. package/lib/module/internal/googleDriveRest.js +304 -38
  50. package/lib/module/internal/googleDriveRest.js.map +1 -1
  51. package/lib/module/internal/keys.js +33 -17
  52. package/lib/module/internal/keys.js.map +1 -1
  53. package/lib/module/internal/records.js +41 -0
  54. package/lib/module/internal/records.js.map +1 -0
  55. package/lib/module/providers/cloudKit.js +86 -18
  56. package/lib/module/providers/cloudKit.js.map +1 -1
  57. package/lib/module/providers/cloudKitEncrypted.js +31 -8
  58. package/lib/module/providers/cloudKitEncrypted.js.map +1 -1
  59. package/lib/module/providers/googleDrive.js +37 -2
  60. package/lib/module/providers/googleDrive.js.map +1 -1
  61. package/lib/module/providers/icloudDocuments.js +28 -1
  62. package/lib/module/providers/icloudDocuments.js.map +1 -1
  63. package/lib/module/providers/icloudKV.js +13 -3
  64. package/lib/module/providers/icloudKV.js.map +1 -1
  65. package/lib/module/providers/icloudKV.web.js +8 -1
  66. package/lib/module/providers/icloudKV.web.js.map +1 -1
  67. package/lib/module/providers/memory.js +10 -0
  68. package/lib/module/providers/memory.js.map +1 -1
  69. package/lib/module/resolvers.js +27 -12
  70. package/lib/module/resolvers.js.map +1 -1
  71. package/lib/module/specs/NativeRNCloudSync.js +4 -0
  72. package/lib/module/specs/NativeRNCloudSync.js.map +1 -1
  73. package/lib/module/store.js +360 -173
  74. package/lib/module/store.js.map +1 -1
  75. package/lib/module/types.js.map +1 -1
  76. package/lib/typescript/commonjs/errors.d.ts +16 -16
  77. package/lib/typescript/commonjs/errors.d.ts.map +1 -1
  78. package/lib/typescript/commonjs/hooks.d.ts.map +1 -1
  79. package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -1
  80. package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -1
  81. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +20 -0
  82. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  83. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +19 -0
  84. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  85. package/lib/typescript/commonjs/internal/keys.d.ts +18 -3
  86. package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -1
  87. package/lib/typescript/commonjs/internal/records.d.ts +24 -0
  88. package/lib/typescript/commonjs/internal/records.d.ts.map +1 -0
  89. package/lib/typescript/commonjs/providers/cloudKit.d.ts +1 -1
  90. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  91. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +1 -1
  92. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -1
  93. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -1
  94. package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -1
  95. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -1
  96. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +1 -1
  97. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -1
  98. package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -1
  99. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -1
  100. package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -1
  101. package/lib/typescript/commonjs/resolvers.d.ts +6 -3
  102. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -1
  103. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +12 -3
  104. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -1
  105. package/lib/typescript/commonjs/store.d.ts.map +1 -1
  106. package/lib/typescript/commonjs/types.d.ts +31 -3
  107. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  108. package/lib/typescript/module/errors.d.ts +16 -16
  109. package/lib/typescript/module/errors.d.ts.map +1 -1
  110. package/lib/typescript/module/hooks.d.ts.map +1 -1
  111. package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -1
  112. package/lib/typescript/module/internal/base64.d.ts.map +1 -1
  113. package/lib/typescript/module/internal/cloudKitRest.d.ts +20 -0
  114. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  115. package/lib/typescript/module/internal/googleDriveRest.d.ts +19 -0
  116. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  117. package/lib/typescript/module/internal/keys.d.ts +18 -3
  118. package/lib/typescript/module/internal/keys.d.ts.map +1 -1
  119. package/lib/typescript/module/internal/records.d.ts +24 -0
  120. package/lib/typescript/module/internal/records.d.ts.map +1 -0
  121. package/lib/typescript/module/providers/cloudKit.d.ts +1 -1
  122. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  123. package/lib/typescript/module/providers/cloudKitBackup.d.ts +1 -1
  124. package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -1
  125. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -1
  126. package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -1
  127. package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -1
  128. package/lib/typescript/module/providers/icloudDocuments.d.ts +1 -1
  129. package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -1
  130. package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -1
  131. package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -1
  132. package/lib/typescript/module/providers/memory.d.ts.map +1 -1
  133. package/lib/typescript/module/resolvers.d.ts +6 -3
  134. package/lib/typescript/module/resolvers.d.ts.map +1 -1
  135. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +12 -3
  136. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -1
  137. package/lib/typescript/module/store.d.ts.map +1 -1
  138. package/lib/typescript/module/types.d.ts +31 -3
  139. package/lib/typescript/module/types.d.ts.map +1 -1
  140. package/package.json +38 -28
  141. package/plugin/build/index.js +45 -13
  142. package/react-native-cloud-sync.podspec +10 -3
  143. package/src/hooks.ts +69 -9
  144. package/src/internal/autoFlush.ts +10 -1
  145. package/src/internal/base64.ts +26 -5
  146. package/src/internal/cloudKitRest.ts +103 -14
  147. package/src/internal/googleDriveRest.ts +338 -37
  148. package/src/internal/keys.ts +42 -16
  149. package/src/internal/records.ts +38 -0
  150. package/src/providers/cloudKit.ts +96 -20
  151. package/src/providers/cloudKitEncrypted.ts +37 -8
  152. package/src/providers/googleDrive.ts +38 -2
  153. package/src/providers/icloudDocuments.ts +40 -2
  154. package/src/providers/icloudKV.ts +13 -3
  155. package/src/providers/icloudKV.web.ts +8 -2
  156. package/src/providers/memory.ts +8 -0
  157. package/src/resolvers.ts +28 -13
  158. package/src/specs/NativeRNCloudSync.ts +16 -2
  159. package/src/store.ts +433 -190
  160. package/src/types.ts +32 -3
@@ -1,4 +1,5 @@
1
1
  import CloudKit
2
+ import CryptoKit
2
3
  import Foundation
3
4
 
4
5
  /// All CloudKit and NSUbiquitousKeyValueStore logic.
@@ -30,7 +31,27 @@ import Foundation
30
31
  /// automatically just because the class is `@objc` and inherits NSObject,
31
32
  /// so without it the bridge fails to compile with "property 'emit' not
32
33
  /// found on object of type 'CloudSyncImpl *'".
33
- @objc public var emit: ((String, [String: Any]) -> Void)?
34
+ ///
35
+ /// Lock-guarded: the bridge sets this from the JS/module thread (and clears
36
+ /// it from `dealloc` on whatever thread releases the module) while CloudKit
37
+ /// callbacks and notification observers read it on their own queues. An
38
+ /// unsynchronised Swift closure property is a data race on its retain
39
+ /// count, which can crash across a reload.
40
+ @objc public var emit: ((String, [String: Any]) -> Void)? {
41
+ get {
42
+ emitLock.lock()
43
+ defer { emitLock.unlock() }
44
+ return _emit
45
+ }
46
+ set {
47
+ emitLock.lock()
48
+ _emit = newValue
49
+ emitLock.unlock()
50
+ }
51
+ }
52
+
53
+ private var _emit: ((String, [String: Any]) -> Void)?
54
+ private let emitLock = NSLock()
34
55
 
35
56
  /// Opaque identity of the bridge instance that installed `emit`.
36
57
  ///
@@ -51,12 +72,44 @@ import Foundation
51
72
 
52
73
  /// Resolved once. `CKContainer(identifier:)` is not free, and the previous
53
74
  /// in-app implementation this replaces rebuilt it on every single call.
54
- private lazy var container: CKContainer? = {
55
- guard let identifier = Self.resolveContainerIdentifier() else { return nil }
75
+ ///
76
+ /// Only ever built from a DECLARED identifier - never guessed.
77
+ /// `CKContainer(identifier:)` with an identifier the app is not entitled to
78
+ /// traps inside CloudKit (EXC_BREAKPOINT, uncatchable from Swift or ObjC).
79
+ /// The old `iCloud.<bundle id>` fallback did exactly that in every app
80
+ /// without a CloudKit container - a key-value-store-only app crashed the
81
+ /// moment anything called `cloudKit.isAvailable()`. `nil` here means "no
82
+ /// container declared"; every CloudKit path checks it and fails typed.
83
+ ///
84
+ /// A `static let`, not a `lazy var`: lazy initialisation is not thread-safe
85
+ /// in Swift, and this is first touched from whichever queue gets there
86
+ /// first - a JS call, or the `CKAccountChanged` observer. `static let` is
87
+ /// initialised exactly once under `dispatch_once`.
88
+ private static let sharedContainer: CKContainer? = {
89
+ guard let identifier = declaredContainerIdentifier() else { return nil }
56
90
  return CKContainer(identifier: identifier)
57
91
  }()
58
92
 
59
- private var database: CKDatabase? { container?.privateCloudDatabase }
93
+ private var container: CKContainer? { Self.sharedContainer }
94
+
95
+ private static let containerNotDeclaredMessage =
96
+ "No CloudKit container is declared, so CloudKit is unavailable. Use the Expo config "
97
+ + "plugin (cloudKit: true, the default), or in a bare project add the container id to "
98
+ + "Info.plist as RNCloudSyncContainerIdentifier (a String, e.g. iCloud.com.your.app) "
99
+ + "alongside the iCloud/CloudKit entitlements."
100
+
101
+ private static func containerNotDeclaredError() -> CloudSyncError {
102
+ return .coded(
103
+ code: CloudSyncErrorCode.containerMisconfigured,
104
+ message: containerNotDeclaredMessage,
105
+ info: [:]
106
+ )
107
+ }
108
+
109
+ private func requireContainer() throws -> CKContainer {
110
+ guard let container = container else { throw Self.containerNotDeclaredError() }
111
+ return container
112
+ }
60
113
 
61
114
  // MARK: - Configuration
62
115
 
@@ -65,33 +118,30 @@ import Foundation
65
118
  /// absent" - entitlements live in the code signature, and the API that reads
66
119
  /// those (`SecTaskCopyValueForEntitlement`) is not public on iOS.
67
120
  static func declaredContainerIdentifier() -> String? {
121
+ // Written by the Expo config plugin. Entitlements are not readable from
122
+ // the bundle at runtime, so without this a `containerIdentifier` passed
123
+ // to the plugin never reached native code: every call silently used the
124
+ // `iCloud.<bundle id>` fallback instead, i.e. a different container
125
+ // from the one the app is actually entitled to.
126
+ if let configured = Bundle.main.object(
127
+ forInfoDictionaryKey: "RNCloudSyncContainerIdentifier"
128
+ ) as? String, !configured.isEmpty {
129
+ return configured
130
+ }
68
131
  guard let ids = Bundle.main.object(
69
132
  forInfoDictionaryKey: "com.apple.developer.icloud-container-identifiers"
70
133
  ) as? [String] else { return nil }
71
134
  return ids.first
72
135
  }
73
136
 
74
- /// Reads the container id straight out of the app's entitlements, so apps do
75
- /// not have to repeat it in JavaScript and cannot get the two out of sync.
76
- static func resolveContainerIdentifier() -> String? {
77
- if let declared = declaredContainerIdentifier() { return declared }
78
- // Entitlements are not in Info.plist on a device build; fall back to the
79
- // conventional `iCloud.<bundle id>` form.
80
- guard let bundleId = Bundle.main.bundleIdentifier else { return nil }
81
- return "iCloud.\(bundleId)"
82
- }
83
-
84
137
  @objc public func getConstants() -> [String: Any] {
85
138
  return [
86
- "containerIdentifier": Self.resolveContainerIdentifier() ?? "",
87
- // Derived from the DECLARED identifier, not the resolved one.
88
- // `resolveContainerIdentifier` falls back to `iCloud.<bundle id>`
89
- // whenever the declaration is unreadable, so deriving this from it
90
- // made the constant `true` for every app that has a bundle id -
91
- // including one with no iCloud capability at all, which is exactly
92
- // the case a caller reads this to detect. It is a confirmation, not
93
- // a guarantee: false means "not confirmed here", and the async
94
- // account-status path is the authoritative check.
139
+ // '' when nothing is declared - there is no guessed fallback any
140
+ // more, since using a guessed container crashes inside CloudKit.
141
+ "containerIdentifier": Self.declaredContainerIdentifier() ?? "",
142
+ // A declaration, not proof of the entitlement itself: false means
143
+ // CloudKit is off for this build (every CloudKit call rejects
144
+ // ERR_CONTAINER_MISCONFIGURED), true means it was configured.
95
145
  "hasICloudEntitlement": Self.declaredContainerIdentifier() != nil,
96
146
  ]
97
147
  }
@@ -110,6 +160,12 @@ import Foundation
110
160
  /// Starts observing the two notifications that every library in this space
111
161
  /// either ignores or crashes on.
112
162
  @objc public func startObserving() {
163
+ // Idempotent. Each bridge instance calls this from its init, and across
164
+ // a reload the outgoing instance deliberately does NOT stop observing
165
+ // (see `emitOwner`). Without this removal the singleton was registered
166
+ // once per reload, so every KV change and account change reached JS
167
+ // two, three, N times.
168
+ NotificationCenter.default.removeObserver(self)
113
169
  NotificationCenter.default.addObserver(
114
170
  self,
115
171
  selector: #selector(kvStoreDidChange(_:)),
@@ -158,16 +214,20 @@ import Foundation
158
214
  // The event nobody handles. A different Apple ID is now signed in, so
159
215
  // any user-scoped state the app cached belongs to the previous user.
160
216
  log("iCloud identity changed")
161
- accountStatusString { status in
162
- self.emit?("accountChange", [
163
- "status": status,
164
- "identityChanged": true,
165
- "provider": "icloudKV",
166
- ])
167
- }
217
+ // Key-value status, not CloudKit's: this fires in KV-only apps too,
218
+ // and asking CloudKit there would construct a container the app is not
219
+ // entitled to.
220
+ emit?("accountChange", [
221
+ "status": kvAccountStatusString(),
222
+ "identityChanged": true,
223
+ "provider": "icloudKV",
224
+ ])
168
225
  }
169
226
 
170
227
  @objc private func ckAccountDidChange(_ note: Notification) {
228
+ // Posted by the system regardless of entitlements; asking CloudKit
229
+ // about it in an app without a declared container would trap.
230
+ guard container != nil else { return }
171
231
  accountStatusString { status in
172
232
  self.emit?("accountChange", [
173
233
  "status": status,
@@ -200,16 +260,46 @@ import Foundation
200
260
  resolve: @escaping (Any?) -> Void,
201
261
  reject: @escaping (String, String, NSError?) -> Void
202
262
  ) {
263
+ guard container != nil else {
264
+ let error = Self.containerNotDeclaredError()
265
+ reject(error.code, error.message, error.asNSError)
266
+ return
267
+ }
203
268
  accountStatusString { resolve($0) }
204
269
  }
205
270
 
271
+ /// False, never a throw, when no container is declared - `isAvailable` is
272
+ /// documented as safe to call on a render path.
206
273
  @objc public func isAvailable(
207
274
  resolve: @escaping (Any?) -> Void,
208
275
  reject: @escaping (String, String, NSError?) -> Void
209
276
  ) {
277
+ guard container != nil else {
278
+ resolve(false)
279
+ return
280
+ }
210
281
  accountStatusString { resolve($0 == "available") }
211
282
  }
212
283
 
284
+ /// Account status as the key-value store sees it, without CloudKit.
285
+ ///
286
+ /// `ubiquityIdentityToken` is non-nil exactly when an iCloud account is
287
+ /// signed in with iCloud Drive/KV available to this app. It needs no
288
+ /// CloudKit entitlement, so a KV-only app can call this safely - unlike
289
+ /// `getAccountStatus`, which goes through `CKContainer` and raises a
290
+ /// `CKException` when that entitlement is missing. It cannot tell
291
+ /// "restricted" from "signed out"; both read as `noAccount`.
292
+ private func kvAccountStatusString() -> String {
293
+ return FileManager.default.ubiquityIdentityToken != nil ? "available" : "noAccount"
294
+ }
295
+
296
+ @objc public func kvGetAccountStatus(
297
+ resolve: @escaping (Any?) -> Void,
298
+ reject: @escaping (String, String, NSError?) -> Void
299
+ ) {
300
+ resolve(kvAccountStatusString())
301
+ }
302
+
213
303
  // MARK: - Key-value store
214
304
 
215
305
  @objc public func kvGetItem(
@@ -245,6 +335,8 @@ import Foundation
245
335
  let all = kvStore.dictionaryRepresentation
246
336
  for (existingKey, existingValue) in all {
247
337
  if existingKey == key { continue }
338
+ // Apple's 1 MB total covers keys as well as values.
339
+ bytes += existingKey.lengthOfBytes(using: .utf8)
248
340
  if let text = existingValue as? String {
249
341
  bytes += text.lengthOfBytes(using: .utf8)
250
342
  } else if let data = existingValue as? Data {
@@ -281,7 +373,7 @@ import Foundation
281
373
  // values silently starves every other key, and the only signal is a
282
374
  // quota-violation notification that arrives long after the write was
283
375
  // reported as successful.
284
- let projected = usage.bytes + bytes
376
+ let projected = usage.bytes + key.lengthOfBytes(using: .utf8) + bytes
285
377
  if projected > Self.kvMaxTotalBytes {
286
378
  let error = CloudSyncError.coded(
287
379
  code: CloudSyncErrorCode.quotaExceeded,
@@ -376,21 +468,100 @@ import Foundation
376
468
  // MARK: - CloudKit records
377
469
 
378
470
  private func requireDatabase() throws -> CKDatabase {
379
- guard let database = database else {
380
- throw CloudSyncError.coded(
381
- code: CloudSyncErrorCode.containerMisconfigured,
382
- message: "No iCloud container is configured. Add the iCloud capability and a "
383
- + "CloudKit container to the app target's entitlements.",
384
- info: [:]
471
+ return try requireContainer().privateCloudDatabase
472
+ }
473
+
474
+ private func recordID(_ recordName: String, _ zoneName: String?) throws -> CKRecord.ID {
475
+ try Self.validateRecordName(recordName)
476
+ guard let zoneName = zoneName else { return CKRecord.ID(recordName: recordName) }
477
+ return CKRecord.ID(recordName: recordName, zoneID: try zoneID(zoneName))
478
+ }
479
+
480
+ private func zoneID(_ zoneName: String) throws -> CKRecordZone.ID {
481
+ try Self.validateZoneName(zoneName)
482
+ return CKRecordZone.ID(zoneName: zoneName, ownerName: CKCurrentUserDefaultName)
483
+ }
484
+
485
+ // MARK: - Identifier validation
486
+ //
487
+ // CloudKit validates record types, record names, zone names and field names
488
+ // by raising an Objective-C exception (`CKException` /
489
+ // `NSInvalidArgumentException`) from the initialiser or subscript - not by
490
+ // returning an error. Swift cannot catch those, so an empty key, a
491
+ // 256-character name or a field called `creationDate` coming from JS
492
+ // terminated the app. Every one of those strings is caller- or data-supplied
493
+ // (keys synced from another device, migrated from the key-value store), so
494
+ // they are checked here first and rejected as ERR_INVALID_KEY.
495
+ //
496
+ // The rules below were established empirically against CloudKit itself:
497
+ // lengths are counted in UTF-16 units, and the character rules apply to
498
+ // record types and field names only.
499
+
500
+ static let maxIdentifierLength = 255
501
+
502
+ /// Field names CloudKit reserves for record metadata.
503
+ static let reservedFieldNames: Set<String> = [
504
+ "recordID", "recordType", "creationDate", "creatorUserRecordID",
505
+ "modificationDate", "lastModifiedUserRecordID", "recordChangeTag",
506
+ ]
507
+
508
+ private static func isSchemaIdentifier(_ value: String, maxLength: Int) -> Bool {
509
+ guard !value.isEmpty, value.utf16.count <= maxLength else { return false }
510
+ for (index, scalar) in value.unicodeScalars.enumerated() {
511
+ let isLetter = ("a"..."z").contains(scalar) || ("A"..."Z").contains(scalar)
512
+ let isDigit = ("0"..."9").contains(scalar)
513
+ let ok = index == 0 ? (isLetter || scalar == "_") : (isLetter || isDigit || scalar == "_")
514
+ if !ok { return false }
515
+ }
516
+ return true
517
+ }
518
+
519
+ private static func invalidIdentifier(_ kind: String, _ value: String, _ rule: String) -> CloudSyncError {
520
+ let shown = value.count > 64 ? "\(value.prefix(64))..." : value
521
+ return .coded(
522
+ code: CloudSyncErrorCode.invalidKey,
523
+ message: "Invalid CloudKit \(kind) '\(shown)': \(rule).",
524
+ info: [:]
525
+ )
526
+ }
527
+
528
+ static func validateRecordType(_ recordType: String) throws {
529
+ guard isSchemaIdentifier(recordType, maxLength: maxIdentifierLength) else {
530
+ throw invalidIdentifier(
531
+ "record type", recordType,
532
+ "use 1-\(maxIdentifierLength) ASCII letters, digits or '_', not starting with a digit"
385
533
  )
386
534
  }
387
- return database
388
535
  }
389
536
 
390
- private func recordID(_ recordName: String, _ zoneName: String?) -> CKRecord.ID {
391
- guard let zoneName = zoneName else { return CKRecord.ID(recordName: recordName) }
392
- let zoneID = CKRecordZone.ID(zoneName: zoneName, ownerName: CKCurrentUserDefaultName)
393
- return CKRecord.ID(recordName: recordName, zoneID: zoneID)
537
+ static func validateRecordName(_ recordName: String) throws {
538
+ guard !recordName.isEmpty, recordName.utf16.count <= maxIdentifierLength else {
539
+ throw invalidIdentifier(
540
+ "record name", recordName, "must be 1-\(maxIdentifierLength) characters"
541
+ )
542
+ }
543
+ }
544
+
545
+ static func validateZoneName(_ zoneName: String) throws {
546
+ guard !zoneName.isEmpty, zoneName.utf16.count <= maxIdentifierLength else {
547
+ throw invalidIdentifier(
548
+ "zone name", zoneName, "must be 1-\(maxIdentifierLength) characters"
549
+ )
550
+ }
551
+ }
552
+
553
+ /// Asset field names also carry a `__size` sibling (see `sizeField`), so
554
+ /// they must leave room for that suffix under CloudKit's 255 limit.
555
+ static func validateFieldName(_ fieldName: String) throws {
556
+ let maxLength = maxIdentifierLength - "__size".utf16.count
557
+ guard isSchemaIdentifier(fieldName, maxLength: maxLength),
558
+ !reservedFieldNames.contains(fieldName) else {
559
+ throw invalidIdentifier(
560
+ "field name", fieldName,
561
+ "use 1-\(maxLength) ASCII letters, digits or '_', not starting with a digit, "
562
+ + "and not a reserved name such as 'creationDate'"
563
+ )
564
+ }
394
565
  }
395
566
 
396
567
  /// Reads the value field, from the encrypted or the plain side of the record.
@@ -417,7 +588,8 @@ import Foundation
417
588
  ) {
418
589
  do {
419
590
  let database = try requireDatabase()
420
- database.fetch(withRecordID: recordID(recordName, zoneName)) { record, error in
591
+ try Self.validateRecordType(recordType)
592
+ database.fetch(withRecordID: try recordID(recordName, zoneName)) { record, error in
421
593
  if let error = error {
422
594
  // A missing record is a normal outcome, not a failure - but
423
595
  // it must be distinguished from every other error, which is
@@ -430,6 +602,21 @@ import Foundation
430
602
  reject(mapped.code, mapped.message, mapped.asNSError)
431
603
  return
432
604
  }
605
+ // The record type is part of the read contract, not just the
606
+ // write. A record name is shared across types, so without this
607
+ // a `KVBlob` (or any other type) occupying an encrypted
608
+ // provider's `rncs-enc.<key>` name was read as if it were an
609
+ // `EncryptedKVBlob` - a downgrade the caller cannot see.
610
+ if let record = record, record.recordType != recordType {
611
+ let error = CloudSyncError.coded(
612
+ code: CloudSyncErrorCode.invalidKey,
613
+ message: "Record '\(recordName)' has type '\(record.recordType)', not the "
614
+ + "expected '\(recordType)'. It was not read.",
615
+ info: [:]
616
+ )
617
+ reject(error.code, error.message, error.asNSError)
618
+ return
619
+ }
433
620
  resolve(Self.readValue(record, encrypted: encrypted))
434
621
  }
435
622
  } catch {
@@ -466,7 +653,8 @@ import Foundation
466
653
 
467
654
  do {
468
655
  let database = try requireDatabase()
469
- let id = recordID(recordName, zoneName)
656
+ try Self.validateRecordType(recordType)
657
+ let id = try recordID(recordName, zoneName)
470
658
  let record = CKRecord(recordType: recordType, recordID: id)
471
659
  if encrypted {
472
660
  record.encryptedValues[Self.valueField] = value as CKRecordValue
@@ -507,7 +695,7 @@ import Foundation
507
695
  ) {
508
696
  do {
509
697
  let database = try requireDatabase()
510
- database.delete(withRecordID: recordID(recordName, zoneName)) { _, error in
698
+ database.delete(withRecordID: try recordID(recordName, zoneName)) { _, error in
511
699
  if let error = error {
512
700
  // Already gone is the desired end state.
513
701
  if let ckError = error as? CKError, ckError.code == .unknownItem {
@@ -534,9 +722,8 @@ import Foundation
534
722
  ) {
535
723
  do {
536
724
  let database = try requireDatabase()
537
- let zoneID = zoneName.map {
538
- CKRecordZone.ID(zoneName: $0, ownerName: CKCurrentUserDefaultName)
539
- }
725
+ try Self.validateRecordType(recordType)
726
+ let zoneID = try zoneName.map { try self.zoneID($0) }
540
727
 
541
728
  var names: [String] = []
542
729
 
@@ -584,6 +771,7 @@ import Foundation
584
771
  ) {
585
772
  do {
586
773
  let database = try requireDatabase()
774
+ try Self.validateZoneName(zoneName)
587
775
  let zone = CKRecordZone(zoneName: zoneName)
588
776
  let operation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil)
589
777
  operation.modifyRecordZonesResultBlock = { result in
@@ -609,7 +797,7 @@ import Foundation
609
797
  ) {
610
798
  do {
611
799
  let database = try requireDatabase()
612
- let zoneID = CKRecordZone.ID(zoneName: zoneName, ownerName: CKCurrentUserDefaultName)
800
+ let zoneID = try self.zoneID(zoneName)
613
801
  let operation = CKModifyRecordZonesOperation(recordZonesToSave: nil, recordZoneIDsToDelete: [zoneID])
614
802
  operation.modifyRecordZonesResultBlock = { result in
615
803
  switch result {
@@ -649,9 +837,29 @@ import Foundation
649
837
  assetOperationLock.unlock()
650
838
  }
651
839
 
652
- private func untrackOperation(recordName: String, fieldName: String) {
840
+ /// Swaps `old` for `new` atomically, but only while `old` is still the
841
+ /// tracked operation. False means it was cancelled (removed) meanwhile.
842
+ private func replaceTrackedOperation(
843
+ _ old: CKOperation, with new: CKOperation, recordName: String, fieldName: String
844
+ ) -> Bool {
845
+ let key = Self.transferKey(recordName, fieldName)
653
846
  assetOperationLock.lock()
654
- activeAssetOperations.removeValue(forKey: Self.transferKey(recordName, fieldName))
847
+ defer { assetOperationLock.unlock() }
848
+ guard activeAssetOperations[key] === old else { return false }
849
+ activeAssetOperations[key] = new
850
+ return true
851
+ }
852
+
853
+ /// Removes `operation` only if it is still the tracked one. A second
854
+ /// transfer of the same record+field replaces the entry, and the first one
855
+ /// finishing must not untrack the second - that made the still-running
856
+ /// transfer uncancellable (`ckCancelAsset` resolved false).
857
+ private func untrackOperation(_ operation: CKOperation, recordName: String, fieldName: String) {
858
+ let key = Self.transferKey(recordName, fieldName)
859
+ assetOperationLock.lock()
860
+ if activeAssetOperations[key] === operation {
861
+ activeAssetOperations.removeValue(forKey: key)
862
+ }
655
863
  assetOperationLock.unlock()
656
864
  }
657
865
 
@@ -698,6 +906,9 @@ import Foundation
698
906
  ) {
699
907
  do {
700
908
  let database = try requireDatabase()
909
+ try Self.validateRecordType(recordType)
910
+ try Self.validateFieldName(fieldName)
911
+ let id = try recordID(recordName, zoneName)
701
912
  let fileURL = Self.fileURL(from: fileUri)
702
913
 
703
914
  guard FileManager.default.fileExists(atPath: fileURL.path) else {
@@ -710,7 +921,6 @@ import Foundation
710
921
  return
711
922
  }
712
923
 
713
- let id = recordID(recordName, zoneName)
714
924
  let record = CKRecord(recordType: recordType, recordID: id)
715
925
  record[fieldName] = CKAsset(fileURL: fileURL)
716
926
 
@@ -740,8 +950,8 @@ import Foundation
740
950
  ])
741
951
  }
742
952
 
743
- operation.modifyRecordsResultBlock = { [weak self] result in
744
- self?.untrackOperation(recordName: recordName, fieldName: fieldName)
953
+ operation.modifyRecordsResultBlock = { [weak self, unowned operation] result in
954
+ self?.untrackOperation(operation, recordName: recordName, fieldName: fieldName)
745
955
  switch result {
746
956
  case .success:
747
957
  resolve(nil)
@@ -790,15 +1000,31 @@ import Foundation
790
1000
  ) {
791
1001
  do {
792
1002
  let database = try requireDatabase()
793
- let id = recordID(recordName, zoneName)
794
-
795
- fetchKnownSize(database: database, id: id, fieldName: fieldName) { [weak self] knownSize in
796
- self?.fetchAsset(
1003
+ try Self.validateFieldName(fieldName)
1004
+ let id = try recordID(recordName, zoneName)
1005
+
1006
+ // The size lookup is tracked as this transfer's operation from the
1007
+ // start, so `ckCancelAsset` during the lookup cancels it rather
1008
+ // than resolving false and letting the download run anyway.
1009
+ // `fetchAsset` swaps in the download operation only if the lookup
1010
+ // is still the tracked one; otherwise the transfer was cancelled.
1011
+ var sizeOperation: CKDatabaseOperation?
1012
+ sizeOperation = fetchKnownSize(database: database, id: id, fieldName: fieldName) { [weak self] knownSize in
1013
+ // Clearing the box breaks operation -> block -> box -> operation.
1014
+ let lookup = sizeOperation
1015
+ sizeOperation = nil
1016
+ guard let self = self, let sizeOperation = lookup else { return }
1017
+ self.fetchAsset(
797
1018
  database: database, id: id, recordName: recordName, fieldName: fieldName,
798
1019
  knownSize: knownSize, destinationUri: destinationUri,
1020
+ replacing: sizeOperation,
799
1021
  resolve: resolve, reject: reject
800
1022
  )
801
1023
  }
1024
+ if let sizeOperation = sizeOperation {
1025
+ trackOperation(sizeOperation, recordName: recordName, fieldName: fieldName)
1026
+ database.add(sizeOperation)
1027
+ }
802
1028
  } catch {
803
1029
  let mapped = CloudSyncError.from(error)
804
1030
  reject(mapped.code, mapped.message, mapped.asNSError)
@@ -814,7 +1040,7 @@ import Foundation
814
1040
  id: CKRecord.ID,
815
1041
  fieldName: String,
816
1042
  completion: @escaping (Int) -> Void
817
- ) {
1043
+ ) -> CKDatabaseOperation {
818
1044
  let operation = CKFetchRecordsOperation(recordIDs: [id])
819
1045
  operation.desiredKeys = [Self.sizeField(fieldName)]
820
1046
 
@@ -841,14 +1067,75 @@ import Foundation
841
1067
  settle(0)
842
1068
  return
843
1069
  }
844
- settle(size)
1070
+ settle(Self.plausibleAssetSize(size))
845
1071
  }
846
1072
  operation.fetchRecordsResultBlock = { _ in
847
1073
  // Only reaches here without having settled when no per-record
848
1074
  // block fired at all - the operation-level failure case.
849
1075
  settle(0)
850
1076
  }
851
- database.add(operation)
1077
+ // Added by the caller, after it has tracked the operation.
1078
+ return operation
1079
+ }
1080
+
1081
+ /// Largest size field value trusted for progress reporting.
1082
+ static let maxPlausibleAssetBytes = 1 << 42 // 4 TiB
1083
+
1084
+ /// The stored size is record data, written by whichever client saved the
1085
+ /// asset - another device, or anything holding the user's CloudKit Web
1086
+ /// Services token - so it is not trusted. A value near `Int.max` made
1087
+ /// `Int(progress * Double(totalBytes))` overflow and trap, crashing the
1088
+ /// app on the first progress callback of an otherwise valid download.
1089
+ static func plausibleAssetSize(_ size: Int) -> Int {
1090
+ return (0...maxPlausibleAssetBytes).contains(size) ? size : 0
1091
+ }
1092
+
1093
+ /// Where a fetched asset lands when the caller names no destination.
1094
+ ///
1095
+ /// Derived from a digest rather than spliced from the names. `recordName`
1096
+ /// may legally contain `/` and `..` (CloudKit accepts both), so the old
1097
+ /// `tmp/rncs-<recordName>-<fieldName>` let a record named
1098
+ /// `x/../../Documents/db.sqlite` resolve outside the temporary directory -
1099
+ /// and the code below deletes whatever is at the destination before copying
1100
+ /// over it. The digest is fixed-length, one path component, and still
1101
+ /// stable per record+field, so repeated fetches reuse one file instead of
1102
+ /// accumulating.
1103
+ static func defaultAssetDestination(recordName: String, fieldName: String, zoneName: String?) -> URL {
1104
+ let identity = [zoneName ?? "", recordName, fieldName].joined(separator: "\u{0}")
1105
+ let digest = SHA256.hash(data: Data(identity.utf8))
1106
+ .map { String(format: "%02x", $0) }
1107
+ .joined()
1108
+ return FileManager.default.temporaryDirectory
1109
+ .appendingPathComponent("rncs-asset-\(digest)", isDirectory: false)
1110
+ }
1111
+
1112
+ /// Clears `destination` so a copy can land there, refusing to delete a
1113
+ /// directory.
1114
+ ///
1115
+ /// Both download paths replace an existing file at the caller's
1116
+ /// destination. `removeItem` is recursive, so a destination that named a
1117
+ /// directory - `FileSystem.documentDirectory`, say, by someone reading
1118
+ /// `destinationUri` as "put it in here" - wiped that whole directory before
1119
+ /// the copy. The type is read without following symlinks: a symlink is
1120
+ /// replaced (the link, not its target), which is what a copy-to-path means.
1121
+ static func prepareDestination(_ destination: URL) throws {
1122
+ let fileManager = FileManager.default
1123
+ let parent = destination.deletingLastPathComponent()
1124
+ if !fileManager.fileExists(atPath: parent.path) {
1125
+ try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)
1126
+ }
1127
+ guard let attributes = try? fileManager.attributesOfItem(atPath: destination.path) else {
1128
+ return // Nothing there.
1129
+ }
1130
+ if attributes[.type] as? FileAttributeType == .typeDirectory {
1131
+ throw CloudSyncError.coded(
1132
+ code: CloudSyncErrorCode.unknown,
1133
+ message: "Destination \(destination.path) is a directory. Pass a file path, not a "
1134
+ + "folder - an existing file there is replaced, a directory never is.",
1135
+ info: [:]
1136
+ )
1137
+ }
1138
+ try fileManager.removeItem(at: destination)
852
1139
  }
853
1140
 
854
1141
  private func fetchAsset(
@@ -858,12 +1145,32 @@ import Foundation
858
1145
  fieldName: String,
859
1146
  knownSize: Int,
860
1147
  destinationUri: String?,
1148
+ replacing sizeOperation: CKOperation,
861
1149
  resolve: @escaping (Any?) -> Void,
862
1150
  reject: @escaping (String, String, NSError?) -> Void
863
1151
  ) {
864
1152
  let operation = CKFetchRecordsOperation(recordIDs: [id])
865
1153
  var totalBytes = knownSize
866
1154
 
1155
+ // Exactly one settlement. A per-record outcome is followed by the
1156
+ // operation-level block, and that block reports `.failure` (a
1157
+ // partialFailure) whenever the record failed - including the
1158
+ // `.unknownItem` case already resolved as nil, and a cancellation
1159
+ // already rejected. Settling twice is "Tried to resolve a promise more
1160
+ // than once" in React Native. CloudKit invokes these blocks serially on
1161
+ // the operation's queue, so a plain flag is enough.
1162
+ var settled = false
1163
+ let settleResolve: (Any?) -> Void = { value in
1164
+ if settled { return }
1165
+ settled = true
1166
+ resolve(value)
1167
+ }
1168
+ let settleReject: (String, String, NSError?) -> Void = { code, message, error in
1169
+ if settled { return }
1170
+ settled = true
1171
+ reject(code, message, error)
1172
+ }
1173
+
867
1174
  operation.perRecordProgressBlock = { [weak self] _, progress in
868
1175
  guard let self = self, progress > 0 else { return }
869
1176
  self.emit?("assetProgress", [
@@ -879,7 +1186,7 @@ import Foundation
879
1186
  case let .success(record):
880
1187
  guard let asset = record[fieldName] as? CKAsset,
881
1188
  let url = asset.fileURL else {
882
- resolve(nil)
1189
+ settleResolve(nil)
883
1190
  return
884
1191
  }
885
1192
 
@@ -898,55 +1205,59 @@ import Foundation
898
1205
  // may reclaim, so copy it somewhere the caller controls
899
1206
  // before handing back a path.
900
1207
  let destination = destinationUri.map { Self.fileURL(from: $0) }
901
- ?? FileManager.default.temporaryDirectory
902
- .appendingPathComponent("rncs-\(recordName)-\(fieldName)")
1208
+ ?? Self.defaultAssetDestination(
1209
+ recordName: recordName, fieldName: fieldName, zoneName: id.zoneID.zoneName
1210
+ )
903
1211
  do {
904
- // Create the parent directory when the caller named a path
1212
+ // Creates the parent directory when the caller named a path
905
1213
  // inside one that does not exist yet - a copy into a missing
906
1214
  // directory fails, and making them create it first would be
907
1215
  // a pointless extra step in every export flow.
908
- let parent = destination.deletingLastPathComponent()
909
- if !FileManager.default.fileExists(atPath: parent.path) {
910
- try FileManager.default.createDirectory(
911
- at: parent, withIntermediateDirectories: true
912
- )
913
- }
914
- if FileManager.default.fileExists(atPath: destination.path) {
915
- try FileManager.default.removeItem(at: destination)
916
- }
1216
+ try Self.prepareDestination(destination)
917
1217
  try FileManager.default.copyItem(at: url, to: destination)
918
- resolve(destination.absoluteString)
1218
+ settleResolve(destination.absoluteString)
919
1219
  } catch {
920
1220
  let mapped = CloudSyncError.from(error)
921
- reject(mapped.code, mapped.message, mapped.asNSError)
1221
+ settleReject(mapped.code, mapped.message, mapped.asNSError)
922
1222
  }
923
1223
  case let .failure(error):
924
1224
  if let ckError = error as? CKError, ckError.code == .unknownItem {
925
- resolve(nil)
1225
+ settleResolve(nil)
926
1226
  return
927
1227
  }
928
1228
  let mapped = CloudSyncError.from(error)
929
- reject(mapped.code, mapped.message, mapped.asNSError)
1229
+ settleReject(mapped.code, mapped.message, mapped.asNSError)
930
1230
  }
931
1231
  }
932
1232
 
933
- operation.fetchRecordsResultBlock = { [weak self] result in
934
- self?.untrackOperation(recordName: recordName, fieldName: fieldName)
1233
+ operation.fetchRecordsResultBlock = { [weak self, unowned operation] result in
1234
+ self?.untrackOperation(operation, recordName: recordName, fieldName: fieldName)
935
1235
  if case let .failure(error) = result {
936
1236
  // A per-record failure already resolved/rejected above; this
937
1237
  // only fires for operation-level failures (e.g. the record
938
1238
  // simply not existing surfaces here rather than per-record
939
1239
  // on some CloudKit versions), so guard against double-resolving.
940
1240
  if let ckError = error as? CKError, ckError.code == .unknownItem {
941
- resolve(nil)
1241
+ settleResolve(nil)
942
1242
  return
943
1243
  }
944
1244
  let mapped = CloudSyncError.from(error)
945
- reject(mapped.code, mapped.message, mapped.asNSError)
1245
+ settleReject(mapped.code, mapped.message, mapped.asNSError)
946
1246
  }
947
1247
  }
948
1248
 
949
- trackOperation(operation, recordName: recordName, fieldName: fieldName)
1249
+ guard replaceTrackedOperation(
1250
+ sizeOperation, with: operation, recordName: recordName, fieldName: fieldName
1251
+ ) else {
1252
+ // `ckCancelAsset` removed the size lookup while it ran.
1253
+ let error = CloudSyncError.coded(
1254
+ code: CloudSyncErrorCode.cancelled,
1255
+ message: "The CloudKit operation was cancelled.",
1256
+ info: [:]
1257
+ )
1258
+ settleReject(error.code, error.message, error.asNSError)
1259
+ return
1260
+ }
950
1261
  database.add(operation)
951
1262
  }
952
1263
 
@@ -973,12 +1284,30 @@ import Foundation
973
1284
  /// The container root. Blocking - Apple documents this as slow enough that
974
1285
  /// it must not be called on the main thread, so every caller here hops to a
975
1286
  /// background queue first.
1287
+ ///
1288
+ /// No CKContainer involved, and safe without a declaration: passing nil asks
1289
+ /// for the first container in the app's ubiquity entitlements, and simply
1290
+ /// returns nil when there is none. The old `iCloud.<bundle id>` guess was
1291
+ /// worse than nil - it named a container the app may not have.
976
1292
  private func ubiquityContainerURL() -> URL? {
977
1293
  return FileManager.default.url(
978
- forUbiquityContainerIdentifier: Self.resolveContainerIdentifier()
1294
+ forUbiquityContainerIdentifier: Self.documentsContainerIdentifier()
979
1295
  )
980
1296
  }
981
1297
 
1298
+ /// The container for iCloud Drive documents. Its own Info.plist key, because
1299
+ /// an app can have iCloud Documents without CloudKit - and declaring the
1300
+ /// CloudKit container there would let CloudKit calls build a CKContainer
1301
+ /// the app has no CloudKit service for.
1302
+ static func documentsContainerIdentifier() -> String? {
1303
+ if let configured = Bundle.main.object(
1304
+ forInfoDictionaryKey: "RNCloudSyncDocumentsContainerIdentifier"
1305
+ ) as? String, !configured.isEmpty {
1306
+ return configured
1307
+ }
1308
+ return declaredContainerIdentifier()
1309
+ }
1310
+
982
1311
  /// The user-visible subdirectory. Only `Documents` is ever exposed in
983
1312
  /// Files.app; anything written beside it stays hidden from the user, which
984
1313
  /// would defeat the point of this API.
@@ -1000,6 +1329,28 @@ import Foundation
1000
1329
  return documents
1001
1330
  }
1002
1331
 
1332
+ /// A document name must be a single path component inside `Documents`.
1333
+ ///
1334
+ /// Names are appended to the container URL as-is, so `a/b`, `..` or
1335
+ /// `../../Library/x` reached outside the user-visible folder - into a
1336
+ /// subdirectory that does not exist (a confusing ERR_UNKNOWN), or out of
1337
+ /// `Documents` altogether. A `.x.icloud` name would collide with the
1338
+ /// placeholder naming this file relies on to detect undownloaded items.
1339
+ static func validateDocumentName(_ name: String) throws {
1340
+ let invalid = name.isEmpty
1341
+ || name == "." || name == ".."
1342
+ || name.contains("/") || name.contains("\u{0}")
1343
+ || (name.hasPrefix(".") && name.hasSuffix(".icloud"))
1344
+ guard !invalid else {
1345
+ throw CloudSyncError.coded(
1346
+ code: CloudSyncErrorCode.invalidKey,
1347
+ message: "'\(name)' is not a valid iCloud Drive document name. Use a single "
1348
+ + "file name: non-empty, no '/', not '.' or '..'.",
1349
+ info: [:]
1350
+ )
1351
+ }
1352
+ }
1353
+
1003
1354
  /// True when the device has a usable iCloud Drive container right now.
1004
1355
  @objc public func docIsAvailable(
1005
1356
  resolve: @escaping (Any?) -> Void,
@@ -1035,8 +1386,20 @@ import Foundation
1035
1386
  )
1036
1387
  }
1037
1388
 
1389
+ try Self.validateDocumentName(name)
1038
1390
  let destination = try self.documentsURL().appendingPathComponent(name)
1039
1391
 
1392
+ // Saving the in-container file back under its own name - the
1393
+ // natural "fetch, edit in place, save" flow, since `docFetch`
1394
+ // without a destination resolves exactly that path - used to
1395
+ // remove the destination (i.e. the source) and then fail the
1396
+ // copy, deleting the document from iCloud on every device.
1397
+ // The bytes are already where they belong.
1398
+ if Self.isSameFile(source, destination) {
1399
+ resolve(destination.absoluteString)
1400
+ return
1401
+ }
1402
+
1040
1403
  // Coordinated, because iCloud Drive files are shared with the
1041
1404
  // system daemon and with other processes. An uncoordinated write
1042
1405
  // can be interleaved with a sync and produce a corrupt file.
@@ -1084,6 +1447,7 @@ import Foundation
1084
1447
  DispatchQueue.global(qos: .userInitiated).async { [weak self] in
1085
1448
  guard let self = self else { return }
1086
1449
  do {
1450
+ try Self.validateDocumentName(name)
1087
1451
  let source = try self.documentsURL().appendingPathComponent(name)
1088
1452
 
1089
1453
  guard FileManager.default.fileExists(atPath: source.path)
@@ -1094,7 +1458,7 @@ import Foundation
1094
1458
 
1095
1459
  try FileManager.default.startDownloadingUbiquitousItem(at: source)
1096
1460
 
1097
- let deadline = Date().addingTimeInterval(timeoutMs.doubleValue / 1000)
1461
+ let deadline = Date().addingTimeInterval(Self.fetchTimeoutSeconds(timeoutMs))
1098
1462
  while !self.isDownloaded(source) {
1099
1463
  if Date() >= deadline {
1100
1464
  throw CloudSyncError.coded(
@@ -1121,9 +1485,16 @@ import Foundation
1121
1485
  // Copy out of the container when the caller named a destination,
1122
1486
  // so they get a file the system will not later evict.
1123
1487
  let destination = Self.fileURL(from: destinationUri)
1124
- if FileManager.default.fileExists(atPath: destination.path) {
1125
- try FileManager.default.removeItem(at: destination)
1488
+ // Naming the in-container file itself as the destination would
1489
+ // otherwise delete it (everywhere - it is an iCloud document)
1490
+ // and then fail the copy.
1491
+ if Self.isSameFile(source, destination) {
1492
+ resolve(source.absoluteString)
1493
+ return
1126
1494
  }
1495
+ // Same as `ckFetchAsset`: creates a missing parent, and never
1496
+ // deletes a directory standing at the destination.
1497
+ try Self.prepareDestination(destination)
1127
1498
 
1128
1499
  var coordinationError: NSError?
1129
1500
  var copyError: Error?
@@ -1146,6 +1517,34 @@ import Foundation
1146
1517
  }
1147
1518
  }
1148
1519
 
1520
+ /// Default and ceiling for `docFetch`'s wait, in milliseconds.
1521
+ static let defaultFetchTimeoutMs = 60_000.0
1522
+ static let maxFetchTimeoutMs = 60.0 * 60 * 1000
1523
+
1524
+ /// The wait is a polling loop that holds a GCD worker thread for its whole
1525
+ /// duration. A NaN timeout never compared past the deadline, so it held
1526
+ /// that thread forever; enough of them exhaust the global pool. Clamped to
1527
+ /// an hour, NaN reads as the default.
1528
+ static func fetchTimeoutSeconds(_ timeoutMs: NSNumber) -> TimeInterval {
1529
+ let value = timeoutMs.doubleValue
1530
+ guard !value.isNaN else { return defaultFetchTimeoutMs / 1000 }
1531
+ return min(max(value, 0), maxFetchTimeoutMs) / 1000
1532
+ }
1533
+
1534
+ /// True when both URLs name the same file on disk, after resolving symlinks
1535
+ /// and `..`. Falls back to comparing standardized paths when either side
1536
+ /// does not exist yet.
1537
+ static func isSameFile(_ a: URL, _ b: URL) -> Bool {
1538
+ let left = a.standardizedFileURL.resolvingSymlinksInPath()
1539
+ let right = b.standardizedFileURL.resolvingSymlinksInPath()
1540
+ if left.path == right.path { return true }
1541
+ guard let leftID = try? left.resourceValues(forKeys: [.fileResourceIdentifierKey])
1542
+ .fileResourceIdentifier,
1543
+ let rightID = try? right.resourceValues(forKeys: [.fileResourceIdentifierKey])
1544
+ .fileResourceIdentifier else { return false }
1545
+ return leftID.isEqual(rightID)
1546
+ }
1547
+
1149
1548
  /// Whether the local copy is current, i.e. safe to read.
1150
1549
  private func isDownloaded(_ url: URL) -> Bool {
1151
1550
  let values = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
@@ -1197,17 +1596,26 @@ import Foundation
1197
1596
  if seen.contains(name) { continue }
1198
1597
  seen.insert(name)
1199
1598
 
1200
- let values = try? url.resourceValues(forKeys: [
1599
+ // Ask about the item, not the `.name.icloud` stub. The stub
1600
+ // is a plain local file: it carries no downloading status,
1601
+ // so a not-yet-downloaded file was reported as
1602
+ // `isDownloaded: true` with the stub's own size. The
1603
+ // ubiquitous-item keys resolve on the logical URL even
1604
+ // while only the stub is on disk.
1605
+ let isPlaceholder = url.lastPathComponent != name
1606
+ let itemURL = documents.appendingPathComponent(name)
1607
+ let itemValues = try? itemURL.resourceValues(forKeys: [
1201
1608
  .fileSizeKey,
1202
1609
  .ubiquitousItemDownloadingStatusKey,
1203
1610
  .ubiquitousItemIsDownloadingKey,
1204
1611
  ])
1205
- let status = values?.ubiquitousItemDownloadingStatus
1612
+ let status = itemValues?.ubiquitousItemDownloadingStatus
1613
+ let isDownloaded = status.map { $0 == .current } ?? !isPlaceholder
1206
1614
  result.append([
1207
1615
  "name": name,
1208
- "sizeBytes": values?.fileSize ?? 0,
1209
- "isDownloaded": status == nil || status == .current,
1210
- "isDownloading": values?.ubiquitousItemIsDownloading ?? false,
1616
+ "sizeBytes": itemValues?.fileSize ?? 0,
1617
+ "isDownloaded": isDownloaded,
1618
+ "isDownloading": itemValues?.ubiquitousItemIsDownloading ?? false,
1211
1619
  ])
1212
1620
  }
1213
1621
 
@@ -1235,9 +1643,10 @@ import Foundation
1235
1643
  DispatchQueue.global(qos: .userInitiated).async { [weak self] in
1236
1644
  guard let self = self else { return }
1237
1645
  do {
1646
+ try Self.validateDocumentName(name)
1238
1647
  let target = try self.documentsURL().appendingPathComponent(name)
1239
- guard FileManager.default.fileExists(atPath: target.path)
1240
- || self.placeholderExists(for: target) else {
1648
+ let hasLocalItem = FileManager.default.fileExists(atPath: target.path)
1649
+ guard hasLocalItem || self.placeholderExists(for: target) else {
1241
1650
  // Already gone is the end state the caller asked for.
1242
1651
  resolve(false)
1243
1652
  return
@@ -1249,7 +1658,18 @@ import Foundation
1249
1658
  writingItemAt: target, options: .forDeleting, error: &coordinationError
1250
1659
  ) { url in
1251
1660
  do {
1252
- try FileManager.default.removeItem(at: url)
1661
+ if FileManager.default.fileExists(atPath: url.path) {
1662
+ try FileManager.default.removeItem(at: url)
1663
+ } else {
1664
+ // Not downloaded on this device (iOS 16 and
1665
+ // earlier): only the `.name.icloud` stub is on disk,
1666
+ // so removing the logical path failed with "no such
1667
+ // file". The stub stands for the item, and deleting
1668
+ // it deletes the item from the account.
1669
+ let stub = url.deletingLastPathComponent()
1670
+ .appendingPathComponent(".\(url.lastPathComponent).icloud")
1671
+ try FileManager.default.removeItem(at: stub)
1672
+ }
1253
1673
  } catch {
1254
1674
  removeError = error
1255
1675
  }