adoor 0.1.0 → 0.1.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.
- package/CHANGELOG.md +4 -0
- package/README.md +2 -2
- package/dist/adoor.mjs +105 -84
- package/native/LICENSE +662 -0
- package/native/README.md +12 -0
- package/native/darwin/ADoorService.app/Contents/Info.plist +57 -0
- package/native/darwin/ADoorService.app/Contents/MacOS/ADoorService +0 -0
- package/native/darwin/ADoorService.app/Contents/PkgInfo +1 -0
- package/native/darwin/ADoorService.app/Contents/_CodeSignature/CodeResources +123 -0
- package/native/darwin/ADoorService.app/Contents/embedded.provisionprofile +0 -0
- package/native/source/Package.swift +6 -0
- package/native/source/sdk/LICENSE +21 -0
- package/native/source/sdk/Package.swift +14 -0
- package/native/source/sdk/Sources/ADoor/AdoorClient.swift +270 -0
- package/native/source/sdk/Sources/ADoor/AdoorError.swift +60 -0
- package/native/source/sdk/Sources/ADoor/Changes.swift +202 -0
- package/native/source/sdk/Sources/ADoor/DesktopSessionState.swift +73 -0
- package/native/source/sdk/Sources/ADoor/DeviceFlow.swift +70 -0
- package/native/source/sdk/Sources/ADoor/FolderCatalog.swift +49 -0
- package/native/source/sdk/Sources/ADoor/JSONValue.swift +70 -0
- package/native/source/sdk/Sources/ADoor/LocalStore.swift +474 -0
- package/native/source/sdk/Sources/ADoor/Models.swift +146 -0
- package/native/source/sdk/Sources/ADoor/MountModel.swift +896 -0
- package/native/source/sdk/Sources/ADoor/OAuth.swift +225 -0
- package/native/source/sdk/Sources/ADoor/Provider.swift +211 -0
- package/native/source/sdk/Sources/ADoor/Storage.swift +41 -0
- package/native/source/sdk/Sources/ADoor/SyncTree.swift +501 -0
- package/native/source/sdk/Sources/ADoor/Trash.swift +283 -0
- package/native/source/sdk/Tests/ADoorTests/ADoorTests.swift +182 -0
- package/native/source/sdk/Tests/ADoorTests/DesktopSessionStateTests.swift +46 -0
- package/native/source/sdk/Tests/ADoorTests/MountTests.swift +560 -0
- package/native/source/sdk/Tests/ADoorTests/RegressionTests.swift +360 -0
- package/native/source/service/DesktopSession.swift +241 -0
- package/native/source/service/DeviceClient.swift +53 -0
- package/native/source/service/Domains.swift +182 -0
- package/native/source/service/FolderRefresh.swift +37 -0
- package/native/source/service/KeychainStore.swift +74 -0
- package/native/source/service/LocalSessionSocket.swift +142 -0
- package/native/source/service/ServiceMain.swift +14 -0
- package/native/source/service/ServiceMounts.swift +34 -0
- package/package.json +12 -3
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(FoundationNetworking)
|
|
3
|
+
import FoundationNetworking
|
|
4
|
+
#endif
|
|
5
|
+
/// The token endpoint's response, plus when it was issued so refresh can run ahead of expiry.
|
|
6
|
+
public struct Tokens: Codable, Equatable, Sendable {
|
|
7
|
+
public var accessToken: String
|
|
8
|
+
public var tokenType: String
|
|
9
|
+
public var expiresIn: Int
|
|
10
|
+
public var refreshToken: String
|
|
11
|
+
public var installationId: String
|
|
12
|
+
public var connectionId: String
|
|
13
|
+
public var workspaceId: String
|
|
14
|
+
public var spaceIds: [String]
|
|
15
|
+
/// Present on code exchange; refresh may omit it. Persist the selected library separately.
|
|
16
|
+
public var selectedSpaceId: String?
|
|
17
|
+
public var issuedAt: Date?
|
|
18
|
+
|
|
19
|
+
enum CodingKeys: String, CodingKey {
|
|
20
|
+
case accessToken = "access_token", tokenType = "token_type", expiresIn = "expires_in", refreshToken = "refresh_token"
|
|
21
|
+
case installationId = "installation_id", connectionId = "connection_id", workspaceId = "workspace_id", spaceIds = "space_ids", selectedSpaceId = "selected_space_id", issuedAt = "issued_at"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
public var expiresAt: Date? { issuedAt.map { $0.addingTimeInterval(TimeInterval(expiresIn)) } }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// Explicit space chooser and least-privilege grants. OAuth scope labels do not grant data access.
|
|
28
|
+
public struct SpaceAuthorizationDetails: Encodable, Sendable {
|
|
29
|
+
public let type = "adoor_space_access"
|
|
30
|
+
public let spaceSelection: Selection
|
|
31
|
+
public let permissions: [JSONValue]
|
|
32
|
+
public let capabilities: [String]
|
|
33
|
+
public struct Selection: Encodable, Sendable {
|
|
34
|
+
public let allow: [String]
|
|
35
|
+
public let suggestedName: String?
|
|
36
|
+
enum CodingKeys: String, CodingKey { case allow, suggestedName = "suggested_name" }
|
|
37
|
+
}
|
|
38
|
+
enum CodingKeys: String, CodingKey { case type, spaceSelection = "space_selection", permissions, capabilities }
|
|
39
|
+
public init(allow: [String] = ["create", "existing"], suggestedName: String? = nil, permissions: [JSONValue], capabilities: [String] = []) {
|
|
40
|
+
spaceSelection = Selection(allow: allow, suggestedName: suggestedName)
|
|
41
|
+
self.permissions = permissions
|
|
42
|
+
self.capabilities = capabilities
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public struct PKCE: Sendable {
|
|
47
|
+
public let codeVerifier: String
|
|
48
|
+
public let codeChallenge: String
|
|
49
|
+
public let state: String
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
enum SHA256 {
|
|
53
|
+
private static let k: [UInt32] = [
|
|
54
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
55
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
56
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
57
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
58
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
59
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
60
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
61
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
62
|
+
]
|
|
63
|
+
private static func rotate(_ value: UInt32, _ bits: UInt32) -> UInt32 { (value >> bits) | (value << (32 - bits)) }
|
|
64
|
+
static func hash(_ data: Data) -> Data {
|
|
65
|
+
var message = [UInt8](data)
|
|
66
|
+
let bits = UInt64(message.count) * 8
|
|
67
|
+
message.append(0x80)
|
|
68
|
+
while message.count % 64 != 56 { message.append(0) }
|
|
69
|
+
for shift in stride(from: 56, through: 0, by: -8) { message.append(UInt8((bits >> shift) & 0xff)) }
|
|
70
|
+
var h: [UInt32] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
|
|
71
|
+
for offset in stride(from: 0, to: message.count, by: 64) {
|
|
72
|
+
var w = [UInt32](repeating: 0, count: 64)
|
|
73
|
+
for index in 0..<16 {
|
|
74
|
+
let start = offset + index * 4
|
|
75
|
+
w[index] = (UInt32(message[start]) << 24) | (UInt32(message[start + 1]) << 16) | (UInt32(message[start + 2]) << 8) | UInt32(message[start + 3])
|
|
76
|
+
}
|
|
77
|
+
for index in 16..<64 {
|
|
78
|
+
let s0 = rotate(w[index - 15], 7) ^ rotate(w[index - 15], 18) ^ (w[index - 15] >> 3)
|
|
79
|
+
let s1 = rotate(w[index - 2], 17) ^ rotate(w[index - 2], 19) ^ (w[index - 2] >> 10)
|
|
80
|
+
w[index] = w[index - 16] &+ s0 &+ w[index - 7] &+ s1
|
|
81
|
+
}
|
|
82
|
+
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]
|
|
83
|
+
for index in 0..<64 {
|
|
84
|
+
let s1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)
|
|
85
|
+
let ch = (e & f) ^ (~e & g)
|
|
86
|
+
let t1 = hh &+ s1 &+ ch &+ k[index] &+ w[index]
|
|
87
|
+
let s0 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)
|
|
88
|
+
let maj = (a & b) ^ (a & c) ^ (b & c)
|
|
89
|
+
let t2 = s0 &+ maj
|
|
90
|
+
hh = g; g = f; f = e; e = d &+ t1; d = c; c = b; b = a; a = t1 &+ t2
|
|
91
|
+
}
|
|
92
|
+
h[0] = h[0] &+ a; h[1] = h[1] &+ b; h[2] = h[2] &+ c; h[3] = h[3] &+ d
|
|
93
|
+
h[4] = h[4] &+ e; h[5] = h[5] &+ f; h[6] = h[6] &+ g; h[7] = h[7] &+ hh
|
|
94
|
+
}
|
|
95
|
+
return Data(h.flatMap { [UInt8(($0 >> 24) & 0xff), UInt8(($0 >> 16) & 0xff), UInt8(($0 >> 8) & 0xff), UInt8($0 & 0xff)] })
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
public enum OAuth {
|
|
100
|
+
static func base64url(_ data: Data) -> String {
|
|
101
|
+
data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
|
|
102
|
+
}
|
|
103
|
+
static func random(_ count: Int) -> Data {
|
|
104
|
+
var bytes = [UInt8](repeating: 0, count: count)
|
|
105
|
+
for index in bytes.indices { bytes[index] = UInt8.random(in: .min ... .max) }
|
|
106
|
+
return Data(bytes)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// A fresh S256 verifier and challenge, plus a state value, for one authorization attempt.
|
|
110
|
+
public static func createPKCE() -> PKCE {
|
|
111
|
+
let verifier = base64url(random(32))
|
|
112
|
+
return PKCE(codeVerifier: verifier, codeChallenge: base64url(SHA256.hash(Data(verifier.utf8))), state: base64url(random(32)))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// The browser navigation that starts consent. The person approves exact spaces and permissions there.
|
|
116
|
+
/// Use a registered redirect and validate state, callback origin/path and single consumption in the app.
|
|
117
|
+
/// Omission of authorizationDetails requests read-only access to an existing space.
|
|
118
|
+
/// url is the HTTP(S) service endpoint; redirectUri can be a registered app deep link.
|
|
119
|
+
public static func authorizationURL(url: URL, clientId: String, redirectUri: String, pkce: PKCE, scope: String? = nil, resource: String? = nil, authorizationDetails: SpaceAuthorizationDetails? = nil) throws -> URL {
|
|
120
|
+
guard let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme), url.host?.isEmpty == false else {
|
|
121
|
+
throw AdoorError(code: "INVALID_URL", message: "The ADoor service endpoint must use HTTP or HTTPS with a host.", status: 400)
|
|
122
|
+
}
|
|
123
|
+
var components = URLComponents(url: url.appendingPathComponent("oauth/authorize"), resolvingAgainstBaseURL: false)!
|
|
124
|
+
var items = [
|
|
125
|
+
URLQueryItem(name: "response_type", value: "code"),
|
|
126
|
+
URLQueryItem(name: "client_id", value: clientId),
|
|
127
|
+
URLQueryItem(name: "redirect_uri", value: redirectUri),
|
|
128
|
+
URLQueryItem(name: "code_challenge", value: pkce.codeChallenge),
|
|
129
|
+
URLQueryItem(name: "code_challenge_method", value: "S256"),
|
|
130
|
+
URLQueryItem(name: "state", value: pkce.state)
|
|
131
|
+
]
|
|
132
|
+
if let authorizationDetails { items.append(URLQueryItem(name: "authorization_details", value: String(decoding: try JSON.encode([authorizationDetails]), as: UTF8.self))) }
|
|
133
|
+
if let scope { items.append(URLQueryItem(name: "scope", value: scope)) }
|
|
134
|
+
if let resource { items.append(URLQueryItem(name: "resource", value: resource)) }
|
|
135
|
+
components.queryItems = items
|
|
136
|
+
return components.url!
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
static func tokenRequest(url: URL, fields: [(String, String)], session: URLSession) async throws -> Tokens {
|
|
140
|
+
var request = URLRequest(url: url.appendingPathComponent("oauth/token"))
|
|
141
|
+
request.httpMethod = "POST"
|
|
142
|
+
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
|
143
|
+
var allowed = CharacterSet.alphanumerics
|
|
144
|
+
allowed.insert(charactersIn: "-._~")
|
|
145
|
+
request.httpBody = Data(fields.map { "\($0.0)=\($0.1.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")" }.joined(separator: "&").utf8)
|
|
146
|
+
let received: (Data, URLResponse)
|
|
147
|
+
do { received = try await session.data(for: request, delegate: RedirectBlocker()) }
|
|
148
|
+
catch { throw AdoorError.network(error) }
|
|
149
|
+
let (data, response) = received
|
|
150
|
+
guard let http = response as? HTTPURLResponse else { throw AdoorError(code: "HTTP_INVALID", message: "The server returned no HTTP response.", status: 0) }
|
|
151
|
+
guard (200..<300).contains(http.statusCode) else { throw AdoorError.from(response: http, data: data) }
|
|
152
|
+
var tokens = try JSON.decode(Tokens.self, from: data)
|
|
153
|
+
tokens.issuedAt = Date()
|
|
154
|
+
return tokens
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
public static func exchangeCode(url: URL, clientId: String, code: String, redirectUri: String, codeVerifier: String, resource: String? = nil, session: URLSession = .shared) async throws -> Tokens {
|
|
158
|
+
var fields = [("grant_type", "authorization_code"), ("client_id", clientId), ("code", code), ("redirect_uri", redirectUri), ("code_verifier", codeVerifier)]
|
|
159
|
+
if let resource { fields.append(("resource", resource)) }
|
|
160
|
+
return try await tokenRequest(url: url, fields: fields, session: session)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
public static func refreshTokens(url: URL, clientId: String, refreshToken: String, resource: String? = nil, session: URLSession = .shared) async throws -> Tokens {
|
|
164
|
+
var fields = [("grant_type", "refresh_token"), ("client_id", clientId), ("refresh_token", refreshToken)]
|
|
165
|
+
if let resource { fields.append(("resource", resource)) }
|
|
166
|
+
return try await tokenRequest(url: url, fields: fields, session: session)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// A token source that refreshes ahead of expiry with one in-flight refresh shared by concurrent callers.
|
|
171
|
+
/// Refresh tokens rotate on every use; persist each rotation from `onTokens` (the Keychain is the right place).
|
|
172
|
+
public actor TokenProvider {
|
|
173
|
+
public private(set) var tokens: Tokens
|
|
174
|
+
private let url: URL
|
|
175
|
+
private let clientId: String
|
|
176
|
+
private let resource: String?
|
|
177
|
+
private let session: URLSession
|
|
178
|
+
private let leeway: TimeInterval
|
|
179
|
+
private let onTokens: (@Sendable (Tokens) async throws -> Void)?
|
|
180
|
+
private var refreshing: Task<String, Error>?
|
|
181
|
+
private var refreshFailure: AdoorError?
|
|
182
|
+
private var needsPersistence = false
|
|
183
|
+
|
|
184
|
+
public init(url: URL, clientId: String, tokens: Tokens, resource: String? = nil, session: URLSession = .shared, leeway: TimeInterval = 60, onTokens: (@Sendable (Tokens) async throws -> Void)? = nil) {
|
|
185
|
+
self.url = url
|
|
186
|
+
self.clientId = clientId
|
|
187
|
+
self.tokens = tokens
|
|
188
|
+
self.resource = resource
|
|
189
|
+
self.session = session
|
|
190
|
+
self.leeway = leeway
|
|
191
|
+
self.onTokens = onTokens
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
public func token() async throws -> String {
|
|
195
|
+
if let refreshFailure { throw refreshFailure }
|
|
196
|
+
// The shared task includes persistence, not only the HTTP rotation.
|
|
197
|
+
if let refreshing { return try await refreshing.value }
|
|
198
|
+
if !needsPersistence, let expiresAt = tokens.expiresAt, Date() < expiresAt.addingTimeInterval(-leeway) { return tokens.accessToken }
|
|
199
|
+
let task = Task { try await self.rotateAndPersist() }
|
|
200
|
+
refreshing = task
|
|
201
|
+
defer { refreshing = nil }
|
|
202
|
+
return try await task.value
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private func rotateAndPersist() async throws -> String {
|
|
206
|
+
if !needsPersistence {
|
|
207
|
+
do {
|
|
208
|
+
tokens = try await OAuth.refreshTokens(url: url, clientId: clientId, refreshToken: tokens.refreshToken, resource: resource, session: session)
|
|
209
|
+
needsPersistence = true
|
|
210
|
+
} catch {
|
|
211
|
+
// The response may have been lost after rotation committed.
|
|
212
|
+
// Reusing the consumed token revokes the entire family.
|
|
213
|
+
let failure = AdoorError(code: "REFRESH_UNCERTAIN", message: "Refresh did not complete safely. Reconnect before requesting another token.", status: 401)
|
|
214
|
+
refreshFailure = failure
|
|
215
|
+
throw failure
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
try await onTokens?(tokens)
|
|
219
|
+
needsPersistence = false
|
|
220
|
+
return tokens.accessToken
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// Use as `AdoorClient(url:token:)`'s source.
|
|
224
|
+
public nonisolated var source: TokenSource { .provider { [self] in try await self.token() } }
|
|
225
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Where a Mac mount is served. Linux keeps the FUSE driver.
|
|
4
|
+
public enum MacBackend: String, Equatable, Sendable {
|
|
5
|
+
case fileProvider = "file-provider"
|
|
6
|
+
case linuxFuse = "linux-fuse"
|
|
7
|
+
|
|
8
|
+
public static func choose(platformDarwin: Bool) -> MacBackend {
|
|
9
|
+
platformDarwin ? .fileProvider : .linuxFuse
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/// One File Provider domain for a workspace, a space, and a folder. The identifier holds no credential.
|
|
15
|
+
public struct DomainName: Equatable, Sendable {
|
|
16
|
+
public var identifier: String
|
|
17
|
+
public var displayName: String
|
|
18
|
+
public var cloudPath: String
|
|
19
|
+
|
|
20
|
+
public init(identifier: String, displayName: String, cloudPath: String) {
|
|
21
|
+
self.identifier = identifier
|
|
22
|
+
self.displayName = displayName
|
|
23
|
+
self.cloudPath = cloudPath
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// `space` is the space id the file API stores. `label` is only the name Finder shows.
|
|
27
|
+
public static func make(
|
|
28
|
+
home: String, workspace: String, space: String, scope: String, label: String? = nil, readOnly: Bool = false
|
|
29
|
+
) -> DomainName {
|
|
30
|
+
let shown = label ?? space
|
|
31
|
+
let leaf = scope.split(separator: "/").last.map(String.init) ?? shown
|
|
32
|
+
let display = "\(workspace) \(shown) \(leaf)"
|
|
33
|
+
let root = home.hasSuffix("/") ? String(home.dropLast()) : home
|
|
34
|
+
let scopeKey = scope.replacingOccurrences(of: "/", with: "\u{1e}")
|
|
35
|
+
var parts = ["adoor", workspace, space, scopeKey]
|
|
36
|
+
if readOnly { parts.append("read-only") }
|
|
37
|
+
return DomainName(
|
|
38
|
+
identifier: parts.joined(separator: "\u{1f}"),
|
|
39
|
+
displayName: display,
|
|
40
|
+
cloudPath: root + "/Library/CloudStorage/ADoor-" + display)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
public static func parse(_ identifier: String) -> (workspace: String, space: String, scope: String, readOnly: Bool)? {
|
|
44
|
+
let parts = identifier.split(separator: "\u{1f}", omittingEmptySubsequences: false).map(String.init)
|
|
45
|
+
let readOnly = parts.count == 5 && parts[4] == "read-only"
|
|
46
|
+
guard (parts.count == 4 || readOnly), parts[0] == "adoor" else { return nil }
|
|
47
|
+
return (parts[1], parts[2], parts[3].replacingOccurrences(of: "\u{1e}", with: "/"), readOnly)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
public enum FinderPhase: String, Equatable, Sendable {
|
|
52
|
+
case downloaded
|
|
53
|
+
case syncing
|
|
54
|
+
case error
|
|
55
|
+
|
|
56
|
+
public var label: String {
|
|
57
|
+
switch self {
|
|
58
|
+
case .downloaded: return "Downloaded"
|
|
59
|
+
case .syncing: return "Syncing"
|
|
60
|
+
case .error: return "Couldn't reach the server"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// A conflict is a decision about a file, and an unmounted folder is simply not in Finder.
|
|
65
|
+
/// Only a folder this Mac cannot reach is an error.
|
|
66
|
+
public static func phase(for sync: SyncWord) -> FinderPhase {
|
|
67
|
+
switch sync {
|
|
68
|
+
case .current, .conflict, .unmounted: return .downloaded
|
|
69
|
+
case .syncing: return .syncing
|
|
70
|
+
case .offline: return .error
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
public struct ProviderItem: Equatable, Sendable {
|
|
76
|
+
public var identifier: String
|
|
77
|
+
public var parent: String
|
|
78
|
+
public var name: String
|
|
79
|
+
public var isDirectory: Bool
|
|
80
|
+
public var writable: Bool
|
|
81
|
+
public var size: Int
|
|
82
|
+
public var generation: Int
|
|
83
|
+
public var phase: FinderPhase
|
|
84
|
+
public var message: String?
|
|
85
|
+
|
|
86
|
+
public init(
|
|
87
|
+
identifier: String, parent: String, name: String, isDirectory: Bool, size: Int, generation: Int,
|
|
88
|
+
phase: FinderPhase, message: String? = nil, writable: Bool = true
|
|
89
|
+
) {
|
|
90
|
+
self.identifier = identifier
|
|
91
|
+
self.parent = parent
|
|
92
|
+
self.name = name
|
|
93
|
+
self.isDirectory = isDirectory
|
|
94
|
+
self.writable = writable
|
|
95
|
+
self.size = size
|
|
96
|
+
self.generation = generation
|
|
97
|
+
self.phase = phase
|
|
98
|
+
self.message = message
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
public var contentVersion: Data {
|
|
102
|
+
var value = UInt64(generation).bigEndian
|
|
103
|
+
return Data(bytes: &value, count: MemoryLayout<UInt64>.size)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
public var isDownloaded: Bool { phase == .downloaded }
|
|
107
|
+
public var isSyncing: Bool { phase == .syncing }
|
|
108
|
+
public var hasError: Bool { phase == .error }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
public enum ProviderMap {
|
|
112
|
+
public static let root = "root"
|
|
113
|
+
|
|
114
|
+
/// A rename receipt contains the new location and generation, but omits file type, size and mode.
|
|
115
|
+
public static func renamed(_ original: NodeAttr, receipt: NodeAttr, parent: String) throws -> ProviderItem {
|
|
116
|
+
guard original.id == receipt.id else { throw TreeError.invalid }
|
|
117
|
+
var model = item(original, parent: parent, phase: .downloaded)
|
|
118
|
+
model.name = receipt.name
|
|
119
|
+
model.generation = receipt.generation
|
|
120
|
+
return model
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
public static func item(_ node: NodeAttr, parent: String, phase: FinderPhase, message: String? = nil) -> ProviderItem {
|
|
124
|
+
ProviderItem(
|
|
125
|
+
identifier: node.idString, parent: parent, name: node.name, isDirectory: node.kind == .directory,
|
|
126
|
+
size: node.size, generation: node.generation, phase: phase, message: message, writable: node.access.canWrite)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
public struct ProviderListing: Equatable, Sendable {
|
|
131
|
+
public var items: [ProviderItem]
|
|
132
|
+
public var nextCursor: String?
|
|
133
|
+
|
|
134
|
+
public init(items: [ProviderItem], nextCursor: String?) {
|
|
135
|
+
self.items = items
|
|
136
|
+
self.nextCursor = nextCursor
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
public enum ProviderPages {
|
|
141
|
+
public static func remote(_ page: RemotePage, parent: String, phase: FinderPhase) -> ProviderListing {
|
|
142
|
+
ProviderListing(
|
|
143
|
+
items: page.entries.map { ProviderMap.item($0, parent: parent, phase: phase) },
|
|
144
|
+
nextCursor: page.nextCursor)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/// A local window. The cursor is the next index, so a caller can ask for the following page.
|
|
148
|
+
public static func window(
|
|
149
|
+
entries: [NodeAttr], parent: String, cursor: String?, limit: Int, phase: FinderPhase
|
|
150
|
+
) -> ProviderListing {
|
|
151
|
+
let start = min(entries.count, max(0, Int(cursor ?? "") ?? 0))
|
|
152
|
+
let end = min(entries.count, start + max(1, limit))
|
|
153
|
+
let items = entries[start..<end].map { ProviderMap.item($0, parent: parent, phase: phase) }
|
|
154
|
+
return ProviderListing(items: items, nextCursor: end < entries.count ? String(end) : nil)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
public enum DomainFlag {
|
|
159
|
+
public static let readOnly = "readOnly"
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
public struct ProviderAccess: Equatable, Sendable {
|
|
163
|
+
public var readOnly: Bool
|
|
164
|
+
|
|
165
|
+
public init(userInfo: [String: Bool]) {
|
|
166
|
+
readOnly = userInfo[DomainFlag.readOnly] == true
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/// The identifier carries the flag on every macOS the extension runs. `stored` is the domain userInfo when that API exists.
|
|
170
|
+
public static func userInfo(identifier: String, stored: [String: Bool]) -> [String: Bool] {
|
|
171
|
+
var info = stored
|
|
172
|
+
if DomainName.parse(identifier)?.readOnly == true { info[DomainFlag.readOnly] = true }
|
|
173
|
+
return info
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
public func requireWrite() throws {
|
|
177
|
+
if readOnly { throw TreeError.readOnly }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
public enum VersionGeneration {
|
|
182
|
+
public static func decode(_ data: Data) -> Int? {
|
|
183
|
+
guard data.count == MemoryLayout<UInt64>.size else { return nil }
|
|
184
|
+
var value: UInt64 = 0
|
|
185
|
+
let raw = data.prefix(MemoryLayout<UInt64>.size)
|
|
186
|
+
_ = withUnsafeMutableBytes(of: &value) { buffer in raw.copyBytes(to: buffer) }
|
|
187
|
+
return Int(exactly: UInt64(bigEndian: value))
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
public enum UploadPlan: Equatable, Sendable {
|
|
192
|
+
case store(expectedGeneration: Int)
|
|
193
|
+
case conflict(copyName: String, serverGeneration: Int)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
public enum GenerationGate {
|
|
197
|
+
public static func plan(expected: Int, server: Int, name: String, identity: String) -> UploadPlan {
|
|
198
|
+
if expected == server { return .store(expectedGeneration: expected) }
|
|
199
|
+
return .conflict(copyName: ConflictName.make(original: name, id: identity), serverGeneration: server)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
public struct EnumeratorWake: Equatable, Sendable {
|
|
204
|
+
public var containers: [String]
|
|
205
|
+
|
|
206
|
+
public init(containers: [String]) { self.containers = containers }
|
|
207
|
+
|
|
208
|
+
public static func forChange(_ change: FileChange) -> EnumeratorWake {
|
|
209
|
+
EnumeratorWake(containers: ["workingSet", change.inodeId])
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Durable key/value storage for cached rows and the outbox. Values are strings so any store fits.
|
|
4
|
+
public protocol Storage: Sendable {
|
|
5
|
+
func get(_ key: String) async throws -> String?
|
|
6
|
+
func set(_ key: String, _ value: String) async throws
|
|
7
|
+
func delete(_ key: String) async throws
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/// Nothing survives the process; the default when no storage is given.
|
|
11
|
+
public actor MemoryStorage: Storage {
|
|
12
|
+
private var values: [String: String] = [:]
|
|
13
|
+
public init() {}
|
|
14
|
+
public func get(_ key: String) -> String? { values[key] }
|
|
15
|
+
public func set(_ key: String, _ value: String) { values[key] = value }
|
|
16
|
+
public func delete(_ key: String) { values.removeValue(forKey: key) }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// One file per key in a directory, for example Application Support. Writes are atomic.
|
|
20
|
+
public actor FileStorage: Storage {
|
|
21
|
+
private let directory: URL
|
|
22
|
+
public init(directory: URL) throws {
|
|
23
|
+
self.directory = directory
|
|
24
|
+
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
25
|
+
}
|
|
26
|
+
private func file(_ key: String) -> URL {
|
|
27
|
+
var allowed = CharacterSet.alphanumerics
|
|
28
|
+
allowed.insert(charactersIn: "-_.")
|
|
29
|
+
return directory.appendingPathComponent((key.addingPercentEncoding(withAllowedCharacters: allowed) ?? key) + ".json")
|
|
30
|
+
}
|
|
31
|
+
public func get(_ key: String) throws -> String? {
|
|
32
|
+
let url = file(key)
|
|
33
|
+
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
|
34
|
+
return String(data: try Data(contentsOf: url), encoding: .utf8)
|
|
35
|
+
}
|
|
36
|
+
public func set(_ key: String, _ value: String) throws { try Data(value.utf8).write(to: file(key), options: .atomic) }
|
|
37
|
+
public func delete(_ key: String) throws {
|
|
38
|
+
let url = file(key)
|
|
39
|
+
if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) }
|
|
40
|
+
}
|
|
41
|
+
}
|