1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit
extension ATProtoBlueskyService {
func restoreAccount() async throws -> Account? {
try await restoreAccount { _ in }
}
func restoreAccount(onLocalAccount: @MainActor @Sendable (String) -> Void) async throws -> Account? {
let generation = UUID()
sessionGeneration = generation
selectedLabelers.removeAll()
cachedLabelDefinitions.removeAll()
refreshTask = nil
let restored: StoredSession
do {
let lock = try await acquireRefreshLock()
defer {
if let lock {
flock(lock, LOCK_UN)
close(lock)
}
}
guard generation == sessionGeneration else { throw ServiceError.noSession }
if usesSharedSession, try currentSessionID() == nil,
let legacyID = defaults.string(forKey: sessionDefaultsKey) {
try migrateLegacySession(account: legacyID)
}
guard let sessionID = try currentSessionID() else { return nil }
guard let data = try keychainRead(account: sessionID) else {
try clearCurrentSessionID()
return nil
}
activeSessionID = sessionID
restored = try JSONDecoder().decode(StoredSession.self, from: data)
stored = restored
}
await onLocalAccount(restored.did)
guard generation == sessionGeneration else { throw ServiceError.noSession }
_ = try await accessToken()
guard generation == sessionGeneration else { throw ServiceError.noSession }
let result = await account(for: restored)
guard generation == sessionGeneration else { throw ServiceError.noSession }
return result
}
func signIn(handle: String, appPassword: String, authFactorToken: String?) async throws -> Account {
let cleanHandle = handle.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "@", with: "")
guard !cleanHandle.isEmpty, !appPassword.isEmpty else { throw ServiceError.invalidCredentials }
let generation = UUID()
sessionGeneration = generation
selectedLabelers.removeAll()
cachedLabelDefinitions.removeAll()
refreshTask = nil
let did = try await resolveDID(for: cleanHandle)
let loginPDSURL = try await resolvePDSURL(for: did)
let client = await apiClient(for: loginPDSURL)
let response: ComAtprotoLexicon.Server.CreateSessionOutput
do {
response = try await client.createSession(
with: cleanHandle, and: appPassword,
authenticationFactorToken: authFactorToken.flatMap { $0.isEmpty ? nil : $0 })
} catch ServiceError.serverResponse(let code, _)
where authFactorToken != nil && ["InvalidToken", "ExpiredToken"].contains(code) {
throw ServiceError.authFactorTokenRejected
}
let documentData = try response.didDocument?.toJSON()
let fallbackDocument = documentData.flatMap { try? JSONSerialization.jsonObject(with: $0) }
let pdsURL = try await resolvePDSURL(for: response.did, fallbackDocument: fallbackDocument)
guard generation == sessionGeneration else { throw ServiceError.noSession }
let newSession = StoredSession(
handle: response.handle, did: response.did, accessToken: response.accessToken,
refreshToken: response.refreshToken, expiresAt: Self.expiration(of: response.accessToken), pdsURL: pdsURL)
try await storeSession(newSession, generation: generation)
followRecordURIs.removeAll()
let result = await account(for: newSession)
guard generation == sessionGeneration else { throw ServiceError.noSession }
return result
}
func account(for session: StoredSession) async -> Account {
let profile = try? await getProfile(actorID: session.did)
var account = Account(
handle: session.handle,
displayName: profile?.displayName ?? session.handle,
id: session.did,
avatarURL: profile?.avatarImageURL
)
account.isAvatarURLKnown = profile != nil
return account
}
func signOut() async throws {
sessionGeneration = UUID()
refreshTask?.cancel()
refreshTask = nil
let lock = try await acquireRefreshLock()
defer {
if let lock {
flock(lock, LOCK_UN)
close(lock)
}
}
let sessionID = try currentSessionID()
if !usesSharedSession || sessionID == activeSessionID {
try clearCurrentSessionID()
if let sessionID { try keychainDelete(account: sessionID) }
if usesSharedSession { clearLegacySession() }
}
activeSessionID = nil
stored = nil
selectedLabelers.removeAll()
cachedLabelDefinitions.removeAll()
followRecordURIs.removeAll()
}
private func storeSession(_ newSession: StoredSession, generation: UUID) async throws {
let sessionID = UUID().uuidString
do {
let lock = try await acquireRefreshLock()
defer {
if let lock {
flock(lock, LOCK_UN)
close(lock)
}
}
guard generation == sessionGeneration else { throw ServiceError.noSession }
let previousSessionID = try currentSessionID()
try keychainWrite(JSONEncoder().encode(newSession), account: sessionID)
do {
try setCurrentSessionID(sessionID)
} catch {
try? keychainDelete(account: sessionID)
throw error
}
if let previousSessionID { try? keychainDelete(account: previousSessionID) }
if usesSharedSession { clearLegacySession() }
activeSessionID = sessionID
stored = newSession
}
}
}