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.
Files changed (41) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +2 -2
  3. package/dist/adoor.mjs +105 -84
  4. package/native/LICENSE +662 -0
  5. package/native/README.md +12 -0
  6. package/native/darwin/ADoorService.app/Contents/Info.plist +57 -0
  7. package/native/darwin/ADoorService.app/Contents/MacOS/ADoorService +0 -0
  8. package/native/darwin/ADoorService.app/Contents/PkgInfo +1 -0
  9. package/native/darwin/ADoorService.app/Contents/_CodeSignature/CodeResources +123 -0
  10. package/native/darwin/ADoorService.app/Contents/embedded.provisionprofile +0 -0
  11. package/native/source/Package.swift +6 -0
  12. package/native/source/sdk/LICENSE +21 -0
  13. package/native/source/sdk/Package.swift +14 -0
  14. package/native/source/sdk/Sources/ADoor/AdoorClient.swift +270 -0
  15. package/native/source/sdk/Sources/ADoor/AdoorError.swift +60 -0
  16. package/native/source/sdk/Sources/ADoor/Changes.swift +202 -0
  17. package/native/source/sdk/Sources/ADoor/DesktopSessionState.swift +73 -0
  18. package/native/source/sdk/Sources/ADoor/DeviceFlow.swift +70 -0
  19. package/native/source/sdk/Sources/ADoor/FolderCatalog.swift +49 -0
  20. package/native/source/sdk/Sources/ADoor/JSONValue.swift +70 -0
  21. package/native/source/sdk/Sources/ADoor/LocalStore.swift +474 -0
  22. package/native/source/sdk/Sources/ADoor/Models.swift +146 -0
  23. package/native/source/sdk/Sources/ADoor/MountModel.swift +896 -0
  24. package/native/source/sdk/Sources/ADoor/OAuth.swift +225 -0
  25. package/native/source/sdk/Sources/ADoor/Provider.swift +211 -0
  26. package/native/source/sdk/Sources/ADoor/Storage.swift +41 -0
  27. package/native/source/sdk/Sources/ADoor/SyncTree.swift +501 -0
  28. package/native/source/sdk/Sources/ADoor/Trash.swift +283 -0
  29. package/native/source/sdk/Tests/ADoorTests/ADoorTests.swift +182 -0
  30. package/native/source/sdk/Tests/ADoorTests/DesktopSessionStateTests.swift +46 -0
  31. package/native/source/sdk/Tests/ADoorTests/MountTests.swift +560 -0
  32. package/native/source/sdk/Tests/ADoorTests/RegressionTests.swift +360 -0
  33. package/native/source/service/DesktopSession.swift +241 -0
  34. package/native/source/service/DeviceClient.swift +53 -0
  35. package/native/source/service/Domains.swift +182 -0
  36. package/native/source/service/FolderRefresh.swift +37 -0
  37. package/native/source/service/KeychainStore.swift +74 -0
  38. package/native/source/service/LocalSessionSocket.swift +142 -0
  39. package/native/source/service/ServiceMain.swift +14 -0
  40. package/native/source/service/ServiceMounts.swift +34 -0
  41. package/package.json +12 -3
