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,283 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// How long a deleted file stays recoverable. Thirty days is the table and file history age.
|
|
4
|
+
public enum DeletedAccess: Equatable, Sendable {
|
|
5
|
+
case unknown
|
|
6
|
+
case allowed
|
|
7
|
+
case denied
|
|
8
|
+
case unavailable
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
public struct DeletedRow: Equatable, Sendable, Identifiable {
|
|
12
|
+
public let id: String
|
|
13
|
+
public var name: String
|
|
14
|
+
public var who: String
|
|
15
|
+
public var deletedAt: Date
|
|
16
|
+
public var purgeAfter: Date
|
|
17
|
+
public var kind: NodeKind
|
|
18
|
+
|
|
19
|
+
public init(id: String, name: String, who: String, deletedAt: Date, purgeAfter: Date, kind: NodeKind) {
|
|
20
|
+
self.id = id
|
|
21
|
+
self.name = name
|
|
22
|
+
self.who = who
|
|
23
|
+
self.deletedAt = deletedAt
|
|
24
|
+
self.purgeAfter = purgeAfter
|
|
25
|
+
self.kind = kind
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
public struct DeletedFolder: Equatable, Sendable {
|
|
30
|
+
public static let defaultRetentionDays = 30
|
|
31
|
+
|
|
32
|
+
public var files: [DeletedRow]
|
|
33
|
+
public var retentionDays: Int
|
|
34
|
+
public var nextCursor: String?
|
|
35
|
+
|
|
36
|
+
public init(files: [DeletedRow], retentionDays: Int, nextCursor: String? = nil) {
|
|
37
|
+
self.files = files
|
|
38
|
+
self.retentionDays = retentionDays
|
|
39
|
+
self.nextCursor = nextCursor
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public static func note(days: Int) -> String {
|
|
43
|
+
let count = max(1, days)
|
|
44
|
+
return count == 1 ? "Files can be recovered for 1 day." : "Files can be recovered for \(count) days."
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// Recovery operations for a single mounted folder.
|
|
49
|
+
public protocol FileTrash: Sendable {
|
|
50
|
+
func listDeleted(spaceId: String, folderId: String) async throws -> DeletedFolder
|
|
51
|
+
func restore(spaceId: String, inodeId: String) async throws
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
public struct UnavailableFileTrash: FileTrash {
|
|
55
|
+
public init() {}
|
|
56
|
+
|
|
57
|
+
public func listDeleted(spaceId: String, folderId: String) async throws -> DeletedFolder {
|
|
58
|
+
_ = spaceId
|
|
59
|
+
_ = folderId
|
|
60
|
+
throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "fs.list_deleted is not on this server.", status: 501)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public func restore(spaceId: String, inodeId: String) async throws {
|
|
64
|
+
_ = spaceId
|
|
65
|
+
_ = inodeId
|
|
66
|
+
throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "fs.restore is not on this server.", status: 501)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
public enum FileJSON {
|
|
71
|
+
public static func node(_ json: JSONValue, fallbackName: String = "") throws -> NodeAttr {
|
|
72
|
+
guard let id = json["id"]?.stringValue, let uuid = UUID(uuidString: id) else { throw TreeError.invalid }
|
|
73
|
+
let name = json["name"]?.stringValue ?? fallbackName
|
|
74
|
+
let kind = kindOf(json["kind"]?.stringValue)
|
|
75
|
+
let size = json["size"]?.intValue ?? 0
|
|
76
|
+
let generation = json["generation"]?.intValue ?? 1
|
|
77
|
+
let mode = json["mode"]?.intValue ?? (kind == .directory ? 0o755 : 0o644)
|
|
78
|
+
let mtime = date(json["mtime"]?.stringValue) ?? Date(timeIntervalSince1970: 0)
|
|
79
|
+
var node = NodeAttr(
|
|
80
|
+
id: uuid, name: name, kind: kind, size: size, generation: generation, mode: mode, mtime: mtime,
|
|
81
|
+
contentId: json["contentId"]?.stringValue)
|
|
82
|
+
node.parentID = json["parentId"]?.stringValue.flatMap(UUID.init(uuidString:))
|
|
83
|
+
return node
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
public static func page(_ json: JSONValue) throws -> RemotePage {
|
|
87
|
+
guard let id = json["id"]?.stringValue, let directory = UUID(uuidString: id) else { throw TreeError.invalid }
|
|
88
|
+
let entries = try (json["entries"]?.arrayValue ?? []).map { try node($0) }
|
|
89
|
+
return RemotePage(directoryId: directory, entries: entries, nextCursor: json["nextCursor"]?.stringValue)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
public static func inline(_ json: JSONValue) throws -> Data {
|
|
93
|
+
guard let body = json["body"]?.stringValue else { throw TreeError.invalid }
|
|
94
|
+
if json["encoding"]?.stringValue == "base64" {
|
|
95
|
+
guard let data = Data(base64Encoded: body) else { throw TreeError.invalid }
|
|
96
|
+
return data
|
|
97
|
+
}
|
|
98
|
+
return Data(body.utf8)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// The list shape `fs.list_deleted` is expected to return once that operation exists.
|
|
102
|
+
public static func deleted(_ json: JSONValue) throws -> DeletedFolder {
|
|
103
|
+
let days = json["retentionDays"]?.intValue ?? DeletedFolder.defaultRetentionDays
|
|
104
|
+
let rows = try (json["entries"]?.arrayValue ?? []).map { item -> DeletedRow in
|
|
105
|
+
guard let id = item["id"]?.stringValue, !id.isEmpty,
|
|
106
|
+
let name = item["name"]?.stringValue,
|
|
107
|
+
let who = item["deletedBy"]?.stringValue, !who.isEmpty,
|
|
108
|
+
let deletedAt = date(item["deletedAt"]?.stringValue),
|
|
109
|
+
let purgeAfter = date(item["purgeAfter"]?.stringValue) else { throw TreeError.invalid }
|
|
110
|
+
return DeletedRow(
|
|
111
|
+
id: id, name: name, who: who, deletedAt: deletedAt, purgeAfter: purgeAfter, kind: kindOf(item["kind"]?.stringValue))
|
|
112
|
+
}
|
|
113
|
+
return DeletedFolder(files: rows, retentionDays: days, nextCursor: json["nextCursor"]?.stringValue)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
public static func date(_ text: String?) -> Date? {
|
|
117
|
+
guard let text, !text.isEmpty else { return nil }
|
|
118
|
+
let fractional = ISO8601DateFormatter()
|
|
119
|
+
fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
120
|
+
if let date = fractional.date(from: text) { return date }
|
|
121
|
+
let plain = ISO8601DateFormatter()
|
|
122
|
+
plain.formatOptions = [.withInternetDateTime]
|
|
123
|
+
return plain.date(from: text)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private static func kindOf(_ raw: String?) -> NodeKind {
|
|
127
|
+
switch raw {
|
|
128
|
+
case "dir", "directory": return .directory
|
|
129
|
+
case "symlink": return .symlink
|
|
130
|
+
default: return .file
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
public final class AdoorFileRemote: FileRemote, @unchecked Sendable {
|
|
136
|
+
private let client: AdoorClient
|
|
137
|
+
|
|
138
|
+
public init(client: AdoorClient) { self.client = client }
|
|
139
|
+
|
|
140
|
+
public func changeHead() async throws -> String {
|
|
141
|
+
let (json, _) = try await client.call("changes.head")
|
|
142
|
+
guard let cursor = json["cursor"]?.stringValue else { throw TreeError.invalid }
|
|
143
|
+
return cursor
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public func changes(after cursor: String) async throws -> ChangePage {
|
|
147
|
+
try await client.changes(after: cursor, limit: 100)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public func stat(spaceId: String, path: String?, inodeId: String?) async throws -> NodeAttr {
|
|
151
|
+
try FileJSON.node(try await client.fsStat(spaceId: spaceId, path: path, inodeId: inodeId))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
public func list(spaceId: String, inodeId: String, cursor: String?) async throws -> RemotePage {
|
|
155
|
+
try await list(spaceId: spaceId, inodeId: inodeId, cursor: cursor, limit: nil)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
public func list(spaceId: String, inodeId: String, cursor: String?, limit: Int?) async throws -> RemotePage {
|
|
159
|
+
try FileJSON.page(try await client.fsList(spaceId: spaceId, inodeId: inodeId, limit: limit, cursor: cursor))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
public func readInline(spaceId: String, inodeId: String) async throws -> Data {
|
|
163
|
+
try FileJSON.inline(try await client.fsRead(spaceId: spaceId, inodeId: inodeId))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
public func contents(spaceId: String, node: NodeAttr) async throws -> Data {
|
|
167
|
+
if node.size <= MountLayout.inlineBytes {
|
|
168
|
+
let row = try await client.fsRead(spaceId: spaceId, inodeId: node.idString)
|
|
169
|
+
guard row["generation"]?.intValue == node.generation else { throw TreeError.conflict }
|
|
170
|
+
return try FileJSON.inline(row)
|
|
171
|
+
}
|
|
172
|
+
var bytes = Data()
|
|
173
|
+
while bytes.count < node.size {
|
|
174
|
+
let length = min(1_048_576, node.size - bytes.count)
|
|
175
|
+
let (row, _) = try await client.call("fs.range", input: .object([
|
|
176
|
+
"spaceId": .string(spaceId), "inodeId": .string(node.idString),
|
|
177
|
+
"offset": .number(Double(bytes.count)), "length": .number(Double(length))
|
|
178
|
+
]))
|
|
179
|
+
guard row["generation"]?.intValue == node.generation else { throw TreeError.conflict }
|
|
180
|
+
let part = try FileJSON.inline(row)
|
|
181
|
+
guard part.count == length else { throw TreeError.invalid }
|
|
182
|
+
bytes.append(part)
|
|
183
|
+
}
|
|
184
|
+
return bytes
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private func locator(spaceId: String, path: String?, name: String?, inodeId: String?, generation: Int?) -> [String: JSONValue] {
|
|
188
|
+
var fields = ["spaceId": JSONValue.string(spaceId)]
|
|
189
|
+
fields["path"] = path.map(JSONValue.string)
|
|
190
|
+
fields["name"] = name.map(JSONValue.string)
|
|
191
|
+
fields["inodeId"] = inodeId.map(JSONValue.string)
|
|
192
|
+
fields["expectedGeneration"] = generation.map { .number(Double($0)) }
|
|
193
|
+
return fields
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
public func writeInline(
|
|
197
|
+
spaceId: String, path: String?, name: String?, inodeId: String?, bytes: Data,
|
|
198
|
+
expectedGeneration: Int?, idempotencyKey: String
|
|
199
|
+
) async throws -> NodeAttr {
|
|
200
|
+
if let packed = FilePacker.pack(bytes) {
|
|
201
|
+
return try await commitSlices(spaceId: spaceId, inodeId: inodeId, path: path, name: name,
|
|
202
|
+
expectedGeneration: expectedGeneration, packed: packed)
|
|
203
|
+
}
|
|
204
|
+
guard let text = String(data: bytes, encoding: .utf8), Data(text.utf8) == bytes else {
|
|
205
|
+
var fields = locator(spaceId: spaceId, path: path, name: name, inodeId: inodeId, generation: expectedGeneration)
|
|
206
|
+
fields["body"] = .string(bytes.base64EncodedString())
|
|
207
|
+
let (json, _) = try await client.call("fs.inline", input: .object(fields))
|
|
208
|
+
return try FileJSON.node(json, fallbackName: name ?? "")
|
|
209
|
+
}
|
|
210
|
+
let json = try await client.fsWrite(
|
|
211
|
+
spaceId: spaceId, body: text, path: path, name: name, inodeId: inodeId,
|
|
212
|
+
expectedGeneration: expectedGeneration, idempotencyKey: idempotencyKey)
|
|
213
|
+
return try FileJSON.node(json, fallbackName: name ?? "")
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
public func mkdir(spaceId: String, parentId: String, name: String) async throws -> NodeAttr {
|
|
217
|
+
try FileJSON.node(try await client.fsMkdir(spaceId: spaceId, name: name, inodeId: parentId), fallbackName: name)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
public func rename(spaceId: String, inodeId: String, name: String, expectedGeneration: Int, parentId: String?) async throws -> NodeAttr {
|
|
221
|
+
let json = try await client.fsRename(
|
|
222
|
+
spaceId: spaceId, inodeId: inodeId, name: name, expectedGeneration: expectedGeneration, parentId: parentId)
|
|
223
|
+
return try FileJSON.node(json, fallbackName: name)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
public func remove(spaceId: String, inodeId: String, expectedGeneration: Int) async throws {
|
|
227
|
+
_ = try await client.fsRemove(spaceId: spaceId, inodeId: inodeId, expectedGeneration: expectedGeneration)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
public func commitSlices(
|
|
231
|
+
spaceId: String, inodeId: String?, path: String?, name: String?, expectedGeneration: Int?, packed: PackedFile
|
|
232
|
+
) async throws -> NodeAttr {
|
|
233
|
+
var fields = locator(spaceId: spaceId, path: path, name: name, inodeId: inodeId, generation: expectedGeneration)
|
|
234
|
+
var staged = Set<String>()
|
|
235
|
+
for part in packed.objects where staged.insert(part.sha).inserted {
|
|
236
|
+
fields["sha256"] = .string(part.sha)
|
|
237
|
+
fields["body"] = .string(part.body.base64EncodedString())
|
|
238
|
+
_ = try await client.call("fs.part", input: .object(fields))
|
|
239
|
+
}
|
|
240
|
+
let hashes = packed.objects.map(\.sha)
|
|
241
|
+
let json = try await client.fsCommit(
|
|
242
|
+
spaceId: spaceId, contentSha: packed.contentSha, size: packed.size, manifestHex: packed.manifestHex, hashes: hashes,
|
|
243
|
+
path: path, name: name, inodeId: inodeId, expectedGeneration: expectedGeneration)
|
|
244
|
+
return try FileJSON.node(json, fallbackName: name ?? "")
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
public final class AdoorFileTrash: FileTrash, @unchecked Sendable {
|
|
249
|
+
private let client: AdoorClient
|
|
250
|
+
|
|
251
|
+
public init(client: AdoorClient) { self.client = client }
|
|
252
|
+
|
|
253
|
+
public func listDeleted(spaceId: String, folderId: String) async throws -> DeletedFolder {
|
|
254
|
+
var fields: [String: JSONValue] = ["spaceId": .string(spaceId), "parentId": .string(folderId), "limit": .number(1000)]
|
|
255
|
+
var files: [DeletedRow] = []
|
|
256
|
+
var days = DeletedFolder.defaultRetentionDays
|
|
257
|
+
var guardPages = 0
|
|
258
|
+
var cursor: String?
|
|
259
|
+
repeat {
|
|
260
|
+
if let cursor { fields["cursor"] = .string(cursor) }
|
|
261
|
+
let json = try await call("fs.list_deleted", fields)
|
|
262
|
+
let page = try FileJSON.deleted(json)
|
|
263
|
+
days = page.retentionDays
|
|
264
|
+
files.append(contentsOf: page.files)
|
|
265
|
+
cursor = page.nextCursor
|
|
266
|
+
guardPages += 1
|
|
267
|
+
} while cursor != nil && guardPages < 20
|
|
268
|
+
return DeletedFolder(files: files, retentionDays: days, nextCursor: cursor)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
public func restore(spaceId: String, inodeId: String) async throws {
|
|
272
|
+
_ = try await call("fs.restore", ["spaceId": .string(spaceId), "inodeId": .string(inodeId)])
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private func call(_ operation: String, _ fields: [String: JSONValue]) async throws -> JSONValue {
|
|
276
|
+
do {
|
|
277
|
+
let (json, _) = try await client.call(operation, input: .object(fields))
|
|
278
|
+
return json
|
|
279
|
+
} catch let error as AdoorError where error.code == "UNKNOWN_OPERATION" {
|
|
280
|
+
throw AdoorError(code: "ENDPOINT_UNAVAILABLE", message: "\(operation) is not on this server.", status: 501)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import XCTest
|
|
2
|
+
import Foundation
|
|
3
|
+
#if canImport(FoundationNetworking)
|
|
4
|
+
import FoundationNetworking
|
|
5
|
+
#endif
|
|
6
|
+
@testable import ADoor
|
|
7
|
+
|
|
8
|
+
/// Unit tests run anywhere. Integration tests run against a local ADoor fixture when ADOOR_TEST_URL and
|
|
9
|
+
/// ADOOR_TEST_TOKEN name a server and a connection access key with select/insert/update/delete on a `notes`
|
|
10
|
+
/// table (title text, done boolean). They do not provision a database.
|
|
11
|
+
final class ADoorTests: XCTestCase {
|
|
12
|
+
func testPKCEChallengeIsSHA256OfVerifier() throws {
|
|
13
|
+
let empty = SHA256.hash(Data())
|
|
14
|
+
XCTAssertEqual(empty.map { String(format: "%02x", $0) }.joined(), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
|
|
15
|
+
let abc = SHA256.hash(Data("abc".utf8))
|
|
16
|
+
XCTAssertEqual(abc.map { String(format: "%02x", $0) }.joined(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
|
17
|
+
let pkce = OAuth.createPKCE()
|
|
18
|
+
XCTAssertEqual(pkce.codeChallenge, OAuth.base64url(SHA256.hash(Data(pkce.codeVerifier.utf8))))
|
|
19
|
+
XCTAssertFalse(pkce.codeChallenge.contains("="))
|
|
20
|
+
let url = try OAuth.authorizationURL(url: URL(string: "https://adoor.example")!, clientId: "client", redirectUri: "myapp://callback", pkce: pkce)
|
|
21
|
+
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
|
|
22
|
+
XCTAssertEqual(components.path, "/oauth/authorize")
|
|
23
|
+
XCTAssertEqual(components.queryItems?.first { $0.name == "code_challenge_method" }?.value, "S256")
|
|
24
|
+
XCTAssertEqual(components.queryItems?.first { $0.name == "state" }?.value, pkce.state)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
func testAuthorizationRejectsNonNetworkEndpoints() throws {
|
|
28
|
+
for endpoint in ["javascript:alert(1)", "JaVaScRiPt:alert(1)", "JAVASCRIPT:alert(1)", "data:text/html,script", "file:///tmp/page.html", "com.example.app:/oauth", "my-app+oauth://authorize", "http:/missing-host"] {
|
|
29
|
+
let url = try XCTUnwrap(URL(string: endpoint))
|
|
30
|
+
XCTAssertThrowsError(try OAuth.authorizationURL(url: url, clientId: "client", redirectUri: "com.example.app:/callback", pkce: OAuth.createPKCE())) { error in
|
|
31
|
+
XCTAssertEqual((error as? AdoorError)?.code, "INVALID_URL")
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Foundation may reject these inputs itself; any parsed URL must still be rejected here.
|
|
35
|
+
for endpoint in ["java\nscript:alert(1)", "java\tscript:alert(1)", "java\rscript:alert(1)", "\u{0000}javascript:alert(1)", " javascript:alert(1)"] {
|
|
36
|
+
if let url = URL(string: endpoint) {
|
|
37
|
+
XCTAssertThrowsError(try OAuth.authorizationURL(url: url, clientId: "client", redirectUri: "com.example.app:/callback", pkce: OAuth.createPKCE()))
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
func testAuthorizationPreservesPrivateUseCallbacksAndEncodedData() throws {
|
|
43
|
+
let pkce = OAuth.createPKCE()
|
|
44
|
+
for endpoint in ["https://adoor.example", "http://remote.example:8080", "http://127.0.0.1:4345", "HTTPS://adoor.example"] {
|
|
45
|
+
for redirect in ["http://127.0.0.1:49101/callback", "cursor://anysphere.cursor-mcp/oauth/callback", "com.example.app:/oauth2redirect/provider", "com.example.app+oauth:/callback?data=%09%0A%20", "com.example.app-oauth:/callback", "MyApp://callback"] {
|
|
46
|
+
let url = try OAuth.authorizationURL(url: XCTUnwrap(URL(string: endpoint + "/base%20path")), clientId: "client", redirectUri: redirect, pkce: pkce, scope: "mcp offline_access", resource: "https://adoor.example/mcp?label=hello%20world")
|
|
47
|
+
let components = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false))
|
|
48
|
+
let items = Dictionary(uniqueKeysWithValues: (components.queryItems ?? []).map { ($0.name, $0.value ?? "") })
|
|
49
|
+
XCTAssertEqual(components.percentEncodedPath, "/base%20path/oauth/authorize")
|
|
50
|
+
XCTAssertEqual(items["redirect_uri"], redirect)
|
|
51
|
+
XCTAssertEqual(items["client_id"], "client")
|
|
52
|
+
XCTAssertEqual(items["response_type"], "code")
|
|
53
|
+
XCTAssertEqual(items["state"], pkce.state)
|
|
54
|
+
XCTAssertEqual(items["code_challenge"], pkce.codeChallenge)
|
|
55
|
+
XCTAssertEqual(items["code_challenge_method"], "S256")
|
|
56
|
+
XCTAssertEqual(items["scope"], "mcp offline_access")
|
|
57
|
+
XCTAssertEqual(items["resource"], "https://adoor.example/mcp?label=hello%20world")
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
func testSSEFramesParseAcrossFieldsAndBlankLines() {
|
|
63
|
+
var parser = SSEFrameParser()
|
|
64
|
+
XCTAssertNil(parser.feed(line: ": heartbeat"))
|
|
65
|
+
XCTAssertNil(parser.feed(line: "id: 17"))
|
|
66
|
+
XCTAssertNil(parser.feed(line: "event: change"))
|
|
67
|
+
XCTAssertNil(parser.feed(line: "data: {\"cursor\":\"17\","))
|
|
68
|
+
XCTAssertNil(parser.feed(line: "data: \"type\":\"table_changed\"}\r"))
|
|
69
|
+
let frame = parser.feed(line: "")
|
|
70
|
+
XCTAssertEqual(frame, SSEFrameParser.Frame(id: "17", event: "change", data: "{\"cursor\":\"17\",\n\"type\":\"table_changed\"}"))
|
|
71
|
+
XCTAssertNil(parser.feed(line: ""), "Consecutive blank lines emit nothing.")
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
func testJSONValueRoundTripsRowsAndLiterals() throws {
|
|
75
|
+
let row: Row = ["id": "a", "qty": 2, "done": false, "note": nil, "tags": ["x", "y"], "meta": ["k": 1.5]]
|
|
76
|
+
let data = try JSON.encode(row)
|
|
77
|
+
let decoded = try JSON.decode(Row.self, from: data)
|
|
78
|
+
XCTAssertEqual(decoded, row)
|
|
79
|
+
XCTAssertEqual(decoded["qty"]?.intValue, 2)
|
|
80
|
+
XCTAssertEqual(decoded["meta"]?["k"]?.doubleValue, 1.5)
|
|
81
|
+
XCTAssertTrue(decoded["note"]?.isNull ?? false)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
func testSqlResultDistinguishesSingleAndBatch() throws {
|
|
85
|
+
let single = Data(#"{"rows":[{"n":1}],"columns":[{"name":"n","type":"23"}],"rowCount":1,"command":"SELECT","schemaVersion":3}"#.utf8)
|
|
86
|
+
let result = try SqlResult(json: try JSON.decode(JSONValue.self, from: single), data: single)
|
|
87
|
+
XCTAssertEqual(result.single?.rows.first?["n"]?.intValue, 1)
|
|
88
|
+
let batch = Data(#"{"batch":true,"atomic":false,"completed":1,"failedAt":1,"results":[{"index":0,"sql":"INSERT 1","kind":"insert","status":"success","rows":[],"columns":[],"rowCount":1,"command":"INSERT","schemaVersion":3,"eventId":"9"},{"index":1,"sql":"INSERT 2","kind":"insert","status":"error","error":{"code":"TABLE_NOT_FOUND","message":"missing","status":404}},{"index":2,"sql":"SELECT","kind":"select","status":"skipped"}]}"#.utf8)
|
|
89
|
+
let parsed = try SqlResult(json: try JSON.decode(JSONValue.self, from: batch), data: batch)
|
|
90
|
+
guard let batchResult = parsed.batch else { return XCTFail("expected a batch") }
|
|
91
|
+
XCTAssertEqual(batchResult.completed, 1)
|
|
92
|
+
XCTAssertEqual(batchResult.failedAt, 1)
|
|
93
|
+
XCTAssertEqual(batchResult.results.count, 3)
|
|
94
|
+
if case .error(_, _, let error, _, _, _, _) = batchResult.results[1] { XCTAssertEqual(error.code, "TABLE_NOT_FOUND") } else { XCTFail("expected an error statement") }
|
|
95
|
+
if case .skipped = batchResult.results[2] {} else { XCTFail("expected a skipped statement") }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
func testErrorEnvelopeAndFlags() {
|
|
99
|
+
let response = HTTPURLResponse(url: URL(string: "https://adoor.example/api/operations/data.execute")!, statusCode: 409, httpVersion: nil, headerFields: nil)!
|
|
100
|
+
let error = AdoorError.from(response: response, data: Data(#"{"error":{"code":"CONFLICT","message":"changed"}}"#.utf8))
|
|
101
|
+
XCTAssertEqual(error.code, "CONFLICT")
|
|
102
|
+
XCTAssertEqual(error.status, 409)
|
|
103
|
+
XCTAssertFalse(error.retryable)
|
|
104
|
+
XCTAssertFalse(error.authority)
|
|
105
|
+
XCTAssertTrue(AdoorError(code: "WORKSPACE_BUSY", message: "", status: 429).retryable)
|
|
106
|
+
XCTAssertTrue(AdoorError(code: "FORBIDDEN", message: "", status: 403).authority)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
func testTablesAreInferredFromSQL() {
|
|
110
|
+
XCTAssertEqual(LocalStore.tables(in: "SELECT p.name FROM people p JOIN companies c ON c.id=p.company_id WHERE p.archived=false"), ["people", "companies"])
|
|
111
|
+
XCTAssertEqual(LocalStore.tables(in: "SELECT 1"), [])
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// MARK: Integration
|
|
115
|
+
|
|
116
|
+
private func fixture() throws -> AdoorClient {
|
|
117
|
+
guard let url = ProcessInfo.processInfo.environment["ADOOR_TEST_URL"].flatMap(URL.init(string:)), let token = ProcessInfo.processInfo.environment["ADOOR_TEST_TOKEN"] else {
|
|
118
|
+
throw XCTSkip("Set ADOOR_TEST_URL and ADOOR_TEST_TOKEN to run against a local ADoor fixture.")
|
|
119
|
+
}
|
|
120
|
+
return AdoorClient(url: url, accessKey: token)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
func testIntegrationQueryExecuteAndIdempotentReplay() async throws {
|
|
124
|
+
let client = try fixture()
|
|
125
|
+
let description = try await client.describe()
|
|
126
|
+
XCTAssertTrue(description.tables.contains { $0.name == "notes" })
|
|
127
|
+
let key = UUID().uuidString
|
|
128
|
+
let title = "swift-\(key.prefix(8))"
|
|
129
|
+
let first = try await client.execute("INSERT INTO notes(title,done) VALUES ($1,false) RETURNING id", params: [.string(title)], idempotencyKey: key)
|
|
130
|
+
let again = try await client.execute("INSERT INTO notes(title,done) VALUES ($1,false) RETURNING id", params: [.string(title)], idempotencyKey: key)
|
|
131
|
+
XCTAssertEqual(again.single?.replayed, true)
|
|
132
|
+
XCTAssertEqual(first.single?.rows, again.single?.rows)
|
|
133
|
+
let read = try await client.query("SELECT count(*)::int AS n FROM notes WHERE title=$1", params: [.string(title)])
|
|
134
|
+
XCTAssertEqual(read.single?.rows.first?["n"]?.intValue, 1)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
func testIntegrationConflictIsEnforcedByTheServer() async throws {
|
|
138
|
+
let client = try fixture()
|
|
139
|
+
let title = "swift-conflict-\(UUID().uuidString.prefix(8))"
|
|
140
|
+
_ = try await client.execute(
|
|
141
|
+
"INSERT INTO notes(title,done) VALUES ($1,false)",
|
|
142
|
+
params: [.string(title)],
|
|
143
|
+
idempotencyKey: UUID().uuidString)
|
|
144
|
+
_ = try await client.execute("UPDATE notes SET done=true WHERE title=$1", params: [.string(title)], expectRowCount: 1)
|
|
145
|
+
do {
|
|
146
|
+
_ = try await client.execute("UPDATE notes SET title=$2 WHERE title=$1 AND done=false", params: [.string(title), .string(title + "-stale")], expectRowCount: 1)
|
|
147
|
+
XCTFail("A stale compare-and-set must not commit")
|
|
148
|
+
} catch let error as AdoorError {
|
|
149
|
+
XCTAssertEqual(error.code, "CONFLICT")
|
|
150
|
+
XCTAssertEqual(error.status, 409)
|
|
151
|
+
}
|
|
152
|
+
let read = try await client.query("SELECT done FROM notes WHERE title=$1", params: [.string(title)])
|
|
153
|
+
XCTAssertEqual(read.single?.rows.first?["done"]?.boolValue, true)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
func testIntegrationLocalStoreSnapshotsAppliesOptimisticallyAndFollowsChanges() async throws {
|
|
157
|
+
let client = try fixture()
|
|
158
|
+
let store = LocalStore(client: client, options: LocalStoreOptions(collections: ["notes": CollectionSpec(sql: "SELECT id,title,done FROM notes ORDER BY title")]))
|
|
159
|
+
let running = Task { try await store.start() }
|
|
160
|
+
defer { running.cancel() }
|
|
161
|
+
try await waitUntil("store reaches live") { await store.status == .live }
|
|
162
|
+
let title = "swift-local-\(UUID().uuidString.prefix(8))"
|
|
163
|
+
let result = try await store.mutate(Mutation(sql: "INSERT INTO notes(title,done) VALUES ($1,false) RETURNING id", params: [.string(title)], apply: ["notes": { rows in rows + [["id": "pending", "title": .string(title), "done": false]] }]))
|
|
164
|
+
XCTAssertEqual(result.single?.rowCount, 1)
|
|
165
|
+
try await waitUntil("server row replaces the optimistic one") {
|
|
166
|
+
let rows = await store.rows(of: "notes")
|
|
167
|
+
return rows.contains { $0["title"]?.stringValue == title && $0["id"]?.stringValue != "pending" } && !rows.contains { $0["id"]?.stringValue == "pending" }
|
|
168
|
+
}
|
|
169
|
+
_ = try await client.execute("UPDATE notes SET done=true WHERE title=$1", params: [.string(title)])
|
|
170
|
+
try await waitUntil("external commit is followed") {
|
|
171
|
+
await store.rows(of: "notes").contains { $0["title"]?.stringValue == title && $0["done"]?.boolValue == true }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private func waitUntil(_ what: String, timeout: TimeInterval = 10, _ check: @escaping @Sendable () async -> Bool) async throws {
|
|
176
|
+
let deadline = Date().addingTimeInterval(timeout)
|
|
177
|
+
while !(await check()) {
|
|
178
|
+
if Date() > deadline { XCTFail("Timed out waiting until \(what)"); return }
|
|
179
|
+
try await Task.sleep(nanoseconds: 50_000_000)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import XCTest
|
|
2
|
+
@testable import ADoor
|
|
3
|
+
|
|
4
|
+
final class DesktopSessionStateTests: XCTestCase {
|
|
5
|
+
func testImportsOnceWithoutOverwritingOrResurrectingAProfile() throws {
|
|
6
|
+
let original: JSONValue = ["version": 1, "activeProfile": "team", "profiles": [
|
|
7
|
+
"team": ["url": "https://one.example", "token": "original-token"]
|
|
8
|
+
]]
|
|
9
|
+
var state = try DesktopSessionState(config: original)
|
|
10
|
+
let incoming: JSONValue = ["version": 1, "activeProfile": "other", "profiles": [
|
|
11
|
+
"team": ["url": "https://two.example", "token": "different-token"],
|
|
12
|
+
"other": ["url": "https://two.example", "token": "scoped-token"]
|
|
13
|
+
]]
|
|
14
|
+
try state.importOnce(incoming, source: "/private/config.json")
|
|
15
|
+
XCTAssertEqual(state.active?["token"], "original-token")
|
|
16
|
+
XCTAssertEqual(state.config["profiles"]?["other"]?["token"], "scoped-token")
|
|
17
|
+
XCTAssertTrue(try state.replace(["version": 1, "profiles": [:]], expected: state.revision))
|
|
18
|
+
let restored = try JSONDecoder().decode(DesktopSessionState.self, from: JSONEncoder().encode(state))
|
|
19
|
+
state = restored
|
|
20
|
+
try state.importOnce(incoming, source: "/private/config.json")
|
|
21
|
+
XCTAssertNil(state.active)
|
|
22
|
+
XCTAssertEqual(state.config["profiles"]?.objectValue?.count, 0)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
func testConcurrentReplacementCannotLoseANewerProfile() throws {
|
|
26
|
+
var state = try DesktopSessionState()
|
|
27
|
+
let first = state.revision
|
|
28
|
+
let next: JSONValue = ["version": 1, "profiles": ["cli": ["url": "https://one.example", "token": "cli-token"]]]
|
|
29
|
+
XCTAssertTrue(try state.replace(next, expected: first))
|
|
30
|
+
XCTAssertFalse(try state.replace(["version": 1, "profiles": [:]], expected: first))
|
|
31
|
+
XCTAssertEqual(state.config, next)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
func testRejectsInvalidProfilesAndRemoteCleartextWithoutChangingState() throws {
|
|
35
|
+
var state = try DesktopSessionState()
|
|
36
|
+
for name in ["__proto__", "../outside", "has spaces"] {
|
|
37
|
+
XCTAssertThrowsError(try state.replace(.object(["version": 1, "profiles": .object([
|
|
38
|
+
name: ["url": "https://one.example", "token": "token"]
|
|
39
|
+
])]), expected: state.revision))
|
|
40
|
+
}
|
|
41
|
+
XCTAssertThrowsError(try state.replace(["version": 1, "profiles": [
|
|
42
|
+
"remote": ["url": "http://remote.example", "token": "token"]
|
|
43
|
+
]], expected: state.revision))
|
|
44
|
+
XCTAssertEqual(state.config["profiles"], [:])
|
|
45
|
+
}
|
|
46
|
+
}
|