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,202 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(FoundationNetworking)
|
|
3
|
+
import FoundationNetworking
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// Parses server-sent-events frames line by line; fields repeat per the spec, data lines join with newlines.
|
|
7
|
+
struct SSEFrameParser {
|
|
8
|
+
struct Frame: Equatable { var id: String?; var event = "message"; var data = "" }
|
|
9
|
+
private var id: String?
|
|
10
|
+
private var event: String?
|
|
11
|
+
private var data: [String] = []
|
|
12
|
+
|
|
13
|
+
/// Feed one line without its terminator; returns a frame when a blank line completes one.
|
|
14
|
+
mutating func feed(line raw: String) -> Frame? {
|
|
15
|
+
let line = raw.hasSuffix("\r") ? String(raw.dropLast()) : raw
|
|
16
|
+
if line.isEmpty {
|
|
17
|
+
guard id != nil || event != nil || !data.isEmpty else { return nil }
|
|
18
|
+
let frame = Frame(id: id, event: event ?? "message", data: data.joined(separator: "\n"))
|
|
19
|
+
id = nil; event = nil; data = []
|
|
20
|
+
return frame
|
|
21
|
+
}
|
|
22
|
+
if line.hasPrefix(":") { return nil }
|
|
23
|
+
let field: String, value: String
|
|
24
|
+
if let colon = line.firstIndex(of: ":") {
|
|
25
|
+
field = String(line[..<colon])
|
|
26
|
+
var rest = String(line[line.index(after: colon)...])
|
|
27
|
+
if rest.hasPrefix(" ") { rest.removeFirst() }
|
|
28
|
+
value = rest
|
|
29
|
+
} else { field = line; value = "" }
|
|
30
|
+
switch field {
|
|
31
|
+
case "id": id = value
|
|
32
|
+
case "event": event = value
|
|
33
|
+
case "data": data.append(value)
|
|
34
|
+
default: break
|
|
35
|
+
}
|
|
36
|
+
return nil
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public struct SubscribeOptions: Sendable {
|
|
41
|
+
/// Resume after this durable cursor; capture it with `changesHead()` before loading a snapshot.
|
|
42
|
+
public var after: String?
|
|
43
|
+
public var initialBackoff: TimeInterval = 0.5
|
|
44
|
+
public var maxBackoff: TimeInterval = 10
|
|
45
|
+
/// A connection without any frame for this long is reopened. The server heartbeats well inside it.
|
|
46
|
+
public var idleTimeout: TimeInterval = 30
|
|
47
|
+
public init(after: String? = nil) { self.after = after }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// The cursor and liveness of one subscription, shared between the reading task and its watchdog.
|
|
51
|
+
actor StreamState {
|
|
52
|
+
private(set) var cursor: String
|
|
53
|
+
private var lastFrame = Date()
|
|
54
|
+
init(cursor: String) { self.cursor = cursor }
|
|
55
|
+
func touch() { lastFrame = Date() }
|
|
56
|
+
func advance(to next: String) { cursor = next; lastFrame = Date() }
|
|
57
|
+
func silent(for interval: TimeInterval) -> Bool { Date().timeIntervalSince(lastFrame) > interval }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
extension AdoorClient {
|
|
61
|
+
/// A resumable change subscription. The cursor advances only on frames the server sent, so a reconnect never
|
|
62
|
+
/// skips or repeats an authorized event. The stream ends when its task is cancelled, and throws when the
|
|
63
|
+
/// caller's authority ends.
|
|
64
|
+
public func subscribeChanges(_ options: SubscribeOptions = SubscribeOptions()) -> AsyncThrowingStream<ChangeFrame, Error> {
|
|
65
|
+
AsyncThrowingStream { continuation in
|
|
66
|
+
let task = Task {
|
|
67
|
+
let state = StreamState(cursor: options.after ?? "0")
|
|
68
|
+
var delay = options.initialBackoff
|
|
69
|
+
while !Task.isCancelled {
|
|
70
|
+
await state.touch()
|
|
71
|
+
let attempt = Task<Void, Error> { try await self.readStream(state: state, continuation: continuation) }
|
|
72
|
+
let watchdog = Task<Void, Never> {
|
|
73
|
+
while !Task.isCancelled {
|
|
74
|
+
try? await Task.sleep(nanoseconds: UInt64(options.idleTimeout / 2 * 1_000_000_000))
|
|
75
|
+
if Task.isCancelled { return }
|
|
76
|
+
if await state.silent(for: options.idleTimeout) { attempt.cancel(); return }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
do {
|
|
80
|
+
try await withTaskCancellationHandler { try await attempt.value } onCancel: { attempt.cancel(); watchdog.cancel() }
|
|
81
|
+
watchdog.cancel()
|
|
82
|
+
delay = options.initialBackoff
|
|
83
|
+
} catch {
|
|
84
|
+
watchdog.cancel()
|
|
85
|
+
if Task.isCancelled { break }
|
|
86
|
+
let typed = error as? AdoorError ?? AdoorError.network(error)
|
|
87
|
+
if typed.authority { continuation.finish(throwing: typed); return }
|
|
88
|
+
}
|
|
89
|
+
if Task.isCancelled { break }
|
|
90
|
+
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
|
|
91
|
+
delay = min(options.maxBackoff, delay * 2)
|
|
92
|
+
}
|
|
93
|
+
continuation.finish()
|
|
94
|
+
}
|
|
95
|
+
continuation.onTermination = { _ in task.cancel() }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// One connection attempt: reads frames until the server or the network ends the stream.
|
|
100
|
+
func readStream(state: StreamState, continuation: AsyncThrowingStream<ChangeFrame, Error>.Continuation) async throws {
|
|
101
|
+
let request = try await makeRequest(path: "api/changes/stream", accept: "text/event-stream", extra: ["Last-Event-ID": await state.cursor])
|
|
102
|
+
let transport = ChunkedResponse(configuration: session.configuration)
|
|
103
|
+
let chunks = transport.open(request)
|
|
104
|
+
let http: HTTPURLResponse
|
|
105
|
+
do { http = try await transport.response() }
|
|
106
|
+
catch { throw error as? AdoorError ?? AdoorError.network(error) }
|
|
107
|
+
guard (200..<300).contains(http.statusCode) else {
|
|
108
|
+
var body = Data()
|
|
109
|
+
for try await chunk in chunks { body.append(chunk); if body.count > 65_536 { break } }
|
|
110
|
+
throw AdoorError.from(response: http, data: body)
|
|
111
|
+
}
|
|
112
|
+
await state.touch()
|
|
113
|
+
var parser = SSEFrameParser(), pending = Data()
|
|
114
|
+
// Split on newline bytes. AsyncLines-style APIs drop the blank line that ends an SSE frame.
|
|
115
|
+
for try await chunk in chunks {
|
|
116
|
+
pending.append(chunk)
|
|
117
|
+
while let newline = pending.firstIndex(of: 10) {
|
|
118
|
+
let line = pending.prefix(upTo: newline)
|
|
119
|
+
pending.removeSubrange(...newline)
|
|
120
|
+
if line.count > 1_048_576 { throw AdoorError(code: "STREAM_FRAME_LIMIT", message: "The change stream line exceeded its limit.", status: 502) }
|
|
121
|
+
await state.touch()
|
|
122
|
+
guard let frame = parser.feed(line: String(decoding: line, as: UTF8.self)) else { continue }
|
|
123
|
+
switch frame.event {
|
|
124
|
+
case "change":
|
|
125
|
+
let change = try JSON.decode(ChangeEvent.self, from: Data(frame.data.utf8))
|
|
126
|
+
await state.advance(to: change.cursor)
|
|
127
|
+
continuation.yield(.change(change))
|
|
128
|
+
case "checkpoint":
|
|
129
|
+
let checkpoint = try JSON.decode(Checkpoint.self, from: Data(frame.data.utf8))
|
|
130
|
+
await state.advance(to: checkpoint.cursor)
|
|
131
|
+
continuation.yield(.checkpoint(cursor: checkpoint.cursor))
|
|
132
|
+
case "error":
|
|
133
|
+
let body = try JSON.decode(JSONValue.self, from: Data(frame.data.utf8))
|
|
134
|
+
throw AdoorError(code: body["error"]?["code"]?.stringValue ?? "STREAM_FAILED", message: body["error"]?["message"]?.stringValue ?? "The change stream stopped.", status: 503)
|
|
135
|
+
default:
|
|
136
|
+
break
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if pending.count > 1_048_576 { throw AdoorError(code: "STREAM_FRAME_LIMIT", message: "The change stream line exceeded its limit.", status: 502) }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/// Incremental body for the change stream. Linux URLSession has no `bytes(for:)`, and a buffered `data(for:)`
|
|
145
|
+
/// would not return until the stream ended. Redirects are refused, matching the other authenticated calls.
|
|
146
|
+
private final class ChunkedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendable {
|
|
147
|
+
private let configuration: URLSessionConfiguration
|
|
148
|
+
private let lock = NSLock()
|
|
149
|
+
private var body: AsyncThrowingStream<Data, Error>.Continuation?
|
|
150
|
+
private var responseWaiter: CheckedContinuation<HTTPURLResponse, Error>?
|
|
151
|
+
private var responseResult: Result<HTTPURLResponse, Error>?
|
|
152
|
+
private var session: URLSession?
|
|
153
|
+
private var task: URLSessionTask?
|
|
154
|
+
|
|
155
|
+
init(configuration: URLSessionConfiguration) { self.configuration = configuration }
|
|
156
|
+
|
|
157
|
+
func open(_ request: URLRequest) -> AsyncThrowingStream<Data, Error> {
|
|
158
|
+
let streaming = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
|
|
159
|
+
let task = streaming.dataTask(with: request)
|
|
160
|
+
self.session = streaming
|
|
161
|
+
self.task = task
|
|
162
|
+
return AsyncThrowingStream { continuation in
|
|
163
|
+
self.body = continuation
|
|
164
|
+
continuation.onTermination = { _ in task.cancel(); streaming.invalidateAndCancel() }
|
|
165
|
+
task.resume()
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
func response() async throws -> HTTPURLResponse {
|
|
170
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
171
|
+
lock.lock()
|
|
172
|
+
if let responseResult { lock.unlock(); continuation.resume(with: responseResult) }
|
|
173
|
+
else { responseWaiter = continuation; lock.unlock() }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
|
|
178
|
+
let http = (response as? HTTPURLResponse) ?? HTTPURLResponse(url: response.url ?? URL(string: "https://invalid.invalid")!, statusCode: 0, httpVersion: nil, headerFields: nil)!
|
|
179
|
+
lock.lock(); responseResult = .success(http); let waiter = responseWaiter; responseWaiter = nil; lock.unlock()
|
|
180
|
+
waiter?.resume(returning: http)
|
|
181
|
+
completionHandler(.allow)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { body?.yield(data) }
|
|
185
|
+
|
|
186
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
187
|
+
lock.lock(); let waiting = responseResult == nil; lock.unlock()
|
|
188
|
+
if waiting {
|
|
189
|
+
let failure: Error = error.map { AdoorError.network($0) } ?? AdoorError(code: "HTTP_INVALID", message: "The server returned no HTTP response.", status: 0)
|
|
190
|
+
lock.lock(); responseResult = .failure(failure); let waiter = responseWaiter; responseWaiter = nil; lock.unlock()
|
|
191
|
+
waiter?.resume(throwing: failure)
|
|
192
|
+
}
|
|
193
|
+
if let error { body?.finish(throwing: AdoorError.network(error)) } else { body?.finish() }
|
|
194
|
+
session.finishTasksAndInvalidate()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
|
198
|
+
completionHandler(nil)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
struct Checkpoint: Decodable { let cursor: String }
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public struct DesktopSessionState: Codable, Sendable {
|
|
4
|
+
public private(set) var revision: String = UUID().uuidString
|
|
5
|
+
public private(set) var config: JSONValue
|
|
6
|
+
private var importedSources: Set<String> = []
|
|
7
|
+
|
|
8
|
+
public init(config: JSONValue = ["version": 1, "profiles": [:]]) throws {
|
|
9
|
+
try Self.validate(config)
|
|
10
|
+
self.config = config
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
public var snapshot: JSONValue { ["revision": .string(revision), "config": config] }
|
|
14
|
+
|
|
15
|
+
public var active: JSONValue? {
|
|
16
|
+
guard let name = config["activeProfile"]?.stringValue else { return nil }
|
|
17
|
+
return config["profiles"]?[name]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
@discardableResult
|
|
21
|
+
public mutating func replace(_ next: JSONValue, expected: String) throws -> Bool {
|
|
22
|
+
guard expected == revision else { return false }
|
|
23
|
+
try Self.validate(next)
|
|
24
|
+
config = next
|
|
25
|
+
revision = UUID().uuidString
|
|
26
|
+
return true
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
public mutating func importOnce(_ incoming: JSONValue, source: String) throws {
|
|
30
|
+
guard !importedSources.contains(source) else { return }
|
|
31
|
+
try Self.validate(incoming)
|
|
32
|
+
var next = config.objectValue!
|
|
33
|
+
var profiles = next["profiles"]!.objectValue!
|
|
34
|
+
for (name, profile) in incoming["profiles"]!.objectValue! where profiles[name] == nil { profiles[name] = profile }
|
|
35
|
+
next["profiles"] = .object(profiles)
|
|
36
|
+
if next["activeProfile"] == nil { next["activeProfile"] = incoming["activeProfile"] }
|
|
37
|
+
for key in ["pendingLogins", "databases"] {
|
|
38
|
+
var values = next[key]?.objectValue ?? [:]
|
|
39
|
+
for (name, value) in incoming[key]?.objectValue ?? [:] where values[name] == nil { values[name] = value }
|
|
40
|
+
if !values.isEmpty { next[key] = .object(values) }
|
|
41
|
+
}
|
|
42
|
+
_ = try replace(.object(next), expected: revision)
|
|
43
|
+
importedSources.insert(source)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public static func validate(_ value: JSONValue) throws {
|
|
47
|
+
guard value["version"]?.intValue == 1, let profiles = value["profiles"]?.objectValue else { throw invalid() }
|
|
48
|
+
for (name, profile) in profiles {
|
|
49
|
+
guard validName(name), let token = profile["token"]?.stringValue, !token.isEmpty,
|
|
50
|
+
let server = profile["url"]?.stringValue, let url = URL(string: server) else { throw invalid() }
|
|
51
|
+
try ServerOrigin.validate(url)
|
|
52
|
+
}
|
|
53
|
+
if let pending = value["pendingLogins"] {
|
|
54
|
+
guard let requests = pending.objectValue else { throw invalid() }
|
|
55
|
+
for (name, request) in requests {
|
|
56
|
+
guard validName(name), let server = request["url"]?.stringValue, let url = URL(string: server),
|
|
57
|
+
let code = request["deviceCode"]?.stringValue, !code.isEmpty,
|
|
58
|
+
FileJSON.date(request["expiresAt"]?.stringValue) != nil else { throw invalid() }
|
|
59
|
+
try ServerOrigin.validate(url)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if let active = value["activeProfile"]?.stringValue, !validName(active) { throw invalid() }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
public static func validName(_ name: String) -> Bool {
|
|
66
|
+
name.range(of: "^[a-zA-Z][a-zA-Z0-9_-]{0,63}$", options: .regularExpression) != nil &&
|
|
67
|
+
!["__proto__", "constructor", "prototype"].contains(name)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private static func invalid() -> AdoorError {
|
|
71
|
+
AdoorError(code: "INVALID_CONFIG", message: "The saved connections are invalid.", status: 400)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public struct DeviceStart: Equatable, Sendable {
|
|
4
|
+
public let deviceCode: String
|
|
5
|
+
public let userCode: String
|
|
6
|
+
public let approvalURL: URL
|
|
7
|
+
public let expiresAt: Date
|
|
8
|
+
public let interval: TimeInterval
|
|
9
|
+
|
|
10
|
+
public init(deviceCode: String, userCode: String, approvalURL: URL, expiresAt: Date, interval: TimeInterval) {
|
|
11
|
+
self.deviceCode = deviceCode
|
|
12
|
+
self.userCode = userCode
|
|
13
|
+
self.approvalURL = approvalURL
|
|
14
|
+
self.expiresAt = expiresAt
|
|
15
|
+
self.interval = interval
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
public enum DevicePoll: Equatable, Sendable {
|
|
20
|
+
case pending
|
|
21
|
+
case approved(token: String)
|
|
22
|
+
case expired
|
|
23
|
+
case denied
|
|
24
|
+
case consumed
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
public enum DeviceFlow {
|
|
28
|
+
public static let userCode = try! NSRegularExpression(
|
|
29
|
+
pattern: "^[BCDFGHJKLMNPQRSTVWXZ23456789]{4}-[BCDFGHJKLMNPQRSTVWXZ23456789]{4}$")
|
|
30
|
+
|
|
31
|
+
public static func parseStart(_ json: JSONValue, origin: URL) throws -> DeviceStart {
|
|
32
|
+
guard let deviceCode = json["deviceCode"]?.stringValue, deviceCode.count >= 20,
|
|
33
|
+
let userCode = json["userCode"]?.stringValue, codeMatches(userCode),
|
|
34
|
+
let approval = json["approvalUrl"]?.stringValue, let approvalURL = URL(string: approval),
|
|
35
|
+
let expires = FileJSON.date(json["expiresAt"]?.stringValue) else {
|
|
36
|
+
throw AdoorError(code: "INVALID_RESPONSE", message: "The server returned an invalid sign-in request.", status: 502)
|
|
37
|
+
}
|
|
38
|
+
guard approvalURL.scheme == origin.scheme, approvalURL.host == origin.host, approvalURL.port == origin.port else {
|
|
39
|
+
throw AdoorError(code: "INVALID_RESPONSE", message: "The sign-in link is not on this server.", status: 502)
|
|
40
|
+
}
|
|
41
|
+
let interval = TimeInterval(max(1, json["interval"]?.intValue ?? 2))
|
|
42
|
+
return DeviceStart(deviceCode: deviceCode, userCode: userCode, approvalURL: approvalURL, expiresAt: expires, interval: interval)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public static func parsePoll(_ json: JSONValue) throws -> DevicePoll {
|
|
46
|
+
switch json["status"]?.stringValue {
|
|
47
|
+
case "pending": return .pending
|
|
48
|
+
case "expired": return .expired
|
|
49
|
+
case "denied": return .denied
|
|
50
|
+
case "consumed": return .consumed
|
|
51
|
+
case "approved":
|
|
52
|
+
guard let token = json["token"]?.stringValue, !token.isEmpty else {
|
|
53
|
+
throw AdoorError(code: "INVALID_RESPONSE", message: "Sign-in completed without a connection credential.", status: 502)
|
|
54
|
+
}
|
|
55
|
+
return .approved(token: token)
|
|
56
|
+
default:
|
|
57
|
+
throw AdoorError(code: "INVALID_RESPONSE", message: "The server returned an invalid sign-in state.", status: 502)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Text safe to log. The device code and any bearer stay out of it.
|
|
62
|
+
public static func redacted(_ start: DeviceStart) -> String {
|
|
63
|
+
"Enter \(start.userCode) at \(start.approvalURL.absoluteString)"
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private static func codeMatches(_ value: String) -> Bool {
|
|
67
|
+
let range = NSRange(value.startIndex..<value.endIndex, in: value)
|
|
68
|
+
return userCode.firstMatch(in: value, range: range) != nil
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public enum FolderCatalog {
|
|
4
|
+
public static func workspaces(from json: JSONValue) -> [WorkspaceRow] {
|
|
5
|
+
(json["workspaces"]?.arrayValue ?? []).compactMap { item in
|
|
6
|
+
guard let id = item["id"]?.stringValue, let name = item["name"]?.stringValue, let slug = item["slug"]?.stringValue else {
|
|
7
|
+
return nil
|
|
8
|
+
}
|
|
9
|
+
return WorkspaceRow(id: id, name: name, slug: slug, current: item["current"]?.boolValue == true)
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
public static func spaces(from json: JSONValue, workspaceID: String) -> [SpaceRow] {
|
|
14
|
+
(json["spaces"]?.arrayValue ?? []).compactMap { item in
|
|
15
|
+
guard item["archived"]?.boolValue != true, let id = item["id"]?.stringValue, let name = item["name"]?.stringValue else {
|
|
16
|
+
return nil
|
|
17
|
+
}
|
|
18
|
+
return SpaceRow(id: id, name: name, slug: item["slug"]?.stringValue ?? id, workspaceID: workspaceID)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public static func folders(
|
|
23
|
+
page: RemotePage, spaceID: String, mounts: [MountRecord], workspace: String, space: String
|
|
24
|
+
) -> [FolderRow] {
|
|
25
|
+
page.entries.filter { $0.kind == .directory }.map { node in
|
|
26
|
+
let path = "/" + node.name
|
|
27
|
+
let mount = mounts.first { $0.workspace == workspace && $0.space == space && $0.remotePath == path }
|
|
28
|
+
return FolderRow(
|
|
29
|
+
id: node.idString, name: node.name, spaceID: spaceID, access: node.access,
|
|
30
|
+
mounted: mount?.state == "mounted", sync: syncWord(mount), localPath: mount?.localPath)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private static func syncWord(_ mount: MountRecord?) -> SyncWord {
|
|
35
|
+
guard let mount, mount.state == "mounted" else { return .unmounted }
|
|
36
|
+
return SyncWord(rawValue: mount.sync) ?? .current
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public enum KeychainPlacement {
|
|
41
|
+
public static let service = "com.halmoslabs.adoor.mac"
|
|
42
|
+
public static let account = "connection"
|
|
43
|
+
public static let accessGroup = "2URP8R2VFB.group.com.halmoslabs.adoor"
|
|
44
|
+
public static let accessible = "kSecAttrAccessibleWhenUnlockedThisDeviceOnly"
|
|
45
|
+
|
|
46
|
+
public static func record(account: String = KeychainPlacement.account) -> [String: String] {
|
|
47
|
+
["class": "kSecClassGenericPassword", "service": service, "account": account, "accessible": accessible]
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Any JSON value. Rows are dictionaries of these; parameters are arrays of them.
|
|
4
|
+
public enum JSONValue: Codable, Equatable, Hashable, Sendable {
|
|
5
|
+
case null
|
|
6
|
+
case bool(Bool)
|
|
7
|
+
case number(Double)
|
|
8
|
+
case string(String)
|
|
9
|
+
case array([JSONValue])
|
|
10
|
+
case object([String: JSONValue])
|
|
11
|
+
|
|
12
|
+
public init(from decoder: Decoder) throws {
|
|
13
|
+
let container = try decoder.singleValueContainer()
|
|
14
|
+
if container.decodeNil() { self = .null; return }
|
|
15
|
+
if let value = try? container.decode(Bool.self) { self = .bool(value); return }
|
|
16
|
+
if let value = try? container.decode(Double.self) { self = .number(value); return }
|
|
17
|
+
if let value = try? container.decode(String.self) { self = .string(value); return }
|
|
18
|
+
if let value = try? container.decode([JSONValue].self) { self = .array(value); return }
|
|
19
|
+
if let value = try? container.decode([String: JSONValue].self) { self = .object(value); return }
|
|
20
|
+
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON value")
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
public func encode(to encoder: Encoder) throws {
|
|
24
|
+
var container = encoder.singleValueContainer()
|
|
25
|
+
switch self {
|
|
26
|
+
case .null: try container.encodeNil()
|
|
27
|
+
case .bool(let value): try container.encode(value)
|
|
28
|
+
case .number(let value): try container.encode(value)
|
|
29
|
+
case .string(let value): try container.encode(value)
|
|
30
|
+
case .array(let value): try container.encode(value)
|
|
31
|
+
case .object(let value): try container.encode(value)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
public subscript(key: String) -> JSONValue? {
|
|
36
|
+
if case .object(let object) = self { return object[key] }
|
|
37
|
+
return nil
|
|
38
|
+
}
|
|
39
|
+
public var stringValue: String? { if case .string(let value) = self { return value }; return nil }
|
|
40
|
+
public var doubleValue: Double? { if case .number(let value) = self { return value }; return nil }
|
|
41
|
+
public var intValue: Int? { if case .number(let value) = self, value == value.rounded() { return Int(exactly: value) }; return nil }
|
|
42
|
+
public var boolValue: Bool? { if case .bool(let value) = self { return value }; return nil }
|
|
43
|
+
public var arrayValue: [JSONValue]? { if case .array(let value) = self { return value }; return nil }
|
|
44
|
+
public var objectValue: [String: JSONValue]? { if case .object(let value) = self { return value }; return nil }
|
|
45
|
+
public var isNull: Bool { if case .null = self { return true }; return false }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
extension JSONValue: ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
|
|
49
|
+
public init(stringLiteral value: String) { self = .string(value) }
|
|
50
|
+
public init(integerLiteral value: Int) { self = .number(Double(value)) }
|
|
51
|
+
public init(floatLiteral value: Double) { self = .number(value) }
|
|
52
|
+
public init(booleanLiteral value: Bool) { self = .bool(value) }
|
|
53
|
+
public init(nilLiteral: ()) { self = .null }
|
|
54
|
+
public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }
|
|
55
|
+
public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(uniqueKeysWithValues: elements)) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// One table row as the server returned it.
|
|
59
|
+
public typealias Row = [String: JSONValue]
|
|
60
|
+
|
|
61
|
+
enum JSON {
|
|
62
|
+
static let decoder = JSONDecoder()
|
|
63
|
+
static let encoder: JSONEncoder = {
|
|
64
|
+
let encoder = JSONEncoder()
|
|
65
|
+
encoder.outputFormatting = [.sortedKeys]
|
|
66
|
+
return encoder
|
|
67
|
+
}()
|
|
68
|
+
static func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T { try decoder.decode(type, from: data) }
|
|
69
|
+
static func encode<T: Encodable>(_ value: T) throws -> Data { try encoder.encode(value) }
|
|
70
|
+
}
|