Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ManagedSocialAuth.swift
| 1 | import AppKit |
| 2 | import AuthenticationServices |
| 3 | import CryptoKit |
| 4 | import Foundation |
| 5 | import Security |
| 6 | |
| 7 | enum SocialPlatform: String, CaseIterable, Identifiable { |
| 8 | case x, linkedin, instagram, reddit, tiktok |
| 9 | |
| 10 | var id: Self { self } |
| 11 | var name: String { platformName(rawValue) } |
| 12 | var supportsSharedConnection: Bool { self != .x } |
| 13 | |
| 14 | var identityURL: URL { |
| 15 | let address = switch self { |
| 16 | case .x: "https://api.x.com/2/users/me" |
| 17 | case .linkedin: "https://api.linkedin.com/v2/userinfo" |
| 18 | case .instagram: "https://graph.instagram.com/v25.0/me?fields=user_id,username,account_type" |
| 19 | case .reddit: "https://oauth.reddit.com/api/v1/me" |
| 20 | case .tiktok: "https://open.tiktokapis.com/v2/user/info/?fields=open_id,display_name,avatar_url" |
| 21 | } |
| 22 | return URL(string: address)! |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | struct ManagedSocialSession: Codable, Sendable { |
| 27 | let accessToken: String |
| 28 | let refreshToken: String? |
| 29 | let managedTicket: String? |
| 30 | let expiresAt: Int64 |
| 31 | let scopes: String? |
| 32 | |
| 33 | private enum CodingKeys: String, CodingKey { |
| 34 | case accessToken, refreshToken, managedTicket, expiresAt, scopes |
| 35 | } |
| 36 | |
| 37 | init(accessToken: String, refreshToken: String?, managedTicket: String?, expiresAt: Int64, scopes: String?) { |
| 38 | self.accessToken = accessToken |
| 39 | self.refreshToken = refreshToken |
| 40 | self.managedTicket = managedTicket |
| 41 | self.expiresAt = expiresAt |
| 42 | self.scopes = scopes |
| 43 | } |
| 44 | |
| 45 | init(from decoder: Decoder) throws { |
| 46 | let fields = try decoder.container(keyedBy: CodingKeys.self) |
| 47 | accessToken = try fields.decode(String.self, forKey: .accessToken) |
| 48 | refreshToken = try fields.decodeIfPresent(String.self, forKey: .refreshToken) |
| 49 | managedTicket = try fields.decodeIfPresent(String.self, forKey: .managedTicket) |
| 50 | expiresAt = try fields.decode(Int64.self, forKey: .expiresAt) |
| 51 | if let permissions = try? fields.decode([String].self, forKey: .scopes) { |
| 52 | scopes = permissions.joined(separator: ",") |
| 53 | } else { |
| 54 | scopes = try fields.decodeIfPresent(String.self, forKey: .scopes) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func validate(now: Date = .now) throws { |
| 59 | guard !accessToken.isEmpty, accessToken.utf8.count <= 24_000, |
| 60 | (refreshToken?.utf8.count ?? 0) <= 12_000, (managedTicket?.utf8.count ?? 0) <= 12_000, |
| 61 | (scopes?.utf8.count ?? 0) <= 5000, expiration > now else { |
| 62 | throw WorkspaceError("The platform returned an incomplete connection. Connect again.") |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | var expiration: Date { Date(timeIntervalSince1970: Double(expiresAt) / 1000) } |
| 67 | } |
| 68 | |
| 69 | struct ManagedSocialAccount: Codable, Sendable { |
| 70 | var session: ManagedSocialSession |
| 71 | let id: String |
| 72 | let name: String |
| 73 | let username: String |
| 74 | var ownApp: Bool? = nil |
| 75 | var linkedInPages: [LinkedInDestination]? = nil |
| 76 | var connectedAt: String? = nil |
| 77 | var connectionKey: String { id + ":" + (connectedAt ?? "") } |
| 78 | } |
| 79 | |
| 80 | struct ManagedOAuthHandshake { |
| 81 | static let base = URL(string: "https://inkspring.ai/api/desktop/connect/")! |
| 82 | private static let purpose = Data("inkspring-desktop-result-v1".utf8) |
| 83 | private static let x25519Prefix = Data([0x30, 0x2A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x6E, 0x03, 0x21, 0x00]) |
| 84 | private static let ed25519Prefix = Data([0x30, 0x2A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x03, 0x21, 0x00]) |
| 85 | |
| 86 | let platform: SocialPlatform |
| 87 | let state: String |
| 88 | private let key: Curve25519.KeyAgreement.PrivateKey |
| 89 | private let signing: Curve25519.Signing.PublicKey |
| 90 | |
| 91 | init(platform: SocialPlatform, signingKey: String) throws { |
| 92 | guard platform.supportsSharedConnection else { |
| 93 | throw WorkspaceError("Set up your own X developer app in Connections to use X.") |
| 94 | } |
| 95 | self.platform = platform |
| 96 | key = Curve25519.KeyAgreement.PrivateKey() |
| 97 | signing = try Curve25519.Signing.PublicKey(rawRepresentation: Self.rawKey(signingKey, prefix: Self.ed25519Prefix)) |
| 98 | var entropy = Data(count: 32) |
| 99 | let result = entropy.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!) } |
| 100 | guard result == errSecSuccess else { throw WorkspaceError("Couldn’t create a secure sign-in request.") } |
| 101 | state = platform.rawValue + "." + entropy.base64URL |
| 102 | } |
| 103 | |
| 104 | var url: URL { |
| 105 | Self.base.appending(path: "start").appending(queryItems: [ |
| 106 | URLQueryItem(name: "provider", value: platform.rawValue), |
| 107 | URLQueryItem(name: "state", value: state), |
| 108 | URLQueryItem(name: "publicKey", value: (Self.x25519Prefix + key.publicKey.rawRepresentation).base64URL) |
| 109 | ]) |
| 110 | } |
| 111 | |
| 112 | private struct Envelope: Decodable { |
| 113 | let v: Int |
| 114 | let key: String |
| 115 | let iv: String |
| 116 | let data: String |
| 117 | let tag: String |
| 118 | let signature: String |
| 119 | |
| 120 | var signedBytes: Data { |
| 121 | Data(#"{"v":1,"key":"\#(key)","iv":"\#(iv)","data":"\#(data)","tag":"\#(tag)"}"#.utf8) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | private struct Result: Decodable { |
| 126 | let provider: String |
| 127 | let state: String |
| 128 | let expiresAt: Int64 |
| 129 | let error: String? |
| 130 | let session: ManagedSocialSession? |
| 131 | } |
| 132 | |
| 133 | func open(_ callback: URL, now: Date = .now) throws -> ManagedSocialSession { |
| 134 | guard callback.absoluteString.utf8.count < 100_000, |
| 135 | let components = URLComponents(url: callback, resolvingAgainstBaseURL: false), |
| 136 | components.scheme == "inkspring", components.host == "oauth", components.port == nil, |
| 137 | components.user == nil, components.password == nil, components.path == "/" + platform.rawValue, |
| 138 | components.queryItems?.filter({ $0.name == "state" }).map(\.value) == [state] else { |
| 139 | throw WorkspaceError("This sign-in belongs to another session. Connect again.") |
| 140 | } |
| 141 | if components.queryItems?.contains(where: { $0.name == "error" }) == true { |
| 142 | throw WorkspaceError("Sign-in was declined. Your previous connection is unchanged.") |
| 143 | } |
| 144 | guard let fragment = components.percentEncodedFragment, |
| 145 | let results = URLComponents(string: "https://inkspring.ai/?" + fragment)?.queryItems?.filter({ $0.name == "result" }), |
| 146 | results.count == 1, let text = results.first?.value, text.utf8.count <= 96_000 else { |
| 147 | throw WorkspaceError("The connection return was incomplete. Connect again.") |
| 148 | } |
| 149 | let result: Result |
| 150 | do { |
| 151 | let envelope = try JSONDecoder().decode(Envelope.self, from: Data(base64URL: text)) |
| 152 | let ciphertext = try Data(base64URL: envelope.data) |
| 153 | let tag = try Data(base64URL: envelope.tag) |
| 154 | let iv = try Data(base64URL: envelope.iv) |
| 155 | let peer = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: Self.rawKey(envelope.key, prefix: Self.x25519Prefix)) |
| 156 | guard envelope.v == 1, iv.count == 12, tag.count == 16, |
| 157 | signing.isValidSignature(try Data(base64URL: envelope.signature), for: envelope.signedBytes) else { |
| 158 | throw WorkspaceError("Invalid sign-in signature.") |
| 159 | } |
| 160 | let secret = try key.sharedSecretFromKeyAgreement(with: peer) |
| 161 | .hkdfDerivedSymmetricKey(using: SHA256.self, salt: Data(), sharedInfo: Self.purpose, outputByteCount: 32) |
| 162 | let box = try AES.GCM.SealedBox(nonce: AES.GCM.Nonce(data: iv), ciphertext: ciphertext, tag: tag) |
| 163 | result = try JSONDecoder().decode(Result.self, from: AES.GCM.open(box, using: secret, authenticating: Self.purpose)) |
| 164 | } catch { |
| 165 | throw WorkspaceError("The connection return could not be verified. Connect again.") |
| 166 | } |
| 167 | guard result.provider == platform.rawValue, result.state == state, |
| 168 | Double(result.expiresAt) / 1000 > now.timeIntervalSince1970 else { |
| 169 | throw WorkspaceError("The sign-in expired or belongs to another session.") |
| 170 | } |
| 171 | if let error = result.error { throw WorkspaceError(error) } |
| 172 | guard let session = result.session else { |
| 173 | throw WorkspaceError("The connection service could not authorize this account.") |
| 174 | } |
| 175 | try session.validate(now: now) |
| 176 | return session |
| 177 | } |
| 178 | |
| 179 | private static func rawKey(_ value: String, prefix: Data) throws -> Data { |
| 180 | let bytes = try Data(base64URL: value) |
| 181 | guard bytes.count == prefix.count + 32, bytes.starts(with: prefix) else { |
| 182 | throw WorkspaceError("The connection service returned an invalid public key.") |
| 183 | } |
| 184 | return Data(bytes.dropFirst(prefix.count)) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | extension Data { |
| 189 | var base64URL: String { |
| 190 | base64EncodedString().replacingOccurrences(of: "+", with: "-") |
| 191 | .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") |
| 192 | } |
| 193 | |
| 194 | fileprivate init(base64URL: String) throws { |
| 195 | guard !base64URL.isEmpty, base64URL.utf8.allSatisfy({ |
| 196 | (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 |
| 197 | }) else { throw WorkspaceError("Invalid sign-in encoding.") } |
| 198 | let padded = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") |
| 199 | + String(repeating: "=", count: (4 - base64URL.utf8.count % 4) % 4) |
| 200 | guard let result = Data(base64Encoded: padded), result.base64URL == base64URL else { |
| 201 | throw WorkspaceError("Invalid sign-in encoding.") |
| 202 | } |
| 203 | self = result |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | @MainActor @Observable |
| 208 | final class ManagedSocialAccounts: NSObject, ASWebAuthenticationPresentationContextProviding { |
| 209 | struct Profile: Equatable { |
| 210 | let id: String |
| 211 | let name: String |
| 212 | let username: String |
| 213 | let usesDeveloperApp: Bool |
| 214 | |
| 215 | var displayName: String { username.isEmpty ? name : username } |
| 216 | } |
| 217 | |
| 218 | private(set) var profiles: [SocialPlatform: Profile] = [:] |
| 219 | private(set) var availability: Set<SocialPlatform> = [] |
| 220 | private(set) var developerAppIDs: [SocialPlatform: String] = [:] |
| 221 | private(set) var developerPages = false |
| 222 | private(set) var linkedInDestinations: [LinkedInDestination] = [] |
| 223 | private(set) var connecting: SocialPlatform? |
| 224 | private var signingKey = "" |
| 225 | private var browserSession: ASWebAuthenticationSession? |
| 226 | private var loopback: LoopbackOAuth? |
| 227 | private var signInTimeout: Task<Void, Never>? |
| 228 | private var refreshes: [SocialPlatform: Task<ManagedSocialAccount, Error>] = [:] |
| 229 | private var revisions: [SocialPlatform: UUID] = [:] |
| 230 | private let transport: SocialTransport |
| 231 | |
| 232 | init(transport: SocialTransport = SocialTransport()) { |
| 233 | self.transport = transport |
| 234 | } |
| 235 | |
| 236 | func loadSavedConnections() throws { |
| 237 | for platform in SocialPlatform.allCases where profiles[platform] == nil { |
| 238 | if let account = try savedAccount(platform) { |
| 239 | profiles[platform] = profile(account) |
| 240 | if platform == .linkedin { setLinkedInDestinations(account) } |
| 241 | } |
| 242 | } |
| 243 | for platform in SocialPlatform.allCases { |
| 244 | if let configuration = try SocialAccountKeychain.configuration(platform) { |
| 245 | developerAppIDs[platform] = configuration.clientID |
| 246 | if platform == .linkedin { developerPages = configuration.linkedInPages } |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func load() async throws { |
| 252 | try loadSavedConnections() |
| 253 | let (result, _) = try await transport.request(ManagedOAuthHandshake.base.appending(path: "config")) |
| 254 | guard result["version"] as? Int == 1, let signingKey = result["signingKey"] as? String, |
| 255 | signingKey.utf8.count <= 100, let providers = result["providers"] as? [String: Any] else { |
| 256 | throw WorkspaceError("The Inkspring connection service returned an unreadable configuration.") |
| 257 | } |
| 258 | self.signingKey = signingKey |
| 259 | availability = Set(SocialPlatform.allCases.filter { platform in |
| 260 | platform.supportsSharedConnection |
| 261 | && (providers[platform.rawValue] as? [String: Any])?["available"] as? Bool == true |
| 262 | && !signingKey.isEmpty |
| 263 | }) |
| 264 | } |
| 265 | |
| 266 | func saveDeveloperApp(_ platform: SocialPlatform, input: DeveloperOAuthConfiguration) throws { |
| 267 | guard connecting != platform else { throw WorkspaceError("Finish the current sign-in first.") } |
| 268 | let old = try SocialAccountKeychain.configuration(platform) |
| 269 | var configuration = input |
| 270 | configuration.clientID = configuration.clientID.trimmingCharacters(in: .whitespacesAndNewlines) |
| 271 | configuration.clientSecret = configuration.clientSecret.trimmingCharacters(in: .whitespacesAndNewlines) |
| 272 | if configuration.clientSecret.isEmpty && old?.clientID == configuration.clientID { |
| 273 | configuration.clientSecret = old?.clientSecret ?? "" |
| 274 | } |
| 275 | try configuration.validate(platform) |
| 276 | if old != configuration, try SocialAccountKeychain.read(platform)?.ownApp == true { |
| 277 | try disconnect(platform) |
| 278 | } |
| 279 | try SocialAccountKeychain.saveConfiguration(configuration, for: platform) |
| 280 | developerAppIDs[platform] = configuration.clientID |
| 281 | if platform == .linkedin { developerPages = configuration.linkedInPages } |
| 282 | } |
| 283 | |
| 284 | func connect(_ platform: SocialPlatform, developerApp: Bool = false) async throws { |
| 285 | guard platform.supportsSharedConnection || developerApp else { |
| 286 | throw WorkspaceError("Set up your own X developer app in Connections to use X.") |
| 287 | } |
| 288 | guard connecting == nil else { throw WorkspaceError("Finish the current sign-in first.") } |
| 289 | connecting = platform |
| 290 | defer { |
| 291 | connecting = nil |
| 292 | browserSession = nil |
| 293 | loopback = nil |
| 294 | signInTimeout?.cancel() |
| 295 | signInTimeout = nil |
| 296 | } |
| 297 | let revision = UUID() |
| 298 | revisions[platform] = revision |
| 299 | let session: ManagedSocialSession |
| 300 | if developerApp { |
| 301 | guard let configuration = try SocialAccountKeychain.configuration(platform) else { |
| 302 | throw WorkspaceError("Save the developer app before connecting.") |
| 303 | } |
| 304 | let request = try DeveloperOAuth(platform: platform, configuration: configuration) |
| 305 | let callback: URL |
| 306 | if platform.usesLoopback { |
| 307 | let listener = LoopbackOAuth(callback: platform.developerCallback, state: request.state) |
| 308 | loopback = listener |
| 309 | callback = try await listener.wait(opening: request.url) |
| 310 | } else { |
| 311 | callback = try await authorize(request.url) |
| 312 | } |
| 313 | session = try await request.exchange(callback, transport: transport) |
| 314 | } else { |
| 315 | try await load() |
| 316 | guard availability.contains(platform) else { throw WorkspaceError("Shared sign-in is unavailable for \(platform.name).") } |
| 317 | let handshake = try ManagedOAuthHandshake(platform: platform, signingKey: signingKey) |
| 318 | let callback = try await authorize(handshake.url) |
| 319 | session = try handshake.open(callback) |
| 320 | } |
| 321 | var account = try await identify(platform, session: session) |
| 322 | account.ownApp = developerApp |
| 323 | account.connectedAt = WorkspaceRecord.timestamp |
| 324 | guard revisions[platform] == revision else { throw CancellationError() } |
| 325 | try SocialAccountKeychain.save(account, for: platform) |
| 326 | profiles[platform] = profile(account) |
| 327 | if platform == .linkedin { setLinkedInDestinations(account) } |
| 328 | } |
| 329 | |
| 330 | func refreshLinkedInPages() async throws { |
| 331 | let account = try await authorized(.linkedin) |
| 332 | let pages = try await LinkedInPages.refresh(account, transport: transport) |
| 333 | guard var current = try SocialAccountKeychain.read(.linkedin), current.id == account.id, |
| 334 | current.session.accessToken == account.session.accessToken else { |
| 335 | throw WorkspaceError("The LinkedIn account changed. Refresh company pages again.") |
| 336 | } |
| 337 | current.linkedInPages = pages |
| 338 | try SocialAccountKeychain.save(current, for: .linkedin) |
| 339 | setLinkedInDestinations(current) |
| 340 | } |
| 341 | |
| 342 | func savedLinkedInDestinations() throws -> [LinkedInDestination] { |
| 343 | guard let account = try SocialAccountKeychain.read(.linkedin) else { return [] } |
| 344 | return [LinkedInDestination.personal(account)] + (LinkedInPages.available(account) ? account.linkedInPages ?? [] : []) |
| 345 | } |
| 346 | |
| 347 | private func setLinkedInDestinations(_ account: ManagedSocialAccount) { |
| 348 | linkedInDestinations = [LinkedInDestination.personal(account)] + (LinkedInPages.available(account) ? account.linkedInPages ?? [] : []) |
| 349 | } |
| 350 | |
| 351 | func disconnect(_ platform: SocialPlatform) throws { |
| 352 | revisions[platform] = UUID() |
| 353 | if connecting == platform { |
| 354 | browserSession?.cancel() |
| 355 | loopback?.cancel() |
| 356 | } |
| 357 | refreshes[platform]?.cancel() |
| 358 | try SocialAccountKeychain.remove(platform) |
| 359 | profiles[platform] = nil |
| 360 | if platform == .linkedin { linkedInDestinations = [] } |
| 361 | } |
| 362 | |
| 363 | func savedAccount(_ platform: SocialPlatform) throws -> ManagedSocialAccount? { |
| 364 | guard let account = try SocialAccountKeychain.read(platform), |
| 365 | platform.supportsSharedConnection || account.ownApp == true else { return nil } |
| 366 | return account |
| 367 | } |
| 368 | |
| 369 | func hasSavedAccount(_ platform: SocialPlatform) -> Bool { |
| 370 | if !platform.supportsSharedConnection { return (try? savedAccount(platform)) != nil } |
| 371 | return SocialAccountKeychain.contains(platform) |
| 372 | } |
| 373 | |
| 374 | func xReadToken() async throws -> String? { |
| 375 | if ProviderKey.x.isSaved { return try ProviderKey.x.read() } |
| 376 | guard try savedAccount(.x) != nil else { return nil } |
| 377 | return try await authorized(.x).session.accessToken |
| 378 | } |
| 379 | |
| 380 | func testConnection(_ platform: SocialPlatform) async throws -> Profile { |
| 381 | guard let saved = try savedAccount(platform) else { |
| 382 | throw WorkspaceError("Connect \(platform.name) before testing the connection.") |
| 383 | } |
| 384 | let revision = revisions[platform] |
| 385 | let checked = try await verifyIdentity(platform, account: saved) |
| 386 | guard revision == revisions[platform], let current = try savedAccount(platform), |
| 387 | current.connectionKey == saved.connectionKey, |
| 388 | current.session.accessToken == saved.session.accessToken else { |
| 389 | throw WorkspaceError("The account changed during the check. Test the connection again.") |
| 390 | } |
| 391 | return checked |
| 392 | } |
| 393 | |
| 394 | func verifyIdentity(_ platform: SocialPlatform, account: ManagedSocialAccount) async throws -> Profile { |
| 395 | guard platform.supportsSharedConnection || account.ownApp == true else { |
| 396 | throw WorkspaceError("Set up your own X developer app in Connections to use X.") |
| 397 | } |
| 398 | guard account.session.expiration > .now else { |
| 399 | throw WorkspaceError("This session has expired. Reconnect \(platform.name) before testing again.") |
| 400 | } |
| 401 | var current = try await identify(platform, session: account.session, timeout: 15) |
| 402 | try Task.checkCancellation() |
| 403 | guard current.id == account.id else { |
| 404 | throw WorkspaceError("The platform returned a different account. Reconnect \(platform.name).") |
| 405 | } |
| 406 | current.ownApp = account.ownApp |
| 407 | return profile(current) |
| 408 | } |
| 409 | |
| 410 | func authorized(_ platform: SocialPlatform) async throws -> ManagedSocialAccount { |
| 411 | if let refresh = refreshes[platform] { return try await refresh.value } |
| 412 | guard let account = try savedAccount(platform) else { |
| 413 | if !platform.supportsSharedConnection { |
| 414 | throw WorkspaceError("Set up your own X developer app in Connections to use X.") |
| 415 | } |
| 416 | throw WorkspaceError("Connect \(platform.name) in Connections first.") |
| 417 | } |
| 418 | let threshold: TimeInterval = platform == .instagram ? 7 * 86_400 : 60 |
| 419 | if account.session.expiration.timeIntervalSinceNow > threshold { return account } |
| 420 | let revision = revisions[platform] |
| 421 | let refresh = Task { @MainActor in |
| 422 | var updated = account |
| 423 | if account.ownApp == true, platform != .instagram { |
| 424 | guard let configuration = try SocialAccountKeychain.configuration(platform) else { |
| 425 | throw WorkspaceError("Configure the developer app and reconnect.") |
| 426 | } |
| 427 | updated.session = try await DeveloperOAuth.refresh(platform, configuration: configuration, |
| 428 | session: account.session, transport: self.transport) |
| 429 | } else { |
| 430 | updated.session = try await self.refreshSession(platform, account.session) |
| 431 | } |
| 432 | try Task.checkCancellation() |
| 433 | guard revision == self.revisions[platform] else { throw CancellationError() } |
| 434 | try SocialAccountKeychain.save(updated, for: platform) |
| 435 | return updated |
| 436 | } |
| 437 | refreshes[platform] = refresh |
| 438 | defer { refreshes[platform] = nil } |
| 439 | return try await refresh.value |
| 440 | } |
| 441 | |
| 442 | private func refreshSession(_ platform: SocialPlatform, _ session: ManagedSocialSession) async throws -> ManagedSocialSession { |
| 443 | if platform == .instagram, session.expiration > .now { |
| 444 | let url = URL(string: "https://graph.instagram.com/refresh_access_token")!.appending(queryItems: [ |
| 445 | URLQueryItem(name: "grant_type", value: "ig_refresh_token"), |
| 446 | URLQueryItem(name: "access_token", value: session.accessToken) |
| 447 | ]) |
| 448 | let (value, _) = try await transport.request(url) |
| 449 | if let token = value["access_token"] as? String, let duration = value["expires_in"] as? Int64, |
| 450 | (1...31_536_000).contains(duration) { |
| 451 | let new = ManagedSocialSession(accessToken: token, refreshToken: session.refreshToken, |
| 452 | managedTicket: session.managedTicket, |
| 453 | expiresAt: Int64(Date.now.timeIntervalSince1970 * 1000) + duration * 1000, scopes: session.scopes) |
| 454 | try new.validate() |
| 455 | return new |
| 456 | } |
| 457 | } else if let token = session.refreshToken, !token.isEmpty, |
| 458 | let ticket = session.managedTicket, !ticket.isEmpty { |
| 459 | let (value, _) = try await transport.request(ManagedOAuthHandshake.base.appending(path: "refresh"), method: "POST", |
| 460 | json: ["provider": platform.rawValue, "refreshToken": token, "ticket": ticket]) |
| 461 | let new = try JSONDecoder().decode(ManagedSocialSession.self, from: JSONSerialization.data(withJSONObject: value)) |
| 462 | try new.validate() |
| 463 | return new |
| 464 | } |
| 465 | throw WorkspaceError("This social session has expired. Reconnect in Connections.") |
| 466 | } |
| 467 | |
| 468 | private func identify(_ platform: SocialPlatform, session: ManagedSocialSession, timeout: TimeInterval = 45) async throws -> ManagedSocialAccount { |
| 469 | let headers = platform == .reddit ? ["User-Agent": "desktop:com.protomota.inkspring:v1.0 (Inkspring; https://inkspring.ai)"] : [:] |
| 470 | let (value, _) = try await transport.request(platform.identityURL, token: session.accessToken, headers: headers, timeout: timeout) |
| 471 | let data = value["data"] as? [String: Any] ?? [:] |
| 472 | let person = switch platform { |
| 473 | case .x: data |
| 474 | case .tiktok: data["user"] as? [String: Any] ?? [:] |
| 475 | default: value |
| 476 | } |
| 477 | let id: Any? = switch platform { |
| 478 | case .linkedin: person["sub"] |
| 479 | case .instagram: person["user_id"] ?? person["id"] |
| 480 | case .tiktok: person["open_id"] |
| 481 | default: person["id"] |
| 482 | } |
| 483 | let accountID = id as? String ?? (id as? NSNumber)?.stringValue ?? "" |
| 484 | guard !accountID.isEmpty, accountID.utf8.count <= 300 else { |
| 485 | throw WorkspaceError("The platform did not identify this account.") |
| 486 | } |
| 487 | if platform == .instagram, let type = person["account_type"] as? String, |
| 488 | !["BUSINESS", "CREATOR", "MEDIA_CREATOR"].contains(type) { |
| 489 | throw WorkspaceError("Instagram publishing requires a Business or Creator account.") |
| 490 | } |
| 491 | let username = String((person["username"] as? String ?? person["name"] as? String ?? "").prefix(300)) |
| 492 | let name = String((person["display_name"] as? String ?? person["name"] as? String ?? person["username"] as? String ?? "Connected account").prefix(300)) |
| 493 | return ManagedSocialAccount(session: session, id: accountID, name: name, username: username) |
| 494 | } |
| 495 | |
| 496 | private func authorize(_ url: URL) async throws -> URL { |
| 497 | try await withCheckedThrowingContinuation { continuation in |
| 498 | let completion: ASWebAuthenticationSession.CompletionHandler = { callback, error in |
| 499 | if let callback { continuation.resume(returning: callback) } |
| 500 | else if (error as? ASWebAuthenticationSessionError)?.code == .canceledLogin { |
| 501 | continuation.resume(throwing: CancellationError()) |
| 502 | } else { |
| 503 | continuation.resume(throwing: WorkspaceError("Couldn’t complete browser sign-in.")) |
| 504 | } |
| 505 | } |
| 506 | let session: ASWebAuthenticationSession |
| 507 | if #available(macOS 14.4, *) { |
| 508 | session = ASWebAuthenticationSession(url: url, callback: .customScheme("inkspring"), completionHandler: completion) |
| 509 | } else { |
| 510 | session = ASWebAuthenticationSession(url: url, callbackURLScheme: "inkspring", completionHandler: completion) |
| 511 | } |
| 512 | session.presentationContextProvider = self |
| 513 | browserSession = session |
| 514 | if session.start() { |
| 515 | signInTimeout = Task { @MainActor in |
| 516 | try? await Task.sleep(for: .seconds(600)) |
| 517 | if !Task.isCancelled { session.cancel() } |
| 518 | } |
| 519 | } else { |
| 520 | continuation.resume(throwing: WorkspaceError("Couldn’t open browser sign-in.")) |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { |
| 526 | NSApp.keyWindow ?? NSApp.mainWindow ?? ASPresentationAnchor() |
| 527 | } |
| 528 | |
| 529 | private func profile(_ account: ManagedSocialAccount) -> Profile { |
| 530 | Profile(id: account.id, name: account.name, username: account.username, usesDeveloperApp: account.ownApp == true) |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | private enum SocialAccountKeychain { |
| 535 | private static func query(_ item: String) -> [String: Any] { |
| 536 | [ |
| 537 | kSecClass as String: kSecClassGenericPassword, |
| 538 | kSecAttrService as String: "com.protomota.inkspring.native.social", |
| 539 | kSecAttrAccount as String: item |
| 540 | ] |
| 541 | } |
| 542 | |
| 543 | static func read(_ platform: SocialPlatform) throws -> ManagedSocialAccount? { |
| 544 | try readItem(platform.rawValue) |
| 545 | } |
| 546 | |
| 547 | static func contains(_ platform: SocialPlatform) -> Bool { |
| 548 | SecItemCopyMatching(query(platform.rawValue) as CFDictionary, nil) == errSecSuccess |
| 549 | } |
| 550 | |
| 551 | static func save(_ account: ManagedSocialAccount, for platform: SocialPlatform) throws { |
| 552 | try writeItem(platform.rawValue, value: account) |
| 553 | } |
| 554 | |
| 555 | static func configuration(_ platform: SocialPlatform) throws -> DeveloperOAuthConfiguration? { |
| 556 | try readItem("developer-" + platform.rawValue) |
| 557 | } |
| 558 | |
| 559 | static func saveConfiguration(_ configuration: DeveloperOAuthConfiguration, for platform: SocialPlatform) throws { |
| 560 | try writeItem("developer-" + platform.rawValue, value: configuration) |
| 561 | } |
| 562 | |
| 563 | private static func readItem<T: Decodable>(_ item: String) throws -> T? { |
| 564 | var query = query(item) |
| 565 | query[kSecReturnData as String] = true |
| 566 | var result: CFTypeRef? |
| 567 | let status = SecItemCopyMatching(query as CFDictionary, &result) |
| 568 | if status == errSecItemNotFound { return nil } |
| 569 | try check(status) |
| 570 | guard let data = result as? Data, let value = try? JSONDecoder().decode(T.self, from: data) else { |
| 571 | throw WorkspaceError("The saved connection couldn’t be read. Configure it again.") |
| 572 | } |
| 573 | return value |
| 574 | } |
| 575 | |
| 576 | private static func writeItem<T: Encodable>(_ item: String, value: T) throws { |
| 577 | let query = query(item) |
| 578 | let data = try JSONEncoder().encode(value) |
| 579 | let status = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary) |
| 580 | if status == errSecItemNotFound { |
| 581 | var attributes = query |
| 582 | attributes[kSecValueData as String] = data |
| 583 | try check(SecItemAdd(attributes as CFDictionary, nil)) |
| 584 | } else { |
| 585 | try check(status) |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | static func remove(_ platform: SocialPlatform) throws { |
| 590 | let status = SecItemDelete(query(platform.rawValue) as CFDictionary) |
| 591 | if status != errSecItemNotFound { try check(status) } |
| 592 | } |
| 593 | |
| 594 | private static func check(_ status: OSStatus) throws { |
| 595 | guard status == errSecSuccess else { throw WorkspaceError("Keychain couldn’t access this social connection (\(status)).") } |
| 596 | } |
| 597 | } |