@capgo/capacitor-social-login 8.5.1 → 8.5.3

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.
Files changed (30) hide show
  1. package/README.md +78 -18
  2. package/android/src/main/java/ee/forgr/capacitor/social/login/OAuth2LoginActivity.java +7 -0
  3. package/android/src/main/java/ee/forgr/capacitor/social/login/SocialLoginPlugin.java +31 -1
  4. package/android/src/main/java/ee/forgr/capacitor/social/login/TelegramProvider.java +352 -0
  5. package/android/src/main/java/ee/forgr/capacitor/social/login/helpers/DependencyAvailabilityChecker.java +21 -1
  6. package/dist/docs.json +150 -8
  7. package/dist/esm/definitions.d.ts +87 -3
  8. package/dist/esm/definitions.js.map +1 -1
  9. package/dist/esm/facebook-provider.d.ts +3 -1
  10. package/dist/esm/facebook-provider.js +33 -0
  11. package/dist/esm/facebook-provider.js.map +1 -1
  12. package/dist/esm/oauth-popup-bridge.js +17 -7
  13. package/dist/esm/oauth-popup-bridge.js.map +1 -1
  14. package/dist/esm/oauth-popup-redirect.js +5 -0
  15. package/dist/esm/oauth-popup-redirect.js.map +1 -1
  16. package/dist/esm/social-login.d.ts +1 -1
  17. package/dist/esm/social-login.js.map +1 -1
  18. package/dist/esm/telegram-provider.d.ts +37 -0
  19. package/dist/esm/telegram-provider.js +292 -0
  20. package/dist/esm/telegram-provider.js.map +1 -0
  21. package/dist/esm/web.d.ts +2 -1
  22. package/dist/esm/web.js +23 -3
  23. package/dist/esm/web.js.map +1 -1
  24. package/dist/plugin.cjs.js +364 -10
  25. package/dist/plugin.cjs.js.map +1 -1
  26. package/dist/plugin.js +364 -10
  27. package/dist/plugin.js.map +1 -1
  28. package/ios/Sources/SocialLoginPlugin/SocialLoginPlugin.swift +67 -1
  29. package/ios/Sources/SocialLoginPlugin/TelegramProvider.swift +260 -0
  30. package/package.json +1 -1
@@ -16,7 +16,7 @@ import GoogleSignIn
16
16
  */
17
17
  @objc(SocialLoginPlugin)
18
18
  public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
19
- private let pluginVersion: String = "8.5.1"
19
+ private let pluginVersion: String = "8.5.3"
20
20
  public let identifier = "SocialLoginPlugin"
21
21
  public let jsName = "SocialLogin"
22
22
  private static let userCancelledCode = "USER_CANCELLED"
@@ -61,6 +61,7 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
61
61
 
62
62
  private let twitter = TwitterProvider()
63
63
  private let oauth2 = OAuth2Provider()
64
+ private let telegram = TelegramProvider()
64
65
  private var openSecureWindowCall: CAPPluginCall?
65
66
 
66
67
  // Helper to get Facebook provider (returns nil if unavailable)
@@ -129,6 +130,8 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
129
130
  case "twitter":
130
131
  // Check config first (for "fake disable")
131
132
  return isProviderEnabledInConfig("twitter")
133
+ case "telegram":
134
+ return isProviderEnabledInConfig("telegram")
132
135
  default:
133
136
  return false
134
137
  }
@@ -216,6 +219,19 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
216
219
  initialized = true
217
220
  }
218
221
 
222
+ if let telegramSettings = call.getObject("telegram") {
223
+ guard let botId = telegramSettings["botId"] as? String, !botId.isEmpty else {
224
+ call.reject("telegram.botId is required")
225
+ return
226
+ }
227
+ let requestAccess = telegramSettings["requestAccess"] as? String
228
+ let origin = telegramSettings["origin"] as? String
229
+ let redirectUrl = telegramSettings["redirectUrl"] as? String
230
+ let languageCode = telegramSettings["languageCode"] as? String
231
+ telegram.initialize(botId: botId, requestAccess: requestAccess, origin: origin, redirectUri: redirectUrl, languageCode: languageCode)
232
+ initialized = true
233
+ }
234
+
219
235
  if let oauth2Settings = call.getObject("oauth2"), !oauth2Settings.isEmpty {
220
236
  // oauth2Settings is now a dictionary of provider configs: { "github": {...}, "azure": {...} }
221
237
  var oauth2Configs: [String: [String: Any]] = [:]
@@ -319,6 +335,16 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
319
335
  }
320
336
  }
321
337
  }
338
+ case "telegram": do {
339
+ self.telegram.getAuthorizationCode { res in
340
+ switch res {
341
+ case .success:
342
+ call.reject("getAuthorizationCode is not available for Telegram.")
343
+ case .failure(let error):
344
+ call.reject(error.localizedDescription)
345
+ }
346
+ }
347
+ }
322
348
  case "oauth2": do {
323
349
  guard let providerId = call.getString("providerId") else {
324
350
  call.reject("providerId is required for oauth2 getAuthorizationCode")
@@ -401,6 +427,16 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
401
427
  }
402
428
  }
403
429
  }
430
+ case "telegram": do {
431
+ self.telegram.isLoggedIn { res in
432
+ switch res {
433
+ case .success(let status):
434
+ call.resolve([ "isLoggedIn": status ])
435
+ case .failure(let error):
436
+ call.reject(error.localizedDescription)
437
+ }
438
+ }
439
+ }
404
440
  case "oauth2": do {
405
441
  guard let providerId = call.getString("providerId") else {
406
442
  call.reject("providerId is required for oauth2 isLoggedIn")
@@ -456,6 +492,10 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
456
492
  twitter.login(payload: payload) { (result: Result<TwitterProfileResponse, Error>) in
457
493
  self.handleLoginResult(result, call: call)
458
494
  }
495
+ case "telegram":
496
+ telegram.login(payload: payload) { (result: Result<TelegramLoginResponse, Error>) in
497
+ self.handleLoginResult(result, call: call)
498
+ }
459
499
  case "oauth2":
460
500
  guard let providerId = payload["providerId"] as? String else {
461
501
  call.reject("providerId is required for oauth2 login")
@@ -554,6 +594,10 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
554
594
  twitter.logout { result in
555
595
  self.handleLogoutResult(result, call: call)
556
596
  }
597
+ case "telegram":
598
+ telegram.logout { result in
599
+ self.handleLogoutResult(result, call: call)
600
+ }
557
601
  case "oauth2":
558
602
  guard let providerId = call.getString("providerId") else {
559
603
  call.reject("providerId is required for oauth2 logout")
@@ -602,6 +646,10 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
602
646
  twitter.refresh { result in
603
647
  self.handleRefreshResult(result, call: call)
604
648
  }
649
+ case "telegram":
650
+ telegram.refresh { result in
651
+ self.handleRefreshResult(result, call: call)
652
+ }
605
653
  case "oauth2":
606
654
  guard let options = call.getObject("options"), let providerId = options["providerId"] as? String else {
607
655
  call.reject("providerId is required for oauth2 refresh")
@@ -952,6 +1000,24 @@ public class SocialLoginPlugin: CAPPlugin, CAPBridgedPlugin {
952
1000
  "provider": "twitter",
953
1001
  "result": twitterResult
954
1002
  ])
1003
+ } else if let telegramResponse = response as? TelegramLoginResponse {
1004
+ let profile: [String: Any] = [
1005
+ "id": telegramResponse.profile.id,
1006
+ "firstName": telegramResponse.profile.firstName,
1007
+ "lastName": telegramResponse.profile.lastName ?? NSNull(),
1008
+ "username": telegramResponse.profile.username ?? NSNull(),
1009
+ "photoUrl": telegramResponse.profile.photoUrl ?? NSNull()
1010
+ ]
1011
+ let telegramResult: [String: Any] = [
1012
+ "profile": profile,
1013
+ "authDate": telegramResponse.authDate,
1014
+ "hash": telegramResponse.hash,
1015
+ "requestAccess": telegramResponse.requestAccess
1016
+ ]
1017
+ call.resolve([
1018
+ "provider": "telegram",
1019
+ "result": telegramResult
1020
+ ])
955
1021
  } else if let oauth2Response = response as? OAuth2LoginResponse {
956
1022
  let accessToken: [String: Any] = [
957
1023
  "token": oauth2Response.accessToken.token,
@@ -0,0 +1,260 @@
1
+ import Foundation
2
+ import AuthenticationServices
3
+ import UIKit
4
+
5
+ struct TelegramProfile {
6
+ let id: String
7
+ let firstName: String
8
+ let lastName: String?
9
+ let username: String?
10
+ let photoUrl: String?
11
+ }
12
+
13
+ struct TelegramLoginResponse {
14
+ let profile: TelegramProfile
15
+ let authDate: Int
16
+ let hash: String
17
+ let requestAccess: String
18
+ }
19
+
20
+ private struct TelegramStoredSession: Codable {
21
+ let profile: TelegramProfileStored
22
+ let authDate: Int
23
+ let requestAccess: String
24
+ let expiresAt: Date
25
+ }
26
+
27
+ private struct TelegramProfileStored: Codable {
28
+ let id: String
29
+ let firstName: String
30
+ let lastName: String?
31
+ let username: String?
32
+ let photoUrl: String?
33
+ }
34
+
35
+ class TelegramProvider: NSObject {
36
+ private var botId: String?
37
+ private var requestAccess: String = "write"
38
+ private var origin: String?
39
+ private var redirectUri: String?
40
+ private var languageCode: String?
41
+ private var currentSession: ASWebAuthenticationSession?
42
+ private var pendingState: String?
43
+ private let storageKey = "CapgoTelegramSession"
44
+ private let sessionTtl: TimeInterval = 24 * 60 * 60 // 24h
45
+
46
+ func initialize(botId: String, requestAccess: String?, origin: String?, redirectUri: String?, languageCode: String?) {
47
+ self.botId = botId
48
+ self.requestAccess = requestAccess ?? "write"
49
+ self.origin = origin
50
+ self.redirectUri = redirectUri
51
+ self.languageCode = languageCode
52
+ }
53
+
54
+ func login(payload: [String: Any], completion: @escaping (Result<TelegramLoginResponse, Error>) -> Void) {
55
+ guard let botId = botId else {
56
+ completion(.failure(NSError(domain: "TelegramProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Telegram botId is not configured. Call initialize()."])))
57
+ return
58
+ }
59
+
60
+ guard let redirect = (payload["redirectUrl"] as? String) ?? redirectUri else {
61
+ completion(.failure(NSError(domain: "TelegramProvider", code: -2, userInfo: [NSLocalizedDescriptionKey: "telegram.redirectUrl is required."])))
62
+ return
63
+ }
64
+
65
+ let requestAccess = (payload["requestAccess"] as? String) ?? self.requestAccess
66
+ let state = (payload["state"] as? String) ?? UUID().uuidString
67
+ pendingState = state
68
+
69
+ let origin = self.origin ?? Self.deriveOrigin(from: redirect)
70
+ guard Self.isHttpOrigin(origin) else {
71
+ completion(.failure(NSError(domain: "TelegramProvider", code: -5, userInfo: [NSLocalizedDescriptionKey: "telegram.origin must be an http(s) domain registered with the bot when redirectUrl is not http(s)."])))
72
+ return
73
+ }
74
+ let returnTo = Self.appendState(to: redirect, state: state)
75
+
76
+ guard let authUrl = Self.buildAuthUrl(botId: botId, origin: origin, requestAccess: requestAccess, returnTo: returnTo, languageCode: languageCode) else {
77
+ completion(.failure(NSError(domain: "TelegramProvider", code: -3, userInfo: [NSLocalizedDescriptionKey: "Unable to build Telegram auth URL."])))
78
+ return
79
+ }
80
+
81
+ guard let callbackScheme = URL(string: redirect)?.scheme else {
82
+ completion(.failure(NSError(domain: "TelegramProvider", code: -4, userInfo: [NSLocalizedDescriptionKey: "Invalid redirect URL"])))
83
+ return
84
+ }
85
+
86
+ let session = ASWebAuthenticationSession(url: authUrl, callbackURLScheme: callbackScheme) { [weak self] callbackURL, error in
87
+ guard let self = self else { return }
88
+ self.currentSession = nil
89
+
90
+ if let error = error {
91
+ completion(.failure(error))
92
+ return
93
+ }
94
+
95
+ guard let callbackURL = callbackURL, let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false) else {
96
+ completion(.failure(NSError(domain: "TelegramProvider", code: -5, userInfo: [NSLocalizedDescriptionKey: "Invalid callback URL."])))
97
+ return
98
+ }
99
+
100
+ var payload: [String: String] = [:]
101
+ for item in components.queryItems ?? [] {
102
+ payload[item.name] = item.value ?? ""
103
+ }
104
+
105
+ let returnedState = payload["state"]
106
+ if returnedState != self.pendingState {
107
+ completion(.failure(NSError(domain: "TelegramProvider", code: -6, userInfo: [NSLocalizedDescriptionKey: "State mismatch detected during Telegram login."])))
108
+ return
109
+ }
110
+
111
+ if let errorCode = payload["error"], !errorCode.isEmpty {
112
+ let description = payload["error_description"] ?? errorCode
113
+ completion(.failure(NSError(domain: "TelegramProvider", code: -7, userInfo: [NSLocalizedDescriptionKey: description])))
114
+ return
115
+ }
116
+
117
+ guard let id = payload["id"], let authDateRaw = payload["auth_date"], let hash = payload["hash"] else {
118
+ completion(.failure(NSError(domain: "TelegramProvider", code: -8, userInfo: [NSLocalizedDescriptionKey: "Telegram login payload is incomplete."])))
119
+ return
120
+ }
121
+
122
+ guard let authDate = Int(authDateRaw) else {
123
+ completion(.failure(NSError(domain: "TelegramProvider", code: -9, userInfo: [NSLocalizedDescriptionKey: "Telegram auth_date is invalid."])))
124
+ return
125
+ }
126
+ let profile = TelegramProfile(
127
+ id: id,
128
+ firstName: payload["first_name"] ?? "",
129
+ lastName: payload["last_name"],
130
+ username: payload["username"],
131
+ photoUrl: payload["photo_url"]
132
+ )
133
+
134
+ let response = TelegramLoginResponse(
135
+ profile: profile,
136
+ authDate: authDate,
137
+ hash: hash,
138
+ requestAccess: requestAccess == "read" ? "read" : "write"
139
+ )
140
+
141
+ self.persistSession(response: response)
142
+ completion(.success(response))
143
+ }
144
+
145
+ session.presentationContextProvider = self
146
+ session.prefersEphemeralWebBrowserSession = true
147
+ currentSession = session
148
+ session.start()
149
+ }
150
+
151
+ func logout(completion: @escaping (Result<Void, Error>) -> Void) {
152
+ UserDefaults.standard.removeObject(forKey: storageKey)
153
+ completion(.success(()))
154
+ }
155
+
156
+ func isLoggedIn(completion: @escaping (Result<Bool, Error>) -> Void) {
157
+ guard let stored = loadSession() else {
158
+ completion(.success(false))
159
+ return
160
+ }
161
+ completion(.success(stored.expiresAt > Date()))
162
+ }
163
+
164
+ func refresh(completion: @escaping (Result<TelegramLoginResponse, Error>) -> Void) {
165
+ completion(.failure(NSError(domain: "TelegramProvider", code: -9, userInfo: [NSLocalizedDescriptionKey: "Telegram refresh is not supported. Call login() again."])))
166
+ }
167
+
168
+ func getAuthorizationCode(completion: @escaping (Result<TelegramLoginResponse, Error>) -> Void) {
169
+ completion(.failure(NSError(domain: "TelegramProvider", code: -10, userInfo: [NSLocalizedDescriptionKey: "getAuthorizationCode is not available for Telegram."])))
170
+ }
171
+
172
+ private func persistSession(response: TelegramLoginResponse) {
173
+ let stored = TelegramStoredSession(
174
+ profile: TelegramProfileStored(
175
+ id: response.profile.id,
176
+ firstName: response.profile.firstName,
177
+ lastName: response.profile.lastName,
178
+ username: response.profile.username,
179
+ photoUrl: response.profile.photoUrl
180
+ ),
181
+ authDate: response.authDate,
182
+ requestAccess: response.requestAccess,
183
+ expiresAt: Date(timeIntervalSince1970: TimeInterval(response.authDate)).addingTimeInterval(sessionTtl)
184
+ )
185
+ do {
186
+ let data = try JSONEncoder().encode(stored)
187
+ UserDefaults.standard.set(data, forKey: storageKey)
188
+ } catch {
189
+ print("TelegramProvider persistSession error: \(error.localizedDescription)")
190
+ }
191
+ }
192
+
193
+ private func loadSession() -> TelegramStoredSession? {
194
+ guard let data = UserDefaults.standard.data(forKey: storageKey) else {
195
+ return nil
196
+ }
197
+ do {
198
+ let session = try JSONDecoder().decode(TelegramStoredSession.self, from: data)
199
+ return session
200
+ } catch {
201
+ print("TelegramProvider loadSession error: \(error.localizedDescription)")
202
+ return nil
203
+ }
204
+ }
205
+
206
+ private static func isHttpOrigin(_ value: String) -> Bool {
207
+ guard let url = URL(string: value), let scheme = url.scheme?.lowercased() else {
208
+ return false
209
+ }
210
+ return scheme == "https" || scheme == "http"
211
+ }
212
+
213
+ private static func deriveOrigin(from redirect: String) -> String {
214
+ if let url = URL(string: redirect), let host = url.host, let scheme = url.scheme {
215
+ if let port = url.port {
216
+ return "\(scheme)://\(host):\(port)"
217
+ }
218
+ return "\(scheme)://\(host)"
219
+ }
220
+ return redirect
221
+ }
222
+
223
+ private static func appendState(to redirect: String, state: String) -> String {
224
+ guard var components = URLComponents(string: redirect) else {
225
+ return redirect
226
+ }
227
+ var queryItems = (components.queryItems ?? []).filter { $0.name != "state" }
228
+ queryItems.append(URLQueryItem(name: "state", value: state))
229
+ components.queryItems = queryItems
230
+ return components.url?.absoluteString ?? redirect
231
+ }
232
+
233
+ private static func buildAuthUrl(botId: String, origin: String, requestAccess: String, returnTo: String, languageCode: String?) -> URL? {
234
+ var components = URLComponents(string: "https://oauth.telegram.org/auth")
235
+ var items: [URLQueryItem] = [
236
+ URLQueryItem(name: "bot_id", value: botId),
237
+ URLQueryItem(name: "origin", value: origin),
238
+ URLQueryItem(name: "request_access", value: requestAccess),
239
+ URLQueryItem(name: "return_to", value: returnTo),
240
+ URLQueryItem(name: "embed", value: "1"),
241
+ URLQueryItem(name: "mobile", value: "1")
242
+ ]
243
+ if let languageCode = languageCode, !languageCode.isEmpty {
244
+ items.append(URLQueryItem(name: "lang", value: languageCode))
245
+ }
246
+ components?.queryItems = items
247
+ return components?.url
248
+ }
249
+ }
250
+
251
+ extension TelegramProvider: ASWebAuthenticationPresentationContextProviding {
252
+ func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
253
+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
254
+ let active = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
255
+ if let window = active?.windows.first(where: { $0.isKeyWindow }) ?? active?.windows.first {
256
+ return window
257
+ }
258
+ return ASPresentationAnchor()
259
+ }
260
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-social-login",
3
- "version": "8.5.1",
3
+ "version": "8.5.3",
4
4
  "description": "All social logins in one plugin",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",