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,360 @@
1
+ import XCTest
2
+ import Foundation
3
+ import CryptoKit
4
+ #if canImport(FoundationNetworking)
5
+ import FoundationNetworking
6
+ #endif
7
+ @testable import ADoor
8
+
9
+ private actor Gate {
10
+ var opened = false
11
+ var waiters: [CheckedContinuation<Void, Never>] = []
12
+ func wait() async { if !opened { await withCheckedContinuation { waiters.append($0) } } }
13
+ func open() { opened = true; for waiter in waiters { waiter.resume() }; waiters = [] }
14
+ }
15
+ private actor Recorder {
16
+ var requests: [URLRequest] = []
17
+ var saves = 0
18
+ var returned = 0
19
+ func record(_ request: URLRequest) { requests.append(request) }
20
+ func saved() -> Int { saves += 1; return saves }
21
+ func didReturn() { returned += 1 }
22
+ }
23
+ private final class StubProtocol: URLProtocol, @unchecked Sendable {
24
+ typealias Handler = @Sendable (URLRequest) async throws -> (Int, Data)
25
+ private static let lock = NSLock()
26
+ private static var handlers: [String: Handler] = [:]
27
+ private var transportTask: Task<Void, Never>?
28
+ static func register(_ host: String, _ handler: @escaping Handler) { lock.lock(); defer { lock.unlock() }; handlers[host] = handler }
29
+ static func handler(_ host: String) -> Handler? { lock.lock(); defer { lock.unlock() }; return handlers[host] }
30
+ override class func canInit(with request: URLRequest) -> Bool { true }
31
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
32
+ override func startLoading() {
33
+ let handler = Self.handler(request.url!.host!)!
34
+ transportTask = Task {
35
+ do {
36
+ let (status, data) = try await handler(request)
37
+ guard !Task.isCancelled else { return }
38
+ client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed)
39
+ client?.urlProtocol(self, didLoad: data)
40
+ client?.urlProtocolDidFinishLoading(self)
41
+ } catch { if !Task.isCancelled { client?.urlProtocol(self, didFailWithError: error) } }
42
+ }
43
+ }
44
+ override func stopLoading() { transportTask?.cancel() }
45
+ }
46
+ private actor TestStorage: Storage {
47
+ var values: [String: String] = [:]
48
+ let gate: Gate?
49
+ var failReceiptOnce = false
50
+ let receiptGate: Gate?
51
+ var savingReceipt = false
52
+ init(gate: Gate? = nil, failReceiptOnce: Bool = false, receiptGate: Gate? = nil) { self.gate = gate; self.failReceiptOnce = failReceiptOnce; self.receiptGate = receiptGate }
53
+ func get(_ key: String) -> String? { values[key] }
54
+ func set(_ key: String, _ value: String) async throws {
55
+ if key.hasSuffix(":outbox") { await gate?.wait() }
56
+ if key.hasSuffix(":outbox"), value == "[]", let receiptGate { savingReceipt = true; await receiptGate.wait() }
57
+ if failReceiptOnce, key.hasSuffix(":outbox"), !value.contains("first-key"), value.contains("second-key") {
58
+ failReceiptOnce = false; throw URLError(.cannotWriteToFile)
59
+ }
60
+ values[key] = value
61
+ }
62
+ func delete(_ key: String) { values.removeValue(forKey: key) }
63
+ }
64
+
65
+ private final class AppSession: @unchecked Sendable {
66
+ private let lock = NSLock()
67
+ private var identity: LocalIdentity? = LocalIdentity(accountId: "A", workspaceId: "workspace", spaceId: "chosen")
68
+ func current() -> LocalIdentity? { lock.lock(); defer { lock.unlock() }; return identity }
69
+ func signOut() { lock.lock(); defer { lock.unlock() }; identity = nil }
70
+ func switchAccount() { lock.lock(); defer { lock.unlock() }; identity = LocalIdentity(accountId: "B", workspaceId: "workspace", spaceId: "chosen") }
71
+ }
72
+
73
+ final class RegressionTests: XCTestCase {
74
+ private func savedKey(_ url: URL, _ part: String) throws -> String {
75
+ let data = try JSON.encode(["adoor", url.absoluteString, "account", "workspace", "chosen"])
76
+ let scope = "adoor:v2:" + CryptoKit.SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
77
+ return scope + (part.hasPrefix("rows:") ? ":chosen:" : ":") + part
78
+ }
79
+ private let result = Data(#"{"rows":[],"columns":[],"rowCount":1,"command":"UPDATE","schemaVersion":1}"#.utf8)
80
+ private func fixture(_ handler: @escaping StubProtocol.Handler) -> (URL, URLSession) {
81
+ let host = UUID().uuidString.lowercased() + ".example"
82
+ StubProtocol.register(host, handler)
83
+ let configuration = URLSessionConfiguration.ephemeral
84
+ configuration.protocolClasses = [StubProtocol.self]
85
+ return (URL(string: "https://\(host)")!, URLSession(configuration: configuration))
86
+ }
87
+ private func tokens() throws -> Tokens {
88
+ try JSON.decode(Tokens.self, from: Data(#"{"access_token":"new-access","refresh_token":"new-refresh","token_type":"Bearer","expires_in":3600,"installation_id":"installation","connection_id":"connection","workspace_id":"workspace","space_ids":["other","chosen"],"selected_space_id":"chosen"}"#.utf8))
89
+ }
90
+ private func eventually(_ condition: @escaping () async -> Bool, file: StaticString = #filePath, line: UInt = #line) async throws {
91
+ for _ in 0..<200 { if await condition() { return }; try await Task.sleep(nanoseconds: 5_000_000) }
92
+ XCTFail("Condition did not become true", file: file, line: line)
93
+ }
94
+
95
+ func testChooserAndSelectedSpaceAreCarriedAcrossOAuth() throws {
96
+ let details = SpaceAuthorizationDetails(suggestedName: "My app", permissions: [["table": "*", "actions": ["select", "insert", "update", "create"]]])
97
+ let url = try OAuth.authorizationURL(url: URL(string: "https://adoor.example")!, clientId: "client", redirectUri: "http://127.0.0.1:49101/callback", pkce: OAuth.createPKCE(), authorizationDetails: details)
98
+ let raw = URLComponents(url: url, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "authorization_details" }!.value!
99
+ let value = try JSON.decode(JSONValue.self, from: Data(raw.utf8))
100
+ XCTAssertEqual(value.arrayValue?.first?["space_selection"]?["allow"], ["create", "existing"])
101
+ XCTAssertEqual(try tokens().selectedSpaceId, "chosen")
102
+ }
103
+
104
+ func testConcurrentTokenCallersWaitForPersistence() async throws {
105
+ let recorder = Recorder(), gate = Gate(), data = try JSON.encode(tokens())
106
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
107
+ defer { session.invalidateAndCancel() }
108
+ let provider = TokenProvider(url: url, clientId: "client", tokens: try tokens(), session: session, onTokens: { _ in _ = await recorder.saved(); await gate.wait() })
109
+ let first = Task { let token = try await provider.token(); await recorder.didReturn(); return token }
110
+ try await eventually { await recorder.saves == 1 }
111
+ let second = Task { let token = try await provider.token(); await recorder.didReturn(); return token }
112
+ try await Task.sleep(nanoseconds: 30_000_000)
113
+ let returned = await recorder.returned
114
+ XCTAssertEqual(returned, 0, "No caller may use rotated credentials before persistence.")
115
+ await gate.open()
116
+ let a = try await first.value, b = try await second.value, calls = await recorder.requests.count
117
+ XCTAssertEqual(a, "new-access"); XCTAssertEqual(b, a); XCTAssertEqual(calls, 1)
118
+ }
119
+
120
+ func testLostRefreshResponseIsNeverRetried() async throws {
121
+ let recorder = Recorder()
122
+ let (url, session) = fixture { request in await recorder.record(request); throw URLError(.networkConnectionLost) }
123
+ defer { session.invalidateAndCancel() }
124
+ let provider = TokenProvider(url: url, clientId: "client", tokens: try tokens(), session: session)
125
+ for _ in 0..<2 { do { _ = try await provider.token(); XCTFail("Expected reconnect") } catch let error as AdoorError { XCTAssertEqual(error.code, "REFRESH_UNCERTAIN") } }
126
+ let count = await recorder.requests.count
127
+ XCTAssertEqual(count, 1)
128
+ }
129
+
130
+ func testFailedPersistenceRetriesSamePairWithoutAnotherRotation() async throws {
131
+ let recorder = Recorder(), data = try JSON.encode(tokens())
132
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
133
+ defer { session.invalidateAndCancel() }
134
+ let provider = TokenProvider(url: url, clientId: "client", tokens: try tokens(), session: session, onTokens: { _ in if await recorder.saved() == 1 { throw URLError(.cannotWriteToFile) } })
135
+ do { _ = try await provider.token(); XCTFail("Expected save failure") } catch {}
136
+ let token = try await provider.token(), calls = await recorder.requests.count, saves = await recorder.saves
137
+ XCTAssertEqual(token, "new-access"); XCTAssertEqual(calls, 1); XCTAssertEqual(saves, 2)
138
+ }
139
+
140
+ func testWriteWaitsForDurableOutbox() async throws {
141
+ let gate = Gate(), recorder = Recorder(), data = result
142
+ let storage = TestStorage(gate: gate)
143
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
144
+ defer { session.invalidateAndCancel() }
145
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: [:], storage: storage))
146
+ let mutation = Task { try await store.mutate(Mutation(sql: "UPDATE notes SET title=$1", params: ["original"], idempotencyKey: "stable-key", expectRowCount: 1)) }
147
+ try await eventually { await store.pendingCount == 1 }
148
+ try await Task.sleep(nanoseconds: 20_000_000)
149
+ let before = await recorder.requests.count; XCTAssertEqual(before, 0)
150
+ await gate.open(); _ = try await mutation.value
151
+ let after = await recorder.requests.count; XCTAssertEqual(after, 1)
152
+ try await store.clear()
153
+ }
154
+
155
+ func testClearDuringRefetchCannotResurrectRows() async throws {
156
+ let gate = Gate(), recorder = Recorder(), storage = MemoryStorage()
157
+ let data = Data(#"{"rows":[{"id":"private"}],"columns":[],"rowCount":1,"command":"SELECT","schemaVersion":1}"#.utf8)
158
+ let (url, session) = fixture { request in await recorder.record(request); await gate.wait(); return (200, data) }
159
+ defer { session.invalidateAndCancel() }
160
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: ["notes": CollectionSpec(sql: "SELECT id FROM notes")], storage: storage))
161
+ let refetch = Task { try await store.refresh("notes") }
162
+ try await eventually { await recorder.requests.count == 1 }
163
+ try await store.clear(); await gate.open(); try await refetch.value
164
+ let rows = await store.rows(of: "notes"), cache = await storage.get(try savedKey(url, "rows:notes"))
165
+ XCTAssertTrue(rows.isEmpty); XCTAssertNil(cache)
166
+ do { _ = try await store.mutate(Mutation(sql: "UPDATE notes SET title=1")); XCTFail("Cleared store must be closed") } catch let error as AdoorError { XCTAssertEqual(error.code, "STORE_CLOSED") }
167
+ }
168
+
169
+ func testClearDuringWriteDoesNotCrashOrResumeTwice() async throws {
170
+ let gate = Gate(), recorder = Recorder(), data = result
171
+ let (url, session) = fixture { request in await recorder.record(request); await gate.wait(); return (200, data) }
172
+ defer { session.invalidateAndCancel() }
173
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: [:]))
174
+ let mutation = Task { try await store.mutate(Mutation(sql: "UPDATE notes SET title=1")) }
175
+ try await eventually { await recorder.requests.count == 1 }
176
+ try await store.clear(); await gate.open()
177
+ do { _ = try await mutation.value; XCTFail("Expected closed store") } catch let error as AdoorError { XCTAssertEqual(error.code, "STORE_CLOSED") }
178
+ let pending = await store.pendingCount; XCTAssertEqual(pending, 0)
179
+ }
180
+
181
+ func testRestartLoadsOutboxBeforeAcceptingNewWritesAndKeepsGuard() async throws {
182
+ let recorder = Recorder(), data = result, storage = MemoryStorage()
183
+ let queued = PersistedMutation(id: "old", sql: "UPDATE notes SET title='old'", params: [], spaceId: nil, idempotencyKey: "old-key", expectRowCount: 1)
184
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
185
+ defer { session.invalidateAndCancel() }
186
+ await storage.set(try savedKey(url, "outbox"), String(decoding: try JSON.encode([queued]), as: UTF8.self))
187
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: [:], storage: storage))
188
+ _ = try await store.mutate(Mutation(sql: "UPDATE notes SET title='new'", idempotencyKey: "new-key"))
189
+ let requests = await recorder.requests
190
+ XCTAssertEqual(requests.count, 2)
191
+ let first = try JSON.decode(JSONValue.self, from: requestBody(requests[0]))
192
+ XCTAssertEqual(first["idempotencyKey"], "old-key"); XCTAssertEqual(first["expectRowCount"], 1)
193
+ try await store.clear()
194
+ }
195
+
196
+ func testCorruptOutboxIsPreservedWithoutSending() async throws {
197
+ let recorder = Recorder(), storage = MemoryStorage(), data = result
198
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
199
+ defer { session.invalidateAndCancel() }
200
+ await storage.set(try savedKey(url, "outbox"), "{invalid")
201
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: [:], storage: storage))
202
+ do { _ = try await store.mutate(Mutation(sql: "UPDATE notes SET title=1")); XCTFail("Expected corrupt outbox") } catch let error as AdoorError { XCTAssertEqual(error.code, "OUTBOX_CORRUPT") }
203
+ let count = await recorder.requests.count, outbox = await storage.get(try savedKey(url, "outbox"))
204
+ XCTAssertEqual(count, 0); XCTAssertEqual(outbox, "{invalid")
205
+ }
206
+
207
+ func testInitialRevocationBlocksReplayAndClearsCachedRows() async throws {
208
+ let recorder = Recorder(), storage = MemoryStorage()
209
+ let queued = PersistedMutation(id: "old", sql: "UPDATE notes SET title='old'", params: [], spaceId: nil, idempotencyKey: "old-key", expectRowCount: 1)
210
+ let outbox = String(decoding: try JSON.encode([queued]), as: UTF8.self)
211
+ let (url, session) = fixture { request in
212
+ await recorder.record(request)
213
+ if request.url!.path.hasSuffix("changes.head") { return (200, Data(#"{"cursor":"0"}"#.utf8)) }
214
+ return (403, Data(#"{"error":{"code":"FORBIDDEN","message":"Access removed"}}"#.utf8))
215
+ }
216
+ defer { session.invalidateAndCancel() }
217
+ await storage.set(try savedKey(url, "outbox"), outbox); await storage.set(try savedKey(url, "rows:notes"), #"[{"id":"private"}]"#)
218
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "fixture", session: session, identity: { LocalIdentity(accountId: "account", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: ["notes": CollectionSpec(sql: "SELECT id FROM notes")], storage: storage))
219
+ do { try await store.start(); XCTFail("Expected authority failure") } catch let error as AdoorError { XCTAssertEqual(error.code, "FORBIDDEN") }
220
+ let status = await store.status, rows = await store.rows(of: "notes"), requests = await recorder.requests, cache = await storage.get(try savedKey(url, "rows:notes")), retained = await storage.get(try savedKey(url, "outbox"))
221
+ XCTAssertEqual(status, .blocked); XCTAssertTrue(rows.isEmpty); XCTAssertNil(cache); XCTAssertEqual(retained, outbox)
222
+ XCTAssertFalse(requests.contains { $0.url!.path.hasSuffix("data.execute") })
223
+ }
224
+
225
+ func testSuppliedStorageRequiresIdentityAndPreservesLegacyDrafts() async throws {
226
+ let recorder = Recorder(), storage = MemoryStorage(), data = result
227
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
228
+ defer { session.invalidateAndCancel() }
229
+ let unbound = LocalStore(client: AdoorClient(url: url, accessKey: "B", session: session), options: LocalStoreOptions(collections: [:], storage: storage))
230
+ do { _ = try await unbound.mutate(Mutation(sql: "UPDATE notes SET title=1")); XCTFail("Expected identity requirement") }
231
+ catch let error as AdoorError { XCTAssertEqual(error.code, "IDENTITY_REQUIRED") }
232
+ let legacy = #"[{"id":"A-draft","sql":"UPDATE notes SET title=1","idempotencyKey":"A-key"}]"#
233
+ await storage.set("adoor:outbox", legacy)
234
+ await storage.set("adoor:rows:notes", #"[{"id":"A-private"}]"#)
235
+ let bound = LocalStore(client: AdoorClient(url: url, accessKey: "B", session: session, identity: { LocalIdentity(accountId: "B", workspaceId: "workspace", spaceId: "chosen") }), options: LocalStoreOptions(collections: ["notes": CollectionSpec(sql: "SELECT id FROM notes")], storage: storage))
236
+ do { try await bound.start(); XCTFail("Expected explicit legacy recovery") }
237
+ catch let error as AdoorError { XCTAssertEqual(error.code, "LEGACY_LOCAL_STATE") }
238
+ try await bound.clear()
239
+ let requests = await recorder.requests, outbox = await storage.get("adoor:outbox"), rows = await bound.rows(of: "notes"), cache = await storage.get("adoor:rows:notes")
240
+ XCTAssertTrue(requests.isEmpty); XCTAssertEqual(outbox, legacy); XCTAssertTrue(rows.isEmpty); XCTAssertNotNil(cache)
241
+ }
242
+
243
+ func testStorageIsolatesAccountWorkspaceServerAndSpaceAndResumesSameIdentity() async throws {
244
+ let recorder = Recorder(), firstStorage = TestStorage(), data = result
245
+ let snapshot = Data(#"{"rows":[{"id":"A-private"}],"columns":[],"rowCount":1,"command":"SELECT","schemaVersion":1}"#.utf8)
246
+ let (url, session) = fixture { request in
247
+ await recorder.record(request)
248
+ if request.url!.path.hasSuffix("data.execute") { throw URLError(.notConnectedToInternet) }
249
+ return (200, snapshot)
250
+ }
251
+ defer { session.invalidateAndCancel() }
252
+ let scope = LocalIdentity(accountId: "A", workspaceId: "workspace", spaceId: "chosen")
253
+ let collections = ["notes": CollectionSpec(sql: "SELECT id FROM notes")]
254
+ let first = LocalStore(client: AdoorClient(url: url, accessKey: "A-old", session: session, identity: { scope }), options: LocalStoreOptions(collections: collections, storage: firstStorage))
255
+ try await first.refresh("notes")
256
+ let queued = Task { try? await first.mutate(Mutation(sql: "UPDATE notes SET title=$1", params: ["A-draft"], idempotencyKey: "A-key", expectRowCount: 1)) }
257
+ try await eventually { await recorder.requests.contains { $0.url!.path.hasSuffix("data.execute") } }
258
+ // Simulate a process restart using only state written by the SDK.
259
+ let storage = MemoryStorage()
260
+ for (key, value) in await firstStorage.values { await storage.set(key, value) }
261
+ try await first.clear(); _ = await queued.value
262
+ StubProtocol.register(url.host!) { _ in throw URLError(.notConnectedToInternet) }
263
+
264
+ let targets = [
265
+ (url, LocalIdentity(accountId: "B", workspaceId: "workspace", spaceId: "chosen")),
266
+ (url, LocalIdentity(accountId: "A", workspaceId: "other-workspace", spaceId: "chosen")),
267
+ (url, LocalIdentity(accountId: "A", workspaceId: "workspace", spaceId: "other-space")),
268
+ (url.appendingPathComponent("other-server"), scope)
269
+ ]
270
+ for (endpoint, identity) in targets {
271
+ let store = LocalStore(client: AdoorClient(url: endpoint, accessKey: "other", session: session, identity: { identity }), options: LocalStoreOptions(collections: collections, storage: storage))
272
+ let running = Task { try await store.start() }
273
+ try await eventually { await store.status == .offline }
274
+ let rows = await store.rows(of: "notes"), pending = await store.pendingCount
275
+ XCTAssertTrue(rows.isEmpty); XCTAssertEqual(pending, 0)
276
+ running.cancel(); _ = try? await running.value
277
+ try await store.clear()
278
+ }
279
+ let offline = LocalStore(client: AdoorClient(url: url, accessKey: "A-refreshed", session: session, identity: { scope }), options: LocalStoreOptions(collections: collections, storage: storage))
280
+ let running = Task { try await offline.start() }
281
+ try await eventually { await offline.status == .offline }
282
+ let restoredRows = await offline.rows(of: "notes"), restoredPending = await offline.pendingCount
283
+ XCTAssertEqual(restoredRows, [["id": "A-private"]]); XCTAssertEqual(restoredPending, 1)
284
+ running.cancel(); _ = try? await running.value
285
+
286
+ let replayRecorder = Recorder()
287
+ StubProtocol.register(url.host!) { request in await replayRecorder.record(request); return (200, data) }
288
+ let reload = LocalStore(client: AdoorClient(url: url, accessKey: "A-refreshed", session: session, identity: { scope }), options: LocalStoreOptions(collections: [:], storage: storage))
289
+ _ = try await reload.mutate(Mutation(sql: "UPDATE notes SET title='next'", idempotencyKey: "next-key"))
290
+ let requests = await replayRecorder.requests
291
+ XCTAssertEqual(requests.count, 2)
292
+ let replay = try JSON.decode(JSONValue.self, from: requestBody(requests[0]))
293
+ XCTAssertEqual(replay["idempotencyKey"], "A-key"); XCTAssertEqual(replay["spaceId"], "chosen"); XCTAssertEqual(replay["expectRowCount"], 1)
294
+ XCTAssertEqual(requests[0].value(forHTTPHeaderField: "Authorization"), "Bearer A-refreshed")
295
+ try await reload.clear()
296
+ }
297
+
298
+ func testChangingIdentityWhileResolvingTokenNeverSendsWithNewCredential() async throws {
299
+ let state = AppSession(), gate = Gate(), entered = Gate(), recorder = Recorder(), data = result
300
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
301
+ defer { session.invalidateAndCancel() }
302
+ let client = AdoorClient(url: url, token: .provider { await entered.open(); await gate.wait(); return "B" }, session: session, identity: { state.current() })
303
+ let request = Task { try await client.execute("UPDATE notes SET title=1") }
304
+ await entered.wait(); state.switchAccount(); await gate.open()
305
+ do { _ = try await request.value; XCTFail("Expected changed identity") }
306
+ catch let error as AdoorError { XCTAssertEqual(error.code, "IDENTITY_CHANGED") }
307
+ let requests = await recorder.requests
308
+ XCTAssertTrue(requests.isEmpty)
309
+ }
310
+
311
+ func testSignOutPreventsLateRowsAndNewWritesFromOldStore() async throws {
312
+ let state = AppSession(), gate = Gate(), entered = Gate(), storage = MemoryStorage()
313
+ let snapshot = Data(#"{"rows":[{"id":"A-private"}],"columns":[],"rowCount":1,"command":"SELECT","schemaVersion":1}"#.utf8)
314
+ let (url, session) = fixture { _ in await entered.open(); await gate.wait(); return (200, snapshot) }
315
+ defer { session.invalidateAndCancel() }
316
+ let client = AdoorClient(url: url, accessKey: "A", session: session, identity: { state.current() })
317
+ let store = LocalStore(client: client, options: LocalStoreOptions(collections: ["notes": CollectionSpec(sql: "SELECT id FROM notes")], storage: storage))
318
+ let read = Task { try await store.refresh("notes") }
319
+ await entered.wait(); state.signOut(); await gate.open()
320
+ do { try await read.value; XCTFail("Expected changed identity") }
321
+ catch let error as AdoorError { XCTAssertEqual(error.code, "IDENTITY_CHANGED") }
322
+ let rows = await store.rows(of: "notes"), status = await store.status
323
+ XCTAssertTrue(rows.isEmpty); XCTAssertEqual(status, .blocked)
324
+ do { _ = try await store.mutate(Mutation(sql: "UPDATE notes SET title=1")); XCTFail("Expected closed store") }
325
+ catch let error as AdoorError { XCTAssertEqual(error.code, "STORE_CLOSED") }
326
+ try await store.clear()
327
+ }
328
+
329
+ func testIdentitySwitchWhileSavingReceiptRejectsOldResponse() async throws {
330
+ let state = AppSession(), gate = Gate(), recorder = Recorder(), data = result
331
+ let storage = TestStorage(receiptGate: gate)
332
+ let (url, session) = fixture { request in await recorder.record(request); return (200, data) }
333
+ defer { session.invalidateAndCancel() }
334
+ let store = LocalStore(client: AdoorClient(url: url, accessKey: "A", session: session, identity: { state.current() }), options: LocalStoreOptions(collections: [:], storage: storage))
335
+ let write = Task { try await store.mutate(Mutation(sql: "UPDATE notes SET title=1")) }
336
+ try await eventually { await storage.savingReceipt }
337
+ state.switchAccount(); await gate.open()
338
+ do { _ = try await write.value; XCTFail("Expected changed identity") }
339
+ catch let error as AdoorError { XCTAssertEqual(error.code, "IDENTITY_CHANGED") }
340
+ let requests = await recorder.requests, status = await store.status
341
+ XCTAssertEqual(requests.count, 1); XCTAssertEqual(status, .blocked)
342
+ try await store.clear()
343
+ }
344
+
345
+ func testErrorFlagsAndLargeNumberDoNotTrap() {
346
+ XCTAssertTrue(AdoorError(code: "RATE_LIMITED", message: "", status: 429).retryable)
347
+ XCTAssertTrue(AdoorError(code: "HTTP_403", message: "", status: 403).authority)
348
+ XCTAssertNil(JSONValue.number(1e30).intValue)
349
+ XCTAssertNil(JSONValue.number(.infinity).intValue)
350
+ }
351
+
352
+ private func requestBody(_ request: URLRequest) -> Data {
353
+ if let data = request.httpBody { return data }
354
+ guard let stream = request.httpBodyStream else { return Data() }
355
+ stream.open(); defer { stream.close() }
356
+ var data = Data(), bytes = [UInt8](repeating: 0, count: 4096)
357
+ while stream.hasBytesAvailable { let n = stream.read(&bytes, maxLength: bytes.count); if n <= 0 { break }; data.append(contentsOf: bytes.prefix(n)) }
358
+ return data
359
+ }
360
+ }
@@ -0,0 +1,241 @@
1
+ import ADoor
2
+ import Foundation
3
+
4
+ @MainActor
5
+ final class DesktopSession {
6
+ static let shared = DesktopSession()
7
+ static let changed = Notification.Name("ADoorDesktopSessionChanged")
8
+ private(set) var state: DesktopSessionState?
9
+ private var socket: LocalSessionSocket?
10
+ private var jobs: [String: Task<Void, Never>] = [:]
11
+ private let load: () throws -> Data?
12
+ private let save: (Data) throws -> Void
13
+ private let legacy: () -> (token: String, server: String)?
14
+ private let deviceStart: (URL, String, Bool) async throws -> DeviceStart
15
+ private let devicePoll: (URL, String) async throws -> DeviceReply
16
+ private let verify: (URL, String) async throws -> Void
17
+ private let activate: (JSONValue?) throws -> Void
18
+
19
+ init(load: @escaping () throws -> Data? = KeychainStore.sessionData,
20
+ save: @escaping (Data) throws -> Void = KeychainStore.saveSession,
21
+ legacy: @escaping () -> (token: String, server: String)? = { KeychainStore.load() },
22
+ deviceStart: @escaping (URL, String, Bool) async throws -> DeviceStart = DeviceClient.start,
23
+ devicePoll: @escaping (URL, String) async throws -> DeviceReply = DeviceClient.poll,
24
+ verify: @escaping (URL, String) async throws -> Void = { url, token in
25
+ _ = try await AdoorClient(url: url, accessKey: token).call("identity.get")
26
+ }, activate: @escaping (JSONValue?) throws -> Void = { active in
27
+ if let token = active?["token"]?.stringValue, let server = active?["url"]?.stringValue {
28
+ try KeychainStore.save(token: token, server: server)
29
+ } else { KeychainStore.clearActive() }
30
+ }) {
31
+ self.load = load
32
+ self.save = save
33
+ self.legacy = legacy
34
+ self.deviceStart = deviceStart
35
+ self.devicePoll = devicePoll
36
+ self.verify = verify
37
+ self.activate = activate
38
+ }
39
+
40
+ func start() throws {
41
+ guard socket == nil else { return }
42
+ socket = try LocalSessionSocket { [weak self] input in
43
+ guard let self else { return ["error": ["code": "DESKTOP_UNAVAILABLE"]] }
44
+ return await self.handle(input)
45
+ }
46
+ do { try restore() } catch { socket = nil; throw error }
47
+ for name in state?.config["pendingLogins"]?.objectValue?.keys ?? Dictionary<String, JSONValue>().keys { resume(name) }
48
+
49
+ }
50
+
51
+ func restore() throws {
52
+ guard state == nil else { return }
53
+ if let data = try load() {
54
+ let restored = try JSONDecoder().decode(DesktopSessionState.self, from: data)
55
+ try DesktopSessionState.validate(restored.config)
56
+ state = restored
57
+ } else {
58
+ var initial = try DesktopSessionState()
59
+ if let old = legacy() {
60
+ try initial.importOnce(["version": 1, "activeProfile": "desktop", "profiles": [
61
+ "desktop": ["url": .string(old.server), "token": .string(old.token)]
62
+ ]], source: "native-keychain")
63
+ }
64
+ try persist(initial)
65
+ }
66
+ }
67
+
68
+ private func persist(_ next: DesktopSessionState) throws {
69
+ try save(JSONEncoder().encode(next))
70
+ state = next
71
+ NotificationCenter.default.post(name: Self.changed, object: self)
72
+ if NSClassFromString("XCTestCase") == nil {
73
+ DistributedNotificationCenter.default().postNotificationName(Self.changed, object: nil, userInfo: nil, deliverImmediately: true)
74
+ }
75
+ }
76
+
77
+ func handle(_ input: JSONValue) async -> JSONValue {
78
+ do {
79
+ try restore()
80
+ switch input["method"]?.stringValue {
81
+ case "config.open":
82
+ if let source = input["source"]?.stringValue, let config = input["config"] {
83
+ var next = state!
84
+ try next.importOnce(config, source: source)
85
+ try persist(next)
86
+ }
87
+ return state!.snapshot
88
+ case "config.read": return state!.snapshot
89
+ case "service.info":
90
+ return ["protocol": 1, "pid": .number(Double(ProcessInfo.processInfo.processIdentifier)), "version": "0.1.1"]
91
+ case "config.write":
92
+ guard let config = input["config"], let revision = input["revision"]?.stringValue else { throw invalid() }
93
+ var next = state!
94
+ guard try next.replace(config, expected: revision) else { return ["conflict": true] }
95
+ let previous = state!.config
96
+ try persist(next)
97
+ for (name, job) in jobs where
98
+ (previous["profiles"]?[name] != nil && config["profiles"]?[name] == nil) ||
99
+ (previous["pendingLogins"]?[name] != nil && config["pendingLogins"]?[name] == nil) {
100
+ job.cancel()
101
+ }
102
+ try activate(state?.active)
103
+ return next.snapshot
104
+ case "login.start": return try await begin(input)
105
+ case "login.status": return try status(input)
106
+ case "login.cancel":
107
+ guard let name = input["profile"]?.stringValue else { throw invalid() }
108
+ jobs[name]?.cancel()
109
+ try finish(name, server: state?.config["pendingLogins"]?[name]?["url"]?.stringValue ?? "", status: "cancelled")
110
+ return ["status": "cancelled"]
111
+ default: throw invalid()
112
+ }
113
+ } catch let error as AdoorError {
114
+ return ["error": ["code": .string(error.code)]]
115
+ } catch { return ["error": ["code": "DESKTOP_UNAVAILABLE"]] }
116
+ }
117
+
118
+ private func begin(_ input: JSONValue) async throws -> JSONValue {
119
+ guard let name = input["profile"]?.stringValue, DesktopSessionState.validName(name),
120
+ let server = input["url"]?.stringValue, let url = URL(string: server) else { throw invalid() }
121
+ try ServerOrigin.validate(url)
122
+ if let pending = state?.config["pendingLogins"]?[name],
123
+ let expiry = pending["expiresAt"]?.stringValue, let date = FileJSON.date(expiry), date > Date() {
124
+ guard pending["url"]?.stringValue == server else { throw invalid() }
125
+ resume(name)
126
+ return publicPending(pending, name: name)
127
+ }
128
+ guard jobs[name] == nil else { throw invalid() }
129
+ let id = UUID().uuidString
130
+ jobs[name] = Task {}
131
+ do {
132
+ let started = try await deviceStart(url, input["name"]?.stringValue ?? "ADoor on this Mac", input["operator"]?.boolValue ?? false)
133
+ guard jobs[name]?.isCancelled != true else { throw invalid() }
134
+ var config = state!.config.objectValue!
135
+ var pending = config["pendingLogins"]?.objectValue ?? [:]
136
+ pending[name] = ["id": .string(id), "url": .string(server), "deviceCode": .string(started.deviceCode),
137
+ "userCode": .string(started.userCode), "approvalUrl": .string(started.approvalURL.absoluteString),
138
+ "expiresAt": .string(started.expiresAt.ISO8601Format()), "interval": .number(started.interval)]
139
+ config["pendingLogins"] = .object(pending)
140
+ try replace(config)
141
+ jobs[name] = nil
142
+ resume(name)
143
+ return publicPending(pending[name]!, name: name)
144
+ } catch { jobs[name] = nil; throw error }
145
+ }
146
+
147
+ private func status(_ input: JSONValue) throws -> JSONValue {
148
+ guard let name = input["profile"]?.stringValue else { throw invalid() }
149
+ if let pending = state?.config["pendingLogins"]?[name] {
150
+ if let url = input["url"]?.stringValue, pending["url"]?.stringValue != url { throw invalid() }
151
+ resume(name)
152
+ return publicPending(pending, name: name)
153
+ }
154
+ if let result = state?.config["desktopLoginResults"]?[name] { return result }
155
+ throw AdoorError(code: "LOGIN_NOT_PENDING", message: "Start a sign-in first.", status: 400)
156
+ }
157
+
158
+ private func publicPending(_ pending: JSONValue, name: String) -> JSONValue {
159
+ ["status": "pending", "profile": .string(name), "url": pending["url"] ?? .null,
160
+ "userCode": pending["userCode"] ?? .null, "approvalUrl": pending["approvalUrl"] ?? .null,
161
+ "expiresAt": pending["expiresAt"] ?? .null, "interval": pending["interval"] ?? 2]
162
+ }
163
+
164
+ private func replace(_ config: [String: JSONValue]) throws {
165
+ var next = state!
166
+ _ = try next.replace(.object(config), expected: next.revision)
167
+ try persist(next)
168
+ }
169
+
170
+ private func resume(_ name: String) {
171
+ guard jobs[name] == nil, var pending = state?.config["pendingLogins"]?[name],
172
+ let server = pending["url"]?.stringValue, let url = URL(string: server),
173
+ let code = pending["deviceCode"]?.stringValue, let expiry = FileJSON.date(pending["expiresAt"]?.stringValue) else { return }
174
+ jobs[name] = Task {
175
+ defer { jobs[name] = nil }
176
+ var issued = pending["token"]?.stringValue
177
+ var home = pending["home"]
178
+ while !Task.isCancelled, Date() < expiry || issued != nil {
179
+ do {
180
+ try await Task.sleep(for: .seconds(min(10, max(1, pending["interval"]?.intValue ?? 2))))
181
+ guard state?.config["pendingLogins"]?[name] == pending else { return }
182
+ if issued == nil {
183
+ let polled = try await devicePoll(url, code)
184
+ guard state?.config["pendingLogins"]?[name] == pending else { return }
185
+ if polled.state == .pending { continue }
186
+ guard case .approved(let token) = polled.state else {
187
+ try finish(name, server: server, status: "expired")
188
+ return
189
+ }
190
+ issued = token
191
+ home = polled.home
192
+ }
193
+ guard let token = issued else { return }
194
+ var saved = pending.objectValue!
195
+ saved["token"] = .string(token)
196
+ saved["home"] = home
197
+ var config = state!.config.objectValue!
198
+ var requests = config["pendingLogins"]!.objectValue!
199
+ requests[name] = .object(saved)
200
+ config["pendingLogins"] = .object(requests)
201
+ try replace(config)
202
+ pending = .object(saved)
203
+ try await verify(url, token)
204
+ guard state?.config["pendingLogins"]?[name] == pending else { return }
205
+ try finish(name, server: server, token: token, home: home, status: "connected")
206
+ try activate(state?.active)
207
+ return
208
+ } catch let error as AdoorError where error.status == 401 || error.status == 403 {
209
+ if state?.config["pendingLogins"]?[name] == pending { try? finish(name, server: server, status: "failed") }
210
+ return
211
+ } catch {
212
+ if state?.config["pendingLogins"]?[name] != pending { return }
213
+ }
214
+ }
215
+ if state?.config["pendingLogins"]?[name] == pending { try? finish(name, server: server, status: "expired") }
216
+ }
217
+ }
218
+
219
+ private func finish(_ name: String, server: String, token: String? = nil, home: JSONValue? = nil, status: String) throws {
220
+ var config = state!.config.objectValue!
221
+ if let token {
222
+ var profiles = config["profiles"]!.objectValue!
223
+ var profile: [String: JSONValue] = ["url": .string(server), "token": .string(token)]
224
+ profile["home"] = home
225
+ profiles[name] = .object(profile)
226
+ config["profiles"] = .object(profiles)
227
+ config["activeProfile"] = .string(name)
228
+ }
229
+ var pending = config["pendingLogins"]?.objectValue ?? [:]
230
+ pending.removeValue(forKey: name)
231
+ config["pendingLogins"] = .object(pending)
232
+ var results = config["desktopLoginResults"]?.objectValue ?? [:]
233
+ results[name] = ["status": .string(status), "profile": .string(name), "url": .string(server)]
234
+ config["desktopLoginResults"] = .object(results)
235
+ try replace(config)
236
+ }
237
+
238
+ private func invalid() -> AdoorError {
239
+ AdoorError(code: "INVALID_ARGUMENT", message: "The desktop request is invalid.", status: 400)
240
+ }
241
+ }