@@ -0,0 +1,53 @@
1
+ import ADoor
2
+ import Foundation
3
+ #if canImport(FoundationNetworking)
4
+ import FoundationNetworking
5
+ #endif
6
+
7
+ struct DeviceReply: Sendable {
8
+ let state: DevicePoll
9
+ let home: JSONValue?
10
+ }
11
+
12
+ enum DeviceClient {
13
+ static func start(origin: URL, name: String = "ADoor on this Mac", operatorAccess: Bool = false) async throws -> DeviceStart {
14
+ let json = try await post(origin: origin, path: "api/auth/device", body: ["name": .string(name), "operator": .bool(operatorAccess)])
15
+ return try DeviceFlow.parseStart(json, origin: origin)
16
+ }
17
+
18
+ static func poll(origin: URL, deviceCode: String) async throws -> DeviceReply {
19
+ let json = try await post(origin: origin, path: "api/auth/device/poll", body: ["deviceCode": .string(deviceCode)])
20
+ let state = try DeviceFlow.parsePoll(json)
21
+ let home: JSONValue?
22
+ if let id = json["connection"]?["id"]?.stringValue, let workspace = json["info"]?["workspace"]?["id"]?.stringValue {
23
+ home = ["id": .string(id), "workspace": .string(workspace)]
24
+ } else { home = nil }
25
+ return DeviceReply(state: state, home: home)
26
+ }
27
+
28
+ private static func post(origin: URL, path: String, body: [String: JSONValue]) async throws -> JSONValue {
29
+ var request = URLRequest(url: origin.appendingPathComponent(path))
30
+ request.httpMethod = "POST"
31
+ request.httpBody = try JSONEncoder().encode(body)
32
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
33
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
34
+ let configuration = URLSessionConfiguration.ephemeral
35
+ configuration.timeoutIntervalForRequest = 25
36
+ let session = URLSession(configuration: configuration, delegate: RedirectStop(), delegateQueue: nil)
37
+ defer { session.finishTasksAndInvalidate() }
38
+ let (data, response) = try await session.data(for: request)
39
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
40
+ throw AdoorError(code: "INVALID_RESPONSE", message: "Sign-in did not complete.", status: (response as? HTTPURLResponse)?.statusCode ?? 0)
41
+ }
42
+ return try JSONDecoder().decode(JSONValue.self, from: data)
43
+ }
44
+ }
45
+
46
+ final class RedirectStop: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
47
+ func urlSession(
48
+ _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
49
+ newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void
50
+ ) {
51
+ completionHandler(nil)
52
+ }
53
+ }
@@ -0,0 +1,182 @@
1
+ import ADoor
2
+ import CryptoKit
3
+ import FileProvider
4
+ import Foundation
5
+
6
+ enum DomainSync {
7
+ static func bind(_ identifier: String, token: String, server: String) async throws {
8
+ let previous = KeychainStore.load(domain: identifier)
9
+ if let previous {
10
+ guard previous.server == server else { throw TreeError.unavailable("This Finder folder belongs to another server.") }
11
+ if previous.token == token { return }
12
+ }
13
+ try KeychainStore.save(token: token, server: server, domain: identifier)
14
+ if let domain = try? await NSFileProviderManager.domains().first(where: { $0.identifier.rawValue == identifier }) {
15
+ await resume(domain)
16
+ }
17
+ }
18
+
19
+ static func restoreSignIn(token: String, server: String) async throws {
20
+ let previous = KeychainStore.load()
21
+ try KeychainStore.save(token: token, server: server)
22
+ let registry = MountPaths.registry(home: FileManager.default.homeDirectoryForCurrentUser, platformDarwin: true)
23
+ guard let data = try? Data(contentsOf: registry), let book = try? MountRegistry.decode(data),
24
+ let domains = try? await NSFileProviderManager.domains() else { return }
25
+ for mount in book.mounts where mount.server == server && mount.state == "mounted" {
26
+ guard let domain = domains.first(where: { $0.identifier.rawValue == mount.id }) else { continue }
27
+ let saved = KeychainStore.load(domain: mount.id)
28
+ guard saved == nil || (saved?.server == previous?.server && saved?.token == previous?.token) else { continue }
29
+ try await bind(mount.id, token: token, server: server)
30
+ await resume(domain)
31
+ }
32
+ }
33
+
34
+ private static func resume(_ domain: NSFileProviderDomain) async {
35
+ guard let manager = NSFileProviderManager(for: domain) else { return }
36
+ try? await manager.signalErrorResolved(NSFileProviderError(.notAuthenticated))
37
+ try? await manager.signalEnumerator(for: .workingSet)
38
+ }
39
+
40
+ static func register(_ name: DomainName) async throws -> URL {
41
+ let existing = try await NSFileProviderManager.domains().first { $0.identifier.rawValue == name.identifier }
42
+ let domain: NSFileProviderDomain
43
+ if let existing { domain = existing }
44
+ else { domain = try await add(name) }
45
+ guard let manager = NSFileProviderManager(for: domain) else { throw CocoaError(.fileNoSuchFile) }
46
+ let location = try await manager.getUserVisibleURL(for: .rootContainer)
47
+ if existing == nil {
48
+ try await manager.signalEnumerator(for: .rootContainer)
49
+ try await waitForRoot(location, name: name)
50
+ }
51
+ return location
52
+ }
53
+
54
+ /// Finder requires unique volume names even when the remote folders have distinct identifiers.
55
+ private static func add(_ name: DomainName) async throws -> NSFileProviderDomain {
56
+ let parent = DomainName.parse(name.identifier)?.scope.split(separator: "/").dropLast().last
57
+ let qualified = parent.map { "\(name.displayName) (\($0))" } ?? name.displayName
58
+ let digest = SHA256.hash(data: Data(name.identifier.utf8)).prefix(6).map { String(format: "%02x", $0) }.joined()
59
+ let labels = [name.displayName] + (qualified == name.displayName ? [] : [qualified]) + ["\(qualified) \(digest)"]
60
+ for label in labels {
61
+ let domain = NSFileProviderDomain(identifier: .init(rawValue: name.identifier), displayName: label)
62
+ domain.supportsSyncingTrash = false
63
+ do {
64
+ try await NSFileProviderManager.add(domain)
65
+ return domain
66
+ } catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSFileWriteFileExistsError {
67
+ if let existing = try await NSFileProviderManager.domains().first(where: { $0.identifier == domain.identifier }) { return existing }
68
+ if label == labels.last { throw error }
69
+ }
70
+ }
71
+ throw CocoaError(.fileWriteFileExists)
72
+ }
73
+
74
+ /// macOS can return the domain URL before its initial directory entries are visible.
75
+ private static func waitForRoot(_ location: URL, name: DomainName) async throws {
76
+ guard let saved = KeychainStore.load(domain: name.identifier), let url = URL(string: saved.server),
77
+ let fields = DomainName.parse(name.identifier) else { throw TreeError.unavailable("Sign in to open this folder.") }
78
+ let client = AdoorClient(url: url, accessKey: saved.token)
79
+ let deadline = ContinuousClock.now + .seconds(30)
80
+ var checkRemoteAt = ContinuousClock.now
81
+ var sample: String?
82
+ repeat {
83
+ if ContinuousClock.now >= checkRemoteAt {
84
+ let page = try await client.fsList(spaceId: fields.space, path: fields.scope, limit: 1)
85
+ guard let entries = page["entries"]?.arrayValue else { throw TreeError.invalid }
86
+ sample = entries.first?["name"]?.stringValue
87
+ checkRemoteAt = .now + .seconds(3)
88
+ }
89
+ if let first = sample {
90
+ if FileManager.default.fileExists(atPath: location.appendingPathComponent(first).path) { return }
91
+ } else if (try? FileManager.default.contentsOfDirectory(atPath: location.path)) != nil { return }
92
+ try await Task.sleep(for: .milliseconds(200))
93
+ } while ContinuousClock.now < deadline
94
+ throw TreeError.unavailable("Finder is still opening this folder.")
95
+ }
96
+
97
+ static func unregister(_ identifier: String) async throws {
98
+ let domains = try await NSFileProviderManager.domains()
99
+ if let domain = domains.first(where: { $0.identifier.rawValue == identifier }) { try await remove(domain) }
100
+ }
101
+
102
+ static func remove(_ domain: NSFileProviderDomain) async throws {
103
+ _ = try await NSFileProviderManager.remove(domain, mode: .preserveDirtyUserData)
104
+ KeychainStore.clear(domain: domain.identifier.rawValue)
105
+ }
106
+
107
+ static func sync(_ mounts: [MountRecord]) {
108
+ Task {
109
+ guard let domains = try? await NSFileProviderManager.domains() else { return }
110
+ for mount in mounts where mount.backend == MacBackend.fileProvider.rawValue {
111
+ guard let parsed = DomainName.parse(mount.id) else { continue }
112
+ let existing = domains.first { $0.identifier.rawValue == mount.id }
113
+ if mount.state == "mounted", KeychainStore.load(domain: mount.id) == nil,
114
+ let saved = KeychainStore.load(), saved.server == mount.server {
115
+ do { try await bind(mount.id, token: saved.token, server: saved.server) } catch { continue }
116
+ if let existing { await resume(existing) }
117
+ }
118
+ // The native app and helper publish these rows after File Provider finishes the operation.
119
+ // Replaying an older row can unregister a folder that the next command has just mounted.
120
+ if mount.registeredWithFinder == true { continue }
121
+ if mount.state == "unmounted", let existing {
122
+ try? await remove(existing)
123
+ } else if mount.state == "mounted", existing == nil {
124
+ let name = DomainName.make(home: NSHomeDirectory(), workspace: parsed.workspace, space: parsed.space,
125
+ scope: parsed.scope, label: mount.space, readOnly: mount.readOnly || parsed.readOnly)
126
+ _ = try? await register(name)
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ /// Finder can suspend an idle extension and its event stream. The menu-bar app
134
+ /// also checks the committed cursor so a remote edit can wake that extension.
135
+ @MainActor
136
+ final class FinderChangeMonitor {
137
+ private struct Account: Hashable, Sendable {
138
+ let server: URL
139
+ let token: String
140
+ }
141
+ private struct Watch {
142
+ let folders: Set<String>
143
+ let task: Task<Void, Never>
144
+ }
145
+ private var watches: [Account: Watch] = [:]
146
+
147
+ deinit { for watch in watches.values { watch.task.cancel() } }
148
+
149
+ func update(_ mounts: [MountRecord]) {
150
+ var groups: [Account: Set<String>] = [:]
151
+ for mount in mounts where mount.backend == MacBackend.fileProvider.rawValue && mount.state == "mounted" {
152
+ guard let saved = KeychainStore.load(domain: mount.id), saved.server == mount.server,
153
+ let url = URL(string: saved.server) else { continue }
154
+ groups[Account(server: url, token: saved.token), default: []].insert(mount.id)
155
+ }
156
+ for (account, watch) in watches where groups[account] != watch.folders {
157
+ watch.task.cancel()
158
+ watches.removeValue(forKey: account)
159
+ }
160
+ for (account, folders) in groups where watches[account] == nil {
161
+ let task = Task { await Self.follow(account, folders: folders) }
162
+ watches[account] = Watch(folders: folders, task: task)
163
+ }
164
+ }
165
+
166
+ nonisolated private static func follow(_ account: Account, folders: Set<String>) async {
167
+ let client = AdoorClient(url: account.server, accessKey: account.token)
168
+ var previous: String?
169
+ while !Task.isCancelled {
170
+ var interval = 15
171
+ do {
172
+ let head = try await client.changesHead()
173
+ if head != previous {
174
+ try Task.checkCancellation()
175
+ try await FolderRefresh.signal(folders)
176
+ previous = head
177
+ }
178
+ } catch { interval = 60 }
179
+ do { try await Task.sleep(for: .seconds(interval)) } catch { return }
180
+ }
181
+ }
182
+ }
@@ -0,0 +1,37 @@
1
+ import FileProvider
2
+ import Foundation
3
+
4
+ enum FolderRefresh {
5
+ static func signal(_ identifiers: Set<String>) async throws {
6
+ guard !identifiers.isEmpty else { return }
7
+ if Bundle.main.executableURL?.lastPathComponent == "ADoorService" {
8
+ try await Task.detached { try runHelper(identifiers) }.value
9
+ return
10
+ }
11
+ for domain in try await NSFileProviderManager.domains() where identifiers.contains(domain.identifier.rawValue) {
12
+ guard let manager = NSFileProviderManager(for: domain) else { continue }
13
+ try await manager.signalEnumerator(for: .rootContainer)
14
+ try await manager.signalEnumerator(for: .workingSet)
15
+ }
16
+ }
17
+
18
+ private static func runHelper(_ identifiers: Set<String>) throws {
19
+ let process = Process()
20
+ process.executableURL = URL(fileURLWithPath: "/Applications/ADoor.app/Contents/MacOS/ADoor")
21
+ process.arguments = ["--refresh-domains"]
22
+ let pipe = Pipe()
23
+ process.standardInput = pipe
24
+ process.standardOutput = FileHandle.nullDevice
25
+ process.standardError = FileHandle.nullDevice
26
+ let completed = DispatchSemaphore(value: 0)
27
+ process.terminationHandler = { _ in completed.signal() }
28
+ try process.run()
29
+ try pipe.fileHandleForWriting.write(contentsOf: JSONEncoder().encode(Array(identifiers)))
30
+ try pipe.fileHandleForWriting.close()
31
+ guard completed.wait(timeout: .now() + 30) == .success else {
32
+ process.terminate()
33
+ throw CocoaError(.fileReadUnknown)
34
+ }
35
+ guard process.terminationStatus == 0 else { throw CocoaError(.fileReadUnknown) }
36
+ }
37
+ }
@@ -0,0 +1,74 @@
1
+ import ADoor
2
+ import Foundation
3
+ import Security
4
+
5
+ enum KeychainStore {
6
+ static func save(token: String, server: String, domain: String? = nil) throws {
7
+ let payload = try JSONSerialization.data(withJSONObject: ["token": token, "server": server])
8
+ let key = query(account: account(for: domain))
9
+ let values = [kSecValueData as String: payload]
10
+ var status = SecItemUpdate(key as CFDictionary, values as CFDictionary)
11
+ if status == errSecItemNotFound {
12
+ status = SecItemAdd(key.merging(values) { _, new in new } as CFDictionary, nil)
13
+ if status == errSecDuplicateItem { status = SecItemUpdate(key as CFDictionary, values as CFDictionary) }
14
+ }
15
+ if status != errSecSuccess { throw TreeError.unavailable("The credential could not be saved on this Mac.") }
16
+ }
17
+
18
+ static func load(domain: String? = nil) -> (token: String, server: String)? {
19
+ var query = query(account: account(for: domain))
20
+ query[kSecReturnData as String] = true
21
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
22
+ var item: CFTypeRef?
23
+ guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let data = item as? Data,
24
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: String],
25
+ let token = object["token"], let server = object["server"], !token.isEmpty else { return nil }
26
+ return (token, server)
27
+ }
28
+
29
+ static func sessionData() throws -> Data? {
30
+ var query = query(account: "desktop-session")
31
+ query[kSecReturnData as String] = true
32
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
33
+ var item: CFTypeRef?
34
+ let status = SecItemCopyMatching(query as CFDictionary, &item)
35
+ if status == errSecItemNotFound { return nil }
36
+ guard status == errSecSuccess, let data = item as? Data else {
37
+ throw TreeError.unavailable("Unlock this Mac to open the saved connections.")
38
+ }
39
+ return data
40
+ }
41
+
42
+ static func saveSession(_ data: Data) throws {
43
+ let key = query(account: "desktop-session")
44
+ let values = [kSecValueData as String: data]
45
+ var status = SecItemUpdate(key as CFDictionary, values as CFDictionary)
46
+ if status == errSecItemNotFound {
47
+ status = SecItemAdd(key.merging(values) { _, new in new } as CFDictionary, nil)
48
+ }
49
+ guard status == errSecSuccess else { throw TreeError.unavailable("The connections could not be saved on this Mac.") }
50
+ }
51
+
52
+ static func clearActive() {
53
+ SecItemDelete(query(account: KeychainPlacement.account) as CFDictionary)
54
+ }
55
+
56
+ static func account(for domain: String?) -> String {
57
+ domain.map { "finder:" + $0 } ?? KeychainPlacement.account
58
+ }
59
+
60
+ static func clear(domain: String) {
61
+ SecItemDelete(query(account: account(for: domain)) as CFDictionary)
62
+ }
63
+
64
+ static func query(account: String) -> [String: Any] {
65
+ [
66
+ kSecClass as String: kSecClassGenericPassword,
67
+ kSecUseDataProtectionKeychain as String: true,
68
+ kSecAttrService as String: KeychainPlacement.service,
69
+ kSecAttrAccount as String: account,
70
+ kSecAttrAccessGroup as String: KeychainPlacement.accessGroup,
71
+ kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
72
+ ]
73
+ }
74
+ }
@@ -0,0 +1,142 @@
1
+ import ADoor
2
+ import Darwin
3
+ import Foundation
4
+
5
+ final class LocalSessionSocket: @unchecked Sendable {
6
+ static var path: String {
7
+ NSHomeDirectory() + "/Library/Application Support/ADoor/session.sock"
8
+ }
9
+ private let source: DispatchSourceRead
10
+ private let lock: Int32
11
+
12
+ init(path: String = LocalSessionSocket.path, handler: @escaping @Sendable (JSONValue) async -> JSONValue) throws {
13
+ let directory = URL(fileURLWithPath: path).deletingLastPathComponent().path
14
+ try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true,
15
+ attributes: [.posixPermissions: 0o700])
16
+ var info = stat()
17
+ guard lstat(directory, &info) == 0, info.st_uid == getuid(), info.st_mode & 0o077 == 0,
18
+ info.st_mode & S_IFMT == S_IFDIR else { throw Self.unavailable() }
19
+ lock = Darwin.open(path + ".lock", O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600)
20
+ guard lock >= 0 else { throw Self.unavailable() }
21
+ guard fstat(lock, &info) == 0, info.st_uid == getuid(), info.st_mode & 0o077 == 0,
22
+ info.st_mode & S_IFMT == S_IFREG, flock(lock, LOCK_EX | LOCK_NB) == 0 else {
23
+ close(lock)
24
+ throw Self.unavailable()
25
+ }
26
+ let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
27
+ do {
28
+ guard descriptor >= 0 else { throw Self.unavailable() }
29
+ Self.configure(descriptor)
30
+ if lstat(path, &info) == 0 {
31
+ guard info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK else { throw Self.unavailable() }
32
+ guard unlink(path) == 0 else { throw Self.unavailable() }
33
+ } else if errno != ENOENT { throw Self.unavailable() }
34
+ let bound = try Self.address(path) { Darwin.bind(descriptor, $0, $1) }
35
+ guard bound == 0, chmod(path, 0o600) == 0, listen(descriptor, 16) == 0 else { throw Self.unavailable() }
36
+ } catch {
37
+ close(descriptor)
38
+ close(lock)
39
+ throw error
40
+ }
41
+ source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: .global(qos: .userInitiated))
42
+ let capacity = DispatchSemaphore(value: 16)
43
+ source.setEventHandler {
44
+ let peer = accept(descriptor, nil, nil)
45
+ guard peer >= 0 else { return }
46
+ var uid: uid_t = 0
47
+ var gid: gid_t = 0
48
+ guard getpeereid(peer, &uid, &gid) == 0, uid == getuid(), capacity.wait(timeout: .now()) == .success else {
49
+ close(peer)
50
+ return
51
+ }
52
+ DispatchQueue.global(qos: .userInitiated).async {
53
+ do {
54
+ Self.configure(peer)
55
+ let request = try Self.read(peer)
56
+ Task {
57
+ let response = await handler(request)
58
+ DispatchQueue.global(qos: .userInitiated).async {
59
+ defer { close(peer); capacity.signal() }
60
+ try? Self.write(response, to: peer)
61
+ }
62
+ }
63
+ } catch { close(peer); capacity.signal() }
64
+ }
65
+ }
66
+ let held = lock
67
+ source.setCancelHandler { close(descriptor); close(held) }
68
+ source.resume()
69
+ }
70
+
71
+ deinit { source.cancel() }
72
+
73
+ static func request(_ value: JSONValue, path: String = LocalSessionSocket.path) async throws -> JSONValue {
74
+ try await withCheckedThrowingContinuation { continuation in
75
+ DispatchQueue.global(qos: .userInitiated).async {
76
+ let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
77
+ defer { close(descriptor) }
78
+ do {
79
+ guard descriptor >= 0 else { throw unavailable() }
80
+ configure(descriptor)
81
+ guard try address(path, { connect(descriptor, $0, $1) }) == 0 else { throw unavailable() }
82
+ var uid: uid_t = 0
83
+ var gid: gid_t = 0
84
+ guard getpeereid(descriptor, &uid, &gid) == 0, uid == getuid() else { throw unavailable() }
85
+ try write(value, to: descriptor)
86
+ continuation.resume(returning: try read(descriptor))
87
+ } catch { continuation.resume(throwing: error) }
88
+ }
89
+ }
90
+ }
91
+
92
+ private static func configure(_ descriptor: Int32) {
93
+ var timeout = timeval(tv_sec: 35, tv_usec: 0)
94
+ setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
95
+ setsockopt(descriptor, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
96
+ var enabled: Int32 = 1
97
+ setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size))
98
+ _ = fcntl(descriptor, F_SETFD, FD_CLOEXEC)
99
+ }
100
+
101
+ private static func address(_ path: String, _ body: (UnsafePointer<sockaddr>, socklen_t) -> Int32) throws -> Int32 {
102
+ var address = sockaddr_un()
103
+ address.sun_family = sa_family_t(AF_UNIX)
104
+ address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
105
+ let bytes = Array(path.utf8) + [0]
106
+ guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw unavailable() }
107
+ withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: bytes) }
108
+ return withUnsafePointer(to: &address) {
109
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { body($0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
110
+ }
111
+ }
112
+
113
+ private static func read(_ descriptor: Int32) throws -> JSONValue {
114
+ var data = Data()
115
+ var buffer = [UInt8](repeating: 0, count: 8192)
116
+ while data.count <= 4 * 1024 * 1024 {
117
+ let count = Darwin.read(descriptor, &buffer, buffer.count)
118
+ guard count > 0 else { throw unavailable() }
119
+ data.append(contentsOf: buffer.prefix(count))
120
+ if let end = data.firstIndex(of: 10) { return try JSONDecoder().decode(JSONValue.self, from: data[..<end]) }
121
+ }
122
+ throw unavailable()
123
+ }
124
+
125
+ private static func write(_ value: JSONValue, to descriptor: Int32) throws {
126
+ var data = try JSONEncoder().encode(value)
127
+ data.append(10)
128
+ guard data.count <= 4 * 1024 * 1024 else { throw unavailable() }
129
+ try data.withUnsafeBytes { bytes in
130
+ var offset = 0
131
+ while offset < bytes.count {
132
+ let count = Darwin.write(descriptor, bytes.baseAddress!.advanced(by: offset), bytes.count - offset)
133
+ guard count > 0 else { throw unavailable() }
134
+ offset += count
135
+ }
136
+ }
137
+ }
138
+
139
+ private static func unavailable() -> AdoorError {
140
+ AdoorError(code: "DESKTOP_UNAVAILABLE", message: "The ADoor desktop service is unavailable.", status: 503)
141
+ }
142
+ }
@@ -0,0 +1,14 @@
1
+ import Foundation
2
+
3
+ @main
4
+ enum ADoorServiceEntry {
5
+ @MainActor static func main() async {
6
+ do {
7
+ try DesktopSession.shared.start()
8
+ let mounts = ServiceMounts()
9
+ mounts.start()
10
+ while !Task.isCancelled { try await Task.sleep(for: .seconds(3600)) }
11
+ withExtendedLifetime(mounts) {}
12
+ } catch { exit(1) }
13
+ }
14
+ }
@@ -0,0 +1,34 @@
1
+ import ADoor
2
+ import Darwin
3
+ import Foundation
4
+
5
+ @MainActor
6
+ final class ServiceMounts {
7
+ private var watcher: DispatchSourceFileSystemObject?
8
+ private let monitor = FinderChangeMonitor()
9
+ private var initial = true
10
+ private let registry = MountPaths.registry(home: FileManager.default.homeDirectoryForCurrentUser, platformDarwin: true)
11
+
12
+ func start() {
13
+ let directory = registry.deletingLastPathComponent()
14
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
15
+ let descriptor = open(directory.path, O_EVTONLY)
16
+ guard descriptor >= 0 else { return }
17
+ let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor, eventMask: .write, queue: .main)
18
+ source.setEventHandler { [weak self] in self?.refresh() }
19
+ source.setCancelHandler { close(descriptor) }
20
+ source.resume()
21
+ watcher = source
22
+ refresh()
23
+ }
24
+
25
+ private func refresh() {
26
+ guard let data = try? Data(contentsOf: registry), let mounts = try? MountRegistry.decode(data).mounts else { return }
27
+ monitor.update(mounts)
28
+ if initial {
29
+ initial = false
30
+ let ids = Set(mounts.filter { $0.state == "mounted" }.map(\.id))
31
+ Task { try? await FolderRefresh.signal(ids) }
32
+ }
33
+ }
34
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "adoor",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "ADoor command line: sign in, manage access, and sync shared files.",
5
- "license": "MIT",
5
+ "license": "(MIT AND AGPL-3.0-only)",
6
6
  "author": "Halmos Labs",
7
7
  "homepage": "https://adoor.run",
8
8
  "type": "module",
@@ -13,7 +13,16 @@
13
13
  "dist/adoor.mjs",
14
14
  "README.md",
15
15
  "LICENSE",
16
- "CHANGELOG.md"
16
+ "CHANGELOG.md",
17
+ "native/darwin",
18
+ "native/LICENSE",
19
+ "native/README.md",
20
+ "native/source/Package.swift",
21
+ "native/source/service",
22
+ "native/source/sdk/Package.swift",
23
+ "native/source/sdk/LICENSE",
24
+ "native/source/sdk/Sources",
25
+ "native/source/sdk/Tests"
17
26
  ],
18
27
  "engines": {
19
28
  "node": ">=22.11"