Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / DeveloperOAuth.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | |
| 4 | struct DeveloperOAuthConfiguration: Codable, Equatable { |
| 5 | var clientID: String |
| 6 | var clientSecret: String |
| 7 | var linkedInPages = false |
| 8 | |
| 9 | func validate(_ platform: SocialPlatform) throws { |
| 10 | guard (1...300).contains(clientID.utf8.count), clientSecret.utf8.count <= 4096, |
| 11 | !(clientID + clientSecret).unicodeScalars.contains(where: CharacterSet.controlCharacters.contains), |
| 12 | !platform.needsClientSecret || !clientSecret.isEmpty else { |
| 13 | throw WorkspaceError("Enter the developer app’s client ID and required secret.") |
| 14 | } |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | extension SocialPlatform { |
| 19 | var needsClientSecret: Bool { [.linkedin, .instagram, .tiktok].contains(self) } |
| 20 | var usesLoopback: Bool { [.x, .reddit, .tiktok].contains(self) } |
| 21 | |
| 22 | var developerCallback: URL { |
| 23 | URL(string: usesLoopback ? "http://127.0.0.1:43821/oauth/" + rawValue : "https://inkspring.ai/desktop-connect/")! |
| 24 | } |
| 25 | |
| 26 | var developerConsole: URL { |
| 27 | let address = switch self { |
| 28 | case .x: "https://console.x.com/" |
| 29 | case .reddit: "https://www.reddit.com/prefs/apps" |
| 30 | case .linkedin: "https://www.linkedin.com/developers/apps" |
| 31 | case .instagram: "https://developers.facebook.com/apps/" |
| 32 | case .tiktok: "https://developers.tiktok.com/apps/" |
| 33 | } |
| 34 | return URL(string: address)! |
| 35 | } |
| 36 | |
| 37 | fileprivate var authorizeURL: URL { |
| 38 | let address = switch self { |
| 39 | case .x: "https://x.com/i/oauth2/authorize" |
| 40 | case .reddit: "https://www.reddit.com/api/v1/authorize" |
| 41 | case .linkedin: "https://www.linkedin.com/oauth/v2/authorization" |
| 42 | case .instagram: "https://www.instagram.com/oauth/authorize" |
| 43 | case .tiktok: "https://www.tiktok.com/v2/auth/authorize/" |
| 44 | } |
| 45 | return URL(string: address)! |
| 46 | } |
| 47 | |
| 48 | fileprivate var tokenURL: URL { |
| 49 | let address = switch self { |
| 50 | case .x: "https://api.x.com/2/oauth2/token" |
| 51 | case .reddit: "https://www.reddit.com/api/v1/access_token" |
| 52 | case .linkedin: "https://www.linkedin.com/oauth/v2/accessToken" |
| 53 | case .instagram: "https://api.instagram.com/oauth/access_token" |
| 54 | case .tiktok: "https://open.tiktokapis.com/v2/oauth/token/" |
| 55 | } |
| 56 | return URL(string: address)! |
| 57 | } |
| 58 | |
| 59 | fileprivate var clientField: String { self == .tiktok ? "client_key" : "client_id" } |
| 60 | |
| 61 | fileprivate func scopes(_ configuration: DeveloperOAuthConfiguration) -> String { |
| 62 | switch self { |
| 63 | case .x: "tweet.read tweet.write users.read media.write offline.access" |
| 64 | case .reddit: "identity submit read" |
| 65 | case .linkedin: configuration.linkedInPages |
| 66 | ? "openid profile w_member_social rw_organization_admin w_organization_social" |
| 67 | : "openid profile w_member_social" |
| 68 | case .instagram: "instagram_business_basic,instagram_business_content_publish" |
| 69 | case .tiktok: "user.info.basic,video.publish" |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | struct DeveloperOAuth { |
| 75 | let platform: SocialPlatform |
| 76 | let configuration: DeveloperOAuthConfiguration |
| 77 | let state: String |
| 78 | private let verifier: String |
| 79 | |
| 80 | init(platform: SocialPlatform, configuration: DeveloperOAuthConfiguration) throws { |
| 81 | try configuration.validate(platform) |
| 82 | self.platform = platform |
| 83 | self.configuration = configuration |
| 84 | let nonce = Curve25519.KeyAgreement.PrivateKey().rawRepresentation |
| 85 | state = platform.rawValue + "." + nonce.base64URL |
| 86 | verifier = (Curve25519.KeyAgreement.PrivateKey().rawRepresentation |
| 87 | + Curve25519.KeyAgreement.PrivateKey().rawRepresentation).base64URL |
| 88 | } |
| 89 | |
| 90 | var url: URL { |
| 91 | var fields = [ |
| 92 | platform.clientField: configuration.clientID, "redirect_uri": platform.developerCallback.absoluteString, |
| 93 | "response_type": "code", "scope": platform.scopes(configuration), "state": state |
| 94 | ] |
| 95 | if [.x, .tiktok].contains(platform) { |
| 96 | let digest = Data(SHA256.hash(data: Data(verifier.utf8))) |
| 97 | fields["code_challenge"] = platform == .tiktok |
| 98 | ? digest.map { String(format: "%02x", $0) }.joined() : digest.base64URL |
| 99 | fields["code_challenge_method"] = "S256" |
| 100 | } |
| 101 | if platform == .reddit { fields["duration"] = "permanent" } |
| 102 | if platform == .instagram { |
| 103 | fields["enable_fb_login"] = "0" |
| 104 | fields["force_authentication"] = "1" |
| 105 | } |
| 106 | return platform.authorizeURL.appending(queryItems: fields.map { URLQueryItem(name: $0.key, value: $0.value) }) |
| 107 | } |
| 108 | |
| 109 | func callbackCode(_ url: URL) throws -> String { |
| 110 | guard url.absoluteString.utf8.count <= 12_000, let components = URLComponents(url: url, resolvingAgainstBaseURL: false), |
| 111 | components.user == nil, components.password == nil, components.fragment == nil, |
| 112 | let query = components.queryItems, |
| 113 | query.filter({ $0.name == "state" }).map(\.value) == [state] else { |
| 114 | throw WorkspaceError("The sign-in return belongs to another session.") |
| 115 | } |
| 116 | if platform.usesLoopback { |
| 117 | guard components.scheme == "http", components.host == "127.0.0.1", components.port == 43821, |
| 118 | components.path == platform.developerCallback.path else { throw WorkspaceError("Unexpected sign-in return address.") } |
| 119 | } else { |
| 120 | guard components.scheme == "inkspring", components.host == "oauth", components.port == nil, |
| 121 | components.path == "/" + platform.rawValue else { throw WorkspaceError("Unexpected sign-in return address.") } |
| 122 | } |
| 123 | if query.contains(where: { $0.name == "error" }) { throw CancellationError() } |
| 124 | let codes = query.filter { $0.name == "code" } |
| 125 | guard codes.count == 1, let code = codes[0].value, (1...8000).contains(code.utf8.count), |
| 126 | !code.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) else { |
| 127 | throw WorkspaceError("The provider didn’t return a valid authorization code.") |
| 128 | } |
| 129 | return code |
| 130 | } |
| 131 | |
| 132 | @MainActor |
| 133 | func exchange(_ callback: URL, transport: SocialTransport) async throws -> ManagedSocialSession { |
| 134 | let code = try callbackCode(callback) |
| 135 | var fields = [ |
| 136 | "grant_type": "authorization_code", "code": code, "redirect_uri": platform.developerCallback.absoluteString, |
| 137 | platform.clientField: configuration.clientID |
| 138 | ] |
| 139 | if [.x, .tiktok].contains(platform) { fields["code_verifier"] = verifier } |
| 140 | let session = try await Self.token(platform, configuration: configuration, fields: fields, old: nil, transport: transport) |
| 141 | if platform == .instagram { |
| 142 | let url = URL(string: "https://graph.instagram.com/access_token")!.appending(queryItems: [ |
| 143 | .init(name: "grant_type", value: "ig_exchange_token"), |
| 144 | .init(name: "client_secret", value: configuration.clientSecret), |
| 145 | .init(name: "access_token", value: session.accessToken) |
| 146 | ]) |
| 147 | let (value, _) = try await transport.request(url) |
| 148 | return try Self.parseToken(value, old: session) |
| 149 | } |
| 150 | return session |
| 151 | } |
| 152 | |
| 153 | @MainActor |
| 154 | static func refresh(_ platform: SocialPlatform, configuration: DeveloperOAuthConfiguration, |
| 155 | session: ManagedSocialSession, transport: SocialTransport) async throws -> ManagedSocialSession { |
| 156 | guard let refresh = session.refreshToken, !refresh.isEmpty, platform != .instagram else { |
| 157 | throw WorkspaceError("This account needs to sign in again.") |
| 158 | } |
| 159 | return try await token(platform, configuration: configuration, fields: [ |
| 160 | "grant_type": "refresh_token", "refresh_token": refresh, platform.clientField: configuration.clientID |
| 161 | ], old: session, transport: transport) |
| 162 | } |
| 163 | |
| 164 | @MainActor |
| 165 | private static func token(_ platform: SocialPlatform, configuration: DeveloperOAuthConfiguration, fields: [String: String], |
| 166 | old: ManagedSocialSession?, transport: SocialTransport) async throws -> ManagedSocialSession { |
| 167 | var fields = fields |
| 168 | var headers: [String: String] = [:] |
| 169 | if platform == .reddit || platform == .x && !configuration.clientSecret.isEmpty { |
| 170 | let secret = platform == .reddit ? "" : configuration.clientSecret |
| 171 | headers["Authorization"] = "Basic " + Data((configuration.clientID + ":" + secret).utf8).base64EncodedString() |
| 172 | } |
| 173 | if platform == .reddit { |
| 174 | headers["User-Agent"] = "desktop:com.protomota.inkspring:v1.0 (Inkspring; https://inkspring.ai)" |
| 175 | } |
| 176 | if platform.needsClientSecret { fields["client_secret"] = configuration.clientSecret } |
| 177 | let (value, _) = try await transport.form(platform.tokenURL, values: fields, headers: headers) |
| 178 | return try parseToken(value, old: old) |
| 179 | } |
| 180 | |
| 181 | private static func parseToken(_ response: [String: Any], old: ManagedSocialSession?) throws -> ManagedSocialSession { |
| 182 | let value = (response["data"] as? [[String: Any]])?.first ?? response |
| 183 | guard let token = value["access_token"] as? String else { |
| 184 | throw WorkspaceError("The platform did not authorize the developer app.") |
| 185 | } |
| 186 | let duration = value["expires_in"] as? Int64 ?? 3600 |
| 187 | guard (1...31_536_000).contains(duration) else { throw WorkspaceError("The platform returned an invalid token lifetime.") } |
| 188 | let session = ManagedSocialSession( |
| 189 | accessToken: token, refreshToken: value["refresh_token"] as? String ?? old?.refreshToken, managedTicket: nil, |
| 190 | expiresAt: Int64(Date.now.timeIntervalSince1970 * 1000) + duration * 1000, |
| 191 | scopes: value["scope"] as? String ?? value["permissions"] as? String ?? old?.scopes |
| 192 | ) |
| 193 | try session.validate() |
| 194 | return session |
| 195 | } |
| 196 | } |