@capgo/capacitor-social-login 8.7.5 → 8.7.6

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/README.md CHANGED
@@ -425,7 +425,7 @@ await SocialLogin.initialize({
425
425
  - `iOSClientId`: Required for iOS platform
426
426
  - `iOSServerClientId`: Required when using `mode: 'offline'` on iOS or when you need to verify the token on the server (should be the same value as `webClientId`)
427
427
  - `mode: 'offline'`: Returns only `serverAuthCode` for backend authentication, no user profile data, and `refresh()` is not available in-app. Exchange `serverAuthCode` on your backend and refresh there.
428
- - `mode: 'online'`: Returns user profile data and access tokens (default)
428
+ - `mode: 'online'`: Returns user profile data and access tokens (default). On Android, default online login still runs `AuthorizationClient` and returns an `accessToken` when Google provides one. Set `skipAuthOnlyAuthorizationAfterSignIn: true` in `initialize()` if authorize hangs on stock `BridgeActivity`, or if login rejects because authorization needs user interaction that stock `BridgeActivity` cannot route (then `accessToken` may be `null`; use `idToken` for auth).
429
429
 
430
430
  ### Android configuration
431
431
 
@@ -440,13 +440,39 @@ await SocialLogin.initialize({
440
440
  },
441
441
  });
442
442
  const res = await SocialLogin.login({
443
+ provider: 'google',
444
+ options: {},
445
+ });
446
+ ```
447
+
448
+ Optional hang workaround on stock `BridgeActivity` (skips authorize; `accessToken` may be `null`):
449
+
450
+ ```typescript
451
+ await SocialLogin.initialize({
452
+ google: {
453
+ webClientId: 'your-web-client-id',
454
+ skipAuthOnlyAuthorizationAfterSignIn: true,
455
+ },
456
+ });
457
+ ```
458
+
459
+ **Custom Google API scopes on Android** require a modified `MainActivity` that implements `ModifiedMainActivityForSocialLoginPlugin` and forwards `onActivityResult` to the plugin (see [example-app/android/.../MainActivity.java](example-app/android/app/src/main/java/app/capgo/plugin/SocialLogin/MainActivity.java)). On a stock `BridgeActivity`, do not pass a `scopes` array to `login()`; even `['email', 'profile']` is rejected because those scopes are already included by default.
460
+
461
+ ```typescript
462
+ // Only after MainActivity implements ModifiedMainActivityForSocialLoginPlugin:
463
+ const resWithScopes = await SocialLogin.login({
443
464
  provider: 'google',
444
465
  options: {
445
- scopes: ['email', 'profile'],
466
+ scopes: ['https://www.googleapis.com/auth/drive.readonly'],
446
467
  },
447
468
  });
448
469
  ```
449
470
 
471
+ ```typescript
472
+ // Misleading on stock BridgeActivity (will reject at runtime):
473
+ // await SocialLogin.login({ provider: 'google', options: { scopes: ['email', 'profile'] } });
474
+ ```
475
+
450
476
  #### Android troubleshooting (Credential Manager, SHA-1, and Firebase)
451
477
 
452
478
  On Android this plugin uses **Google Credential Manager** (`androidx.credentials` + Sign in with Google), not the legacy `GoogleSignInClient` API. Logcat errors such as `GetCredentialCustomException: [28444] Developer console is not set up correctly` come from that stack.
@@ -1114,7 +1140,33 @@ Get the current authorization code
1114
1140
  refresh(options: LoginOptions) => Promise<void>
1115
1141
  ```
1116
1142
 
1117
- Refresh the access token
1143
+ Refresh the access token for the logged-in provider.
1144
+
1145
+ **Google Android refresh behavior:**
1146
+ On Android, when the saved ID token is still valid and either no access token is stored or Google access
1147
+ token validation succeeds within the timeout, `refresh()` resolves without updating either token. That
1148
+ early return applies regardless of `skipAuthOnlyAuthorizationAfterSignIn`.
1149
+ If validation fails or times out, `refresh()` continues even when a token remains stored; with
1150
+ `skipAuthOnlyAuthorizationAfterSignIn: true` and default OIDC scopes, a successful credential refresh
1151
+ then clears that access token without obtaining a new one.
1152
+
1153
+ **Google Offline Mode Limitation:**
1154
+ This method is NOT supported when Google is initialized with `mode: 'offline'`.
1155
+ Offline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.
1156
+ The plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,
1157
+ refresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.
1158
+
1159
+ **Google Android `skipAuthOnlyAuthorizationAfterSignIn`:**
1160
+ When initialize sets `google.skipAuthOnlyAuthorizationAfterSignIn: true` and only default OIDC scopes are
1161
+ requested, a refresh that runs past the early return skips `AuthorizationClient.authorize()`, updates the
1162
+ saved `idToken`, and clears any saved access token; no new access token is obtained. Enabling the option
1163
+ does not clear a stored access token while the early return applies (validation succeeded or no token
1164
+ stored). With default `false`, refresh still skips authorize on the early return when no access token is
1165
+ stored but the ID token is valid.
1166
+
1167
+ **Google Web Limitation:**
1168
+ On Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.
1169
+ Call `login()` again on Web to obtain a fresh token instead.
1118
1170
 
1119
1171
  | Param | Type |
1120
1172
  | ------------- | ----------------------------------------------------- |
@@ -1393,16 +1445,16 @@ On user cancel or dismiss, the Promise rejects with `code === 'USER_CANCELLED'`.
1393
1445
 
1394
1446
  #### InitializeOptions
1395
1447
 
1396
- | Prop | Type | Description |
1397
- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
1398
- | **`oauth2`** | <code><a href="#record">Record</a>&lt;string, <a href="#oauth2providerconfig">OAuth2ProviderConfig</a>&gt;</code> | OAuth2 provider configurations. Supports multiple providers by using a <a href="#record">Record</a> with provider IDs as keys. |
1399
- | **`telegram`** | <code>{ botId: string; redirectUrl?: string; origin?: string; requestAccess?: 'read' \| 'write'; languageCode?: string; }</code> | Telegram Login Widget configuration. Uses Telegram's OAuth widget (`oauth.telegram.org`), not standard OAuth2. |
1400
- | **`linkedin`** | <code><a href="#linkedinproviderconfig">LinkedInProviderConfig</a></code> | LinkedIn configuration. Convenience wrapper that maps to the OAuth2 provider using LinkedIn defaults. |
1401
- | **`tiktok`** | <code><a href="#tiktokproviderconfig">TikTokProviderConfig</a></code> | TikTok Login Kit configuration. Convenience wrapper that maps to the OAuth2 provider using TikTok defaults (`client_key`). |
1402
- | **`twitter`** | <code>{ clientId: string; redirectUrl: string; defaultScopes?: string[]; forceLogin?: boolean; audience?: string; }</code> | |
1403
- | **`facebook`** | <code>{ appId: string; clientToken?: string; locale?: string; }</code> | |
1404
- | **`google`** | <code>{ iOSClientId?: string; iOSServerClientId?: string; webClientId?: string; mode?: 'online' \| 'offline'; hostedDomain?: string; redirectUrl?: string; }</code> | |
1405
- | **`apple`** | <code>{ clientId?: string; redirectUrl?: string; useProperTokenExchange?: boolean; useBroadcastChannel?: boolean; }</code> | |
1448
+ | Prop | Type | Description |
1449
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
1450
+ | **`oauth2`** | <code><a href="#record">Record</a>&lt;string, <a href="#oauth2providerconfig">OAuth2ProviderConfig</a>&gt;</code> | OAuth2 provider configurations. Supports multiple providers by using a <a href="#record">Record</a> with provider IDs as keys. |
1451
+ | **`telegram`** | <code>{ botId: string; redirectUrl?: string; origin?: string; requestAccess?: 'read' \| 'write'; languageCode?: string; }</code> | Telegram Login Widget configuration. Uses Telegram's OAuth widget (`oauth.telegram.org`), not standard OAuth2. |
1452
+ | **`linkedin`** | <code><a href="#linkedinproviderconfig">LinkedInProviderConfig</a></code> | LinkedIn configuration. Convenience wrapper that maps to the OAuth2 provider using LinkedIn defaults. |
1453
+ | **`tiktok`** | <code><a href="#tiktokproviderconfig">TikTokProviderConfig</a></code> | TikTok Login Kit configuration. Convenience wrapper that maps to the OAuth2 provider using TikTok defaults (`client_key`). |
1454
+ | **`twitter`** | <code>{ clientId: string; redirectUrl: string; defaultScopes?: string[]; forceLogin?: boolean; audience?: string; }</code> | |
1455
+ | **`facebook`** | <code>{ appId: string; clientToken?: string; locale?: string; }</code> | |
1456
+ | **`google`** | <code>{ iOSClientId?: string; iOSServerClientId?: string; webClientId?: string; mode?: 'online' \| 'offline'; hostedDomain?: string; redirectUrl?: string; skipAuthOnlyAuthorizationAfterSignIn?: boolean; }</code> | |
1457
+ | **`apple`** | <code>{ clientId?: string; redirectUrl?: string; useProperTokenExchange?: boolean; useBroadcastChannel?: boolean; }</code> | |
1406
1458
 
1407
1459
 
1408
1460
  #### OAuth2ProviderConfig
@@ -1504,12 +1556,12 @@ Uses TikTok OAuth 2.0 endpoints and `client_key` instead of `client_id`.
1504
1556
 
1505
1557
  #### GoogleLoginResponseOnline
1506
1558
 
1507
- | Prop | Type | Description |
1508
- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1509
- | **`accessToken`** | <code><a href="#accesstoken">AccessToken</a> \| null</code> | OAuth access token for Google APIs. May be `null` on Android when Credential Manager authentication succeeds but AuthorizationClient does not return an access token (authentication-only / ID-token login with default OIDC scopes). Use `idToken` for user authentication; request additional Google API scopes when an access token is required. |
1510
- | **`idToken`** | <code>string \| null</code> | OpenID Connect ID token (JWT). Includes an `email_verified` claim when the `email` scope is granted. Use `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but always verify the token signature, `iss`, `aud`, and `exp` on your backend before trusting `email_verified` for account linking. |
1511
- | **`profile`** | <code>{ email: string \| null; familyName: string \| null; givenName: string \| null; id: string \| null; name: string \| null; imageUrl: string \| null; }</code> | |
1512
- | **`responseType`** | <code>'online'</code> | |
1559
+ | Prop | Type | Description |
1560
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1561
+ | **`accessToken`** | <code><a href="#accesstoken">AccessToken</a> \| null</code> | OAuth access token for Google APIs. May be `null` on Android when AuthorizationClient does not return an access token, or when `skipAuthOnlyAuthorizationAfterSignIn` is enabled during initialize (opt-in). Use `idToken` for user authentication; request additional Google API scopes when an access token is required. |
1562
+ | **`idToken`** | <code>string \| null</code> | OpenID Connect ID token (JWT). Includes an `email_verified` claim when the `email` scope is granted. Use `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but always verify the token signature, `iss`, `aud`, and `exp` on your backend before trusting `email_verified` for account linking. |
1563
+ | **`profile`** | <code>{ email: string \| null; familyName: string \| null; givenName: string \| null; id: string \| null; name: string \| null; imageUrl: string \| null; }</code> | |
1564
+ | **`responseType`** | <code>'online'</code> | |
1513
1565
 
1514
1566
 
1515
1567
  #### GoogleLoginResponseOffline
@@ -0,0 +1,80 @@
1
+ package ee.forgr.capacitor.social.login;
2
+
3
+ import android.app.Activity;
4
+
5
+ /**
6
+ * Pure decision helpers for Google AuthorizationClient usage after Credential Manager sign-in.
7
+ */
8
+ public final class GoogleAuthorizationDecision {
9
+
10
+ public static final long AUTHORIZATION_WAIT_SECONDS = 60L;
11
+
12
+ public static final long AUTHORIZATION_CONSENT_WAIT_SECONDS = 600L;
13
+
14
+ public static final String UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE =
15
+ "Google authorization requires user interaction, but the host Activity does not implement ModifiedMainActivityForSocialLoginPlugin and forward onActivityResult. For authentication-only scopes in online mode, set google.skipAuthOnlyAuthorizationAfterSignIn to true. For custom scopes or offline mode, update MainActivity as documented in the README.";
16
+
17
+ public static final String AUTHORIZATION_WAIT_TIMEOUT_MESSAGE =
18
+ "Timed out waiting for Google authorization after " + AUTHORIZATION_WAIT_SECONDS + " seconds";
19
+
20
+ public static final String AUTHORIZATION_CONSENT_WAIT_TIMEOUT_MESSAGE =
21
+ "Timed out waiting for Google authorization consent after " + AUTHORIZATION_CONSENT_WAIT_SECONDS + " seconds";
22
+
23
+ private GoogleAuthorizationDecision() {}
24
+
25
+ /**
26
+ * Authentication-only (OIDC) scopes that Credential Manager already covers via the ID token.
27
+ * AuthorizationClient is only needed when requesting additional Google API scopes.
28
+ */
29
+ public static boolean isAuthenticationOnlyScopes(String[] scopes) {
30
+ if (scopes == null || scopes.length == 0) {
31
+ return true;
32
+ }
33
+ for (String scope : scopes) {
34
+ if (scope == null || scope.isEmpty()) {
35
+ continue;
36
+ }
37
+ boolean isDefault =
38
+ scope.equals("openid") ||
39
+ scope.equals("https://www.googleapis.com/auth/userinfo.email") ||
40
+ scope.equals("https://www.googleapis.com/auth/userinfo.profile") ||
41
+ scope.equals("email") ||
42
+ scope.equals("profile");
43
+ if (!isDefault) {
44
+ return false;
45
+ }
46
+ }
47
+ return true;
48
+ }
49
+
50
+ /**
51
+ * Skip AuthorizationClient when online login already has an ID token and only default OIDC scopes are requested.
52
+ * Requires {@code skipAuthOnlyAuthorizationAfterSignIn} (opt-in, default false). Offline mode still needs authorize() for serverAuthCode.
53
+ */
54
+ public static boolean shouldSkipAuthorizationAfterCredentialSignIn(
55
+ GoogleProvider.GoogleProviderLoginType mode,
56
+ String[] scopes,
57
+ boolean skipAuthOnlyAuthorizationAfterSignIn
58
+ ) {
59
+ return (
60
+ skipAuthOnlyAuthorizationAfterSignIn &&
61
+ mode == GoogleProvider.GoogleProviderLoginType.ONLINE &&
62
+ isAuthenticationOnlyScopes(scopes)
63
+ );
64
+ }
65
+
66
+ public static boolean canRouteAuthorizationResolution(Activity activity) {
67
+ return activity instanceof ModifiedMainActivityForSocialLoginPlugin;
68
+ }
69
+
70
+ public static boolean isUnroutableAuthorizationResolutionFailure(Throwable error) {
71
+ Throwable current = error;
72
+ while (current != null) {
73
+ if (UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE.equals(current.getMessage())) {
74
+ return true;
75
+ }
76
+ current = current.getCause();
77
+ }
78
+ return false;
79
+ }
80
+ }
@@ -1,5 +1,6 @@
1
1
  package ee.forgr.capacitor.social.login;
2
2
 
3
+ import android.accounts.Account;
3
4
  import android.app.Activity;
4
5
  import android.app.PendingIntent;
5
6
  import android.content.Context;
@@ -46,10 +47,13 @@ import java.util.HashSet;
46
47
  import java.util.List;
47
48
  import java.util.Objects;
48
49
  import java.util.Set;
50
+ import java.util.concurrent.ExecutionException;
49
51
  import java.util.concurrent.Executor;
50
52
  import java.util.concurrent.ExecutorService;
51
53
  import java.util.concurrent.Executors;
52
54
  import java.util.concurrent.TimeUnit;
55
+ import java.util.concurrent.TimeoutException;
56
+ import java.util.concurrent.atomic.AtomicBoolean;
53
57
  import org.json.JSONArray;
54
58
  import org.json.JSONException;
55
59
  import org.json.JSONObject;
@@ -85,7 +89,33 @@ public class GoogleProvider implements SocialProvider {
85
89
  private String idToken = null;
86
90
  private String accessToken = null;
87
91
  private GoogleProviderLoginType mode = GoogleProviderLoginType.ONLINE;
92
+ private boolean skipAuthOnlyAuthorizationAfterSignIn = false;
88
93
  private String hostedDomain = null;
94
+ private Integer pendingAuthorizationSlotIndex = null;
95
+
96
+ private static final class AuthorizationWaitContext {
97
+
98
+ private final AtomicBoolean finished = new AtomicBoolean(false);
99
+ private final AtomicBoolean consentUiLaunched = new AtomicBoolean(false);
100
+ private final int[] slotIndex = new int[] { -1 };
101
+ private CallbackToFutureAdapter.Completer<AuthorizationResult> slotCompleter = null;
102
+
103
+ private void markFinished() {
104
+ finished.set(true);
105
+ }
106
+
107
+ private boolean isFinished() {
108
+ return finished.get();
109
+ }
110
+
111
+ private void markConsentUiLaunched() {
112
+ consentUiLaunched.set(true);
113
+ }
114
+
115
+ private boolean isConsentUiLaunched() {
116
+ return consentUiLaunched.get();
117
+ }
118
+ }
89
119
 
90
120
  private static String maskClientId(String clientId) {
91
121
  if (clientId == null || clientId.isEmpty()) {
@@ -171,9 +201,19 @@ public class GoogleProvider implements SocialProvider {
171
201
  }
172
202
 
173
203
  public void initialize(String clientId, GoogleProviderLoginType mode, String hostedDomain) {
204
+ initialize(clientId, mode, hostedDomain, false);
205
+ }
206
+
207
+ public void initialize(
208
+ String clientId,
209
+ GoogleProviderLoginType mode,
210
+ String hostedDomain,
211
+ boolean skipAuthOnlyAuthorizationAfterSignIn
212
+ ) {
174
213
  this.credentialManager = CredentialManager.create(activity);
175
214
  this.clientId = clientId;
176
215
  this.mode = mode;
216
+ this.skipAuthOnlyAuthorizationAfterSignIn = skipAuthOnlyAuthorizationAfterSignIn;
177
217
  this.hostedDomain = hostedDomain;
178
218
  logGoogleCloudDiagnostics("initialize");
179
219
 
@@ -186,8 +226,16 @@ public class GoogleProvider implements SocialProvider {
186
226
  try {
187
227
  JSONObject object = new JSONObject(data);
188
228
  GoogleProvider.this.idToken = object.optString("idToken", null);
189
- String restoredAccessToken = object.optString("accessToken", null);
190
- GoogleProvider.this.accessToken = restoredAccessToken != null && !restoredAccessToken.isEmpty() ? restoredAccessToken : null;
229
+ if (!object.has("accessToken") || object.isNull("accessToken")) {
230
+ GoogleProvider.this.accessToken = null;
231
+ } else {
232
+ String restoredAccessToken = object.optString("accessToken", null);
233
+ if (restoredAccessToken == null || restoredAccessToken.isEmpty() || "null".equals(restoredAccessToken)) {
234
+ GoogleProvider.this.accessToken = null;
235
+ } else {
236
+ GoogleProvider.this.accessToken = restoredAccessToken;
237
+ }
238
+ }
191
239
  JSONArray storedScopes = object.optJSONArray("scopes");
192
240
  if (storedScopes != null && storedScopes.length() > 0) {
193
241
  List<String> scopesList = new ArrayList<>(storedScopes.length());
@@ -216,31 +264,6 @@ public class GoogleProvider implements SocialProvider {
216
264
  }
217
265
  }
218
266
 
219
- /**
220
- * Authentication-only (OIDC) scopes that Credential Manager already covers via the ID token.
221
- * AuthorizationClient is only needed when requesting additional Google API scopes.
222
- */
223
- private static boolean isAuthenticationOnlyScopes(String[] scopes) {
224
- if (scopes == null || scopes.length == 0) {
225
- return true;
226
- }
227
- for (String scope : scopes) {
228
- if (scope == null || scope.isEmpty()) {
229
- continue;
230
- }
231
- boolean isDefault =
232
- scope.equals("openid") ||
233
- scope.equals("https://www.googleapis.com/auth/userinfo.email") ||
234
- scope.equals("https://www.googleapis.com/auth/userinfo.profile") ||
235
- scope.equals("email") ||
236
- scope.equals("profile");
237
- if (!isDefault) {
238
- return false;
239
- }
240
- }
241
- return true;
242
- }
243
-
244
267
  private void resolveOnlineLogin(
245
268
  PluginCall call,
246
269
  JSObject response,
@@ -579,7 +602,56 @@ public class GoogleProvider implements SocialProvider {
579
602
  .apply();
580
603
  }
581
604
 
582
- private ListenableFuture<AuthorizationResult> getAuthorizationResult(Boolean forceRefreshToken) {
605
+ private void clearAuthorizationSlot(int index, CallbackToFutureAdapter.Completer<AuthorizationResult> expectedCompleter) {
606
+ if (index < 0) {
607
+ return;
608
+ }
609
+ synchronized (this) {
610
+ if (index < futuresList.size()) {
611
+ CallbackToFutureAdapter.Completer<AuthorizationResult> current = futuresList.get(index);
612
+ if (expectedCompleter != null && current != expectedCompleter) {
613
+ return;
614
+ }
615
+ futuresList.set(index, null);
616
+ }
617
+ if (Objects.equals(pendingAuthorizationSlotIndex, index)) {
618
+ pendingAuthorizationSlotIndex = null;
619
+ }
620
+ }
621
+ }
622
+
623
+ private void finishWaitAndClearSlot(AuthorizationWaitContext waitContext) {
624
+ synchronized (this) {
625
+ waitContext.markFinished();
626
+ clearAuthorizationSlot(waitContext.slotIndex[0], waitContext.slotCompleter);
627
+ }
628
+ }
629
+
630
+ private AuthorizationResult awaitAuthorizationResult(ListenableFuture<AuthorizationResult> future, AuthorizationWaitContext waitContext)
631
+ throws ExecutionException, InterruptedException, TimeoutException {
632
+ long preLaunchDeadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(GoogleAuthorizationDecision.AUTHORIZATION_WAIT_SECONDS);
633
+ while (true) {
634
+ if (waitContext.isConsentUiLaunched()) {
635
+ return future.get(GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_SECONDS, TimeUnit.SECONDS);
636
+ }
637
+ long remainingNanos = preLaunchDeadlineNanos - System.nanoTime();
638
+ if (remainingNanos <= 0) {
639
+ throw new TimeoutException(GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE);
640
+ }
641
+ long pollNanos = Math.min(remainingNanos, TimeUnit.SECONDS.toNanos(1));
642
+ try {
643
+ return future.get(pollNanos, TimeUnit.NANOSECONDS);
644
+ } catch (TimeoutException ignored) {
645
+ // Poll until authorize completes, consent UI launches, or pre-launch deadline.
646
+ }
647
+ }
648
+ }
649
+
650
+ private ListenableFuture<AuthorizationResult> getAuthorizationResult(
651
+ Boolean forceRefreshToken,
652
+ String googleAccountId,
653
+ AuthorizationWaitContext waitContext
654
+ ) {
583
655
  // Account account = new Account(credential.getId(), "com.google");
584
656
  // String scopesString = "oauth2:" + TextUtils.join(" ", this.scopes);
585
657
  // String token = GoogleAuthUtil.getToken(
@@ -605,7 +677,9 @@ public class GoogleProvider implements SocialProvider {
605
677
  scopes.add(new Scope(scope));
606
678
  }
607
679
  AuthorizationRequest.Builder authorizationRequestBuilder = AuthorizationRequest.builder().setRequestedScopes(scopes);
608
- // .requestOfflineAccess(this.clientId)
680
+ if (googleAccountId != null && !googleAccountId.isEmpty()) {
681
+ authorizationRequestBuilder.setAccount(new Account(googleAccountId, "com.google"));
682
+ }
609
683
 
610
684
  if (GoogleProvider.this.mode == GoogleProviderLoginType.OFFLINE) {
611
685
  authorizationRequestBuilder = authorizationRequestBuilder.requestOfflineAccess(this.clientId, forceRefreshToken);
@@ -616,6 +690,9 @@ public class GoogleProvider implements SocialProvider {
616
690
  Identity.getAuthorizationClient(context)
617
691
  .authorize(authorizationRequest)
618
692
  .addOnSuccessListener((authorizationResult) -> {
693
+ if (waitContext.isFinished()) {
694
+ return;
695
+ }
619
696
  if (authorizationResult.hasResolution()) {
620
697
  // Access needs to be granted by the user
621
698
  PendingIntent pendingIntent = authorizationResult.getPendingIntent();
@@ -625,38 +702,68 @@ public class GoogleProvider implements SocialProvider {
625
702
  return;
626
703
  }
627
704
 
628
- // Find an index to put the future into.
629
- int fututeIndex = -1;
630
- for (int i = 0; i < futuresList.size(); i++) {
631
- if (futuresList.get(i) == null) {
632
- fututeIndex = i;
633
- break;
634
- }
635
- }
636
-
637
- if (fututeIndex == -1) {
638
- completer.setException(new RuntimeException("Cannot find index for future"));
639
- Log.e(LOG_TAG, "Cannot find index for future. Too many login requests??");
705
+ if (!GoogleAuthorizationDecision.canRouteAuthorizationResolution(activity)) {
706
+ Log.e(LOG_TAG, "AuthorizationClient returned a resolution, but MainActivity cannot route onActivityResult");
707
+ completer.setException(
708
+ new RuntimeException(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE)
709
+ );
640
710
  return;
641
711
  }
642
712
 
643
- futuresList.set(fututeIndex, completer);
713
+ synchronized (GoogleProvider.this) {
714
+ if (waitContext.isFinished()) {
715
+ return;
716
+ }
644
717
 
645
- try {
646
- activity.startIntentSenderForResult(
647
- pendingIntent.getIntentSender(),
648
- GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN + fututeIndex,
649
- null,
650
- 0,
651
- 0,
652
- 0,
653
- null
654
- );
655
- } catch (IntentSender.SendIntentException e) {
656
- Log.e(LOG_TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
657
- completer.setException(e);
718
+ int fututeIndex = -1;
719
+ for (int i = 0; i < futuresList.size(); i++) {
720
+ if (futuresList.get(i) == null) {
721
+ fututeIndex = i;
722
+ break;
723
+ }
724
+ }
725
+
726
+ if (fututeIndex == -1) {
727
+ completer.setException(new RuntimeException("Cannot find index for future"));
728
+ Log.e(LOG_TAG, "Cannot find index for future. Too many login requests??");
729
+ return;
730
+ }
731
+
732
+ futuresList.set(fututeIndex, completer);
733
+ waitContext.slotIndex[0] = fututeIndex;
734
+ waitContext.slotCompleter = completer;
735
+ pendingAuthorizationSlotIndex = fututeIndex;
736
+
737
+ if (waitContext.isFinished()) {
738
+ clearAuthorizationSlot(fututeIndex, completer);
739
+ waitContext.slotIndex[0] = -1;
740
+ waitContext.slotCompleter = null;
741
+ return;
742
+ }
743
+
744
+ try {
745
+ activity.startIntentSenderForResult(
746
+ pendingIntent.getIntentSender(),
747
+ GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN + fututeIndex,
748
+ null,
749
+ 0,
750
+ 0,
751
+ 0,
752
+ null
753
+ );
754
+ waitContext.markConsentUiLaunched();
755
+ } catch (IntentSender.SendIntentException e) {
756
+ Log.e(LOG_TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
757
+ clearAuthorizationSlot(fututeIndex, completer);
758
+ waitContext.slotIndex[0] = -1;
759
+ waitContext.slotCompleter = null;
760
+ completer.setException(e);
761
+ }
658
762
  }
659
763
  } else {
764
+ if (waitContext.isFinished()) {
765
+ return;
766
+ }
660
767
  // Access already granted, continue with user action.
661
768
  // Online mode: a null access token is allowed (ID-token auth still succeeds).
662
769
  // Offline mode still requires serverAuthCode.
@@ -673,6 +780,9 @@ public class GoogleProvider implements SocialProvider {
673
780
  }
674
781
  })
675
782
  .addOnFailureListener((e) -> {
783
+ if (waitContext.isFinished()) {
784
+ return;
785
+ }
676
786
  completer.setException(new RuntimeException("Failed to authorize"));
677
787
  Log.e(LOG_TAG, "Failed to authorize", e);
678
788
  });
@@ -703,8 +813,25 @@ public class GoogleProvider implements SocialProvider {
703
813
 
704
814
  GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.getData());
705
815
  String idToken = googleIdTokenCredential.getIdToken();
816
+ String googleAccountId = googleIdTokenCredential.getId();
817
+
818
+ if (
819
+ GoogleAuthorizationDecision.shouldSkipAuthorizationAfterCredentialSignIn(
820
+ GoogleProvider.this.mode,
821
+ GoogleProvider.this.scopes,
822
+ GoogleProvider.this.skipAuthOnlyAuthorizationAfterSignIn
823
+ )
824
+ ) {
825
+ resolveOnlineLogin(call, response, resultObj, user, idToken, null);
826
+ return;
827
+ }
706
828
 
707
- ListenableFuture<AuthorizationResult> future = getAuthorizationResult(forceRefreshToken);
829
+ AuthorizationWaitContext authorizationWaitContext = new AuthorizationWaitContext();
830
+ ListenableFuture<AuthorizationResult> future = getAuthorizationResult(
831
+ forceRefreshToken,
832
+ googleAccountId,
833
+ authorizationWaitContext
834
+ );
708
835
 
709
836
  // Use ExecutorService to retrieve the access token
710
837
  ExecutorService executor = Executors.newSingleThreadExecutor();
@@ -714,7 +841,7 @@ public class GoogleProvider implements SocialProvider {
714
841
  @Override
715
842
  public void run() {
716
843
  try {
717
- AuthorizationResult authResult = future.get();
844
+ AuthorizationResult authResult = awaitAuthorizationResult(future, authorizationWaitContext);
718
845
  if (GoogleProvider.this.mode == GoogleProviderLoginType.ONLINE) {
719
846
  // accessToken may be null: Credential Manager auth still succeeded.
720
847
  resolveOnlineLogin(call, response, resultObj, user, idToken, authResult.getAccessToken());
@@ -728,13 +855,24 @@ public class GoogleProvider implements SocialProvider {
728
855
  call.reject("Failed to get serverAuthCode");
729
856
  }
730
857
  }
858
+ } catch (TimeoutException e) {
859
+ finishWaitAndClearSlot(authorizationWaitContext);
860
+ String timeoutMessage = authorizationWaitContext.isConsentUiLaunched()
861
+ ? GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_TIMEOUT_MESSAGE
862
+ : GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE;
863
+ call.reject(timeoutMessage);
731
864
  } catch (Exception e) {
865
+ finishWaitAndClearSlot(authorizationWaitContext);
866
+ if (GoogleAuthorizationDecision.isUnroutableAuthorizationResolutionFailure(e)) {
867
+ call.reject(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE);
868
+ return;
869
+ }
732
870
  // AuthorizationClient failed after Credential Manager returned a valid ID token.
733
871
  // For authentication-only online scopes, resolve with idToken + profile.
734
872
  if (
735
873
  GoogleProvider.this.mode == GoogleProviderLoginType.ONLINE &&
736
874
  idToken != null &&
737
- isAuthenticationOnlyScopes(GoogleProvider.this.scopes)
875
+ GoogleAuthorizationDecision.isAuthenticationOnlyScopes(GoogleProvider.this.scopes)
738
876
  ) {
739
877
  Log.w(
740
878
  LOG_TAG,
@@ -765,21 +903,28 @@ public class GoogleProvider implements SocialProvider {
765
903
 
766
904
  public void handleAuthorizationIntent(int requestCode, Intent data) {
767
905
  int futureIndex = requestCode - GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN;
768
- if (futureIndex < 0 || futureIndex >= futuresList.size()) {
769
- Log.e(
770
- LOG_TAG,
771
- String.format(
772
- "Invalid future index. REQUEST_AUTHORIZE_GOOGLE_MIN: %d, requestCode: %d, futures list length: %d, futureIndex: %d",
773
- REQUEST_AUTHORIZE_GOOGLE_MIN,
774
- requestCode,
775
- futuresList.size(),
776
- futureIndex
777
- )
778
- );
779
- return;
780
- }
906
+ CallbackToFutureAdapter.Completer<AuthorizationResult> future;
907
+ synchronized (this) {
908
+ if (futureIndex < 0 || futureIndex >= futuresList.size()) {
909
+ Log.e(
910
+ LOG_TAG,
911
+ String.format(
912
+ "Invalid future index. REQUEST_AUTHORIZE_GOOGLE_MIN: %d, requestCode: %d, futures list length: %d, futureIndex: %d",
913
+ REQUEST_AUTHORIZE_GOOGLE_MIN,
914
+ requestCode,
915
+ futuresList.size(),
916
+ futureIndex
917
+ )
918
+ );
919
+ return;
920
+ }
781
921
 
782
- CallbackToFutureAdapter.Completer<AuthorizationResult> future = futuresList.get(futureIndex);
922
+ future = futuresList.get(futureIndex);
923
+ if (future == null) {
924
+ Log.w(LOG_TAG, "Authorization result arrived after the login request ended");
925
+ return;
926
+ }
927
+ }
783
928
 
784
929
  try {
785
930
  AuthorizationResult authorizationResult = Identity.getAuthorizationClient(this.activity).getAuthorizationResultFromIntent(data);
@@ -787,6 +932,8 @@ public class GoogleProvider implements SocialProvider {
787
932
  } catch (ApiException e) {
788
933
  Log.e(LOG_TAG, "Cannot get getAuthorizationResultFromIntent", e);
789
934
  future.setException(new RuntimeException("Cannot get getAuthorizationResultFromIntent"));
935
+ } finally {
936
+ clearAuthorizationSlot(futureIndex, future);
790
937
  }
791
938
  }
792
939
 
@@ -1368,7 +1515,25 @@ public class GoogleProvider implements SocialProvider {
1368
1515
  );
1369
1516
  String newIdToken = googleIdTokenCredential.getIdToken();
1370
1517
 
1371
- ListenableFuture<AuthorizationResult> future = getAuthorizationResult(false);
1518
+ if (
1519
+ GoogleAuthorizationDecision.shouldSkipAuthorizationAfterCredentialSignIn(
1520
+ GoogleProvider.this.mode,
1521
+ GoogleProvider.this.scopes,
1522
+ GoogleProvider.this.skipAuthOnlyAuthorizationAfterSignIn
1523
+ )
1524
+ ) {
1525
+ persistState(newIdToken, null, GoogleProvider.this.scopes);
1526
+ call.resolve();
1527
+ return;
1528
+ }
1529
+
1530
+ String googleAccountId = googleIdTokenCredential.getId();
1531
+ AuthorizationWaitContext authorizationWaitContext = new AuthorizationWaitContext();
1532
+ ListenableFuture<AuthorizationResult> future = getAuthorizationResult(
1533
+ false,
1534
+ googleAccountId,
1535
+ authorizationWaitContext
1536
+ );
1372
1537
 
1373
1538
  ExecutorService authExecutor = Executors.newSingleThreadExecutor();
1374
1539
  authExecutor.execute(
@@ -1376,7 +1541,7 @@ public class GoogleProvider implements SocialProvider {
1376
1541
  @Override
1377
1542
  public void run() {
1378
1543
  try {
1379
- AuthorizationResult authResult = future.get(60, TimeUnit.SECONDS);
1544
+ AuthorizationResult authResult = awaitAuthorizationResult(future, authorizationWaitContext);
1380
1545
  String newAccessToken = authResult.getAccessToken();
1381
1546
  // Persist ID token even when access token is unavailable.
1382
1547
  persistState(
@@ -1385,8 +1550,19 @@ public class GoogleProvider implements SocialProvider {
1385
1550
  GoogleProvider.this.scopes
1386
1551
  );
1387
1552
  call.resolve();
1553
+ } catch (TimeoutException e) {
1554
+ finishWaitAndClearSlot(authorizationWaitContext);
1555
+ String timeoutMessage = authorizationWaitContext.isConsentUiLaunched()
1556
+ ? GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_TIMEOUT_MESSAGE
1557
+ : GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE;
1558
+ call.reject(timeoutMessage);
1388
1559
  } catch (Exception e) {
1389
- if (isAuthenticationOnlyScopes(GoogleProvider.this.scopes)) {
1560
+ finishWaitAndClearSlot(authorizationWaitContext);
1561
+ if (GoogleAuthorizationDecision.isUnroutableAuthorizationResolutionFailure(e)) {
1562
+ call.reject(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE);
1563
+ return;
1564
+ }
1565
+ if (GoogleAuthorizationDecision.isAuthenticationOnlyScopes(GoogleProvider.this.scopes)) {
1390
1566
  try {
1391
1567
  // Authorization failed; still keep the refreshed ID token.
1392
1568
  persistState(newIdToken, null, GoogleProvider.this.scopes);
@@ -29,7 +29,7 @@ import org.json.JSONTokener;
29
29
  @CapacitorPlugin(name = "SocialLogin")
30
30
  public class SocialLoginPlugin extends Plugin {
31
31
 
32
- private final String pluginVersion = "8.7.5";
32
+ private final String pluginVersion = "8.7.6";
33
33
 
34
34
  public static String LOG_TAG = "CapgoSocialLogin";
35
35
  private static final String USER_CANCELLED_CODE = "USER_CANCELLED";
@@ -222,7 +222,8 @@ public class SocialLoginPlugin extends Plugin {
222
222
  call.reject("google.mode != (online || offline)");
223
223
  return;
224
224
  }
225
- googleProvider.initialize(googleClientId, mode, hostedDomain);
225
+ boolean skipAuthOnlyAuthorizationAfterSignIn = google.getBoolean("skipAuthOnlyAuthorizationAfterSignIn", false);
226
+ googleProvider.initialize(googleClientId, mode, hostedDomain, skipAuthOnlyAuthorizationAfterSignIn);
226
227
  this.socialProviderHashMap.put("google", googleProvider);
227
228
  }
228
229
 
package/dist/docs.json CHANGED
@@ -146,16 +146,12 @@
146
146
  ],
147
147
  "returns": "Promise<void>",
148
148
  "tags": [
149
- {
150
- "name": "description",
151
- "text": "refresh the access token\n\n**Google Offline Mode Limitation:**\nThis method is NOT supported when Google is initialized with `mode: 'offline'`.\nOffline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.\nThe plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,\nrefresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.\n\n**Google Web Limitation:**\nOn Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.\nCall `login()` again on Web to obtain a fresh token instead."
152
- },
153
149
  {
154
150
  "name": "throws",
155
151
  "text": "Error if Google provider is in offline mode, or on Web where Google `refresh()` is not implemented"
156
152
  }
157
153
  ],
158
- "docs": "Refresh the access token",
154
+ "docs": "Refresh the access token for the logged-in provider.\n\n**Google Android refresh behavior:**\nOn Android, when the saved ID token is still valid and either no access token is stored or Google access\ntoken validation succeeds within the timeout, `refresh()` resolves without updating either token. That\nearly return applies regardless of `skipAuthOnlyAuthorizationAfterSignIn`.\nIf validation fails or times out, `refresh()` continues even when a token remains stored; with\n`skipAuthOnlyAuthorizationAfterSignIn: true` and default OIDC scopes, a successful credential refresh\nthen clears that access token without obtaining a new one.\n\n**Google Offline Mode Limitation:**\nThis method is NOT supported when Google is initialized with `mode: 'offline'`.\nOffline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.\nThe plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,\nrefresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.\n\n**Google Android `skipAuthOnlyAuthorizationAfterSignIn`:**\nWhen initialize sets `google.skipAuthOnlyAuthorizationAfterSignIn: true` and only default OIDC scopes are\nrequested, a refresh that runs past the early return skips `AuthorizationClient.authorize()`, updates the\nsaved `idToken`, and clears any saved access token; no new access token is obtained. Enabling the option\ndoes not clear a stored access token while the early return applies (validation succeeded or no token\nstored). With default `false`, refresh still skips authorize on the early return when no access token is\nstored but the ID token is valid.\n\n**Google Web Limitation:**\nOn Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.\nCall `login()` again on Web to obtain a fresh token instead.",
159
155
  "complexTypes": [
160
156
  "LoginOptions"
161
157
  ],
@@ -437,7 +433,7 @@
437
433
  "tags": [],
438
434
  "docs": "",
439
435
  "complexTypes": [],
440
- "type": "{ iOSClientId?: string | undefined; iOSServerClientId?: string | undefined; webClientId?: string | undefined; mode?: 'online' | 'offline' | undefined; hostedDomain?: string | undefined; redirectUrl?: string | undefined; } | undefined"
436
+ "type": "{ iOSClientId?: string | undefined; iOSServerClientId?: string | undefined; webClientId?: string | undefined; mode?: 'online' | 'offline' | undefined; hostedDomain?: string | undefined; redirectUrl?: string | undefined; skipAuthOnlyAuthorizationAfterSignIn?: boolean | undefined; } | undefined"
441
437
  },
442
438
  {
443
439
  "name": "apple",
@@ -1046,7 +1042,7 @@
1046
1042
  {
1047
1043
  "name": "accessToken",
1048
1044
  "tags": [],
1049
- "docs": "OAuth access token for Google APIs.\n\nMay be `null` on Android when Credential Manager authentication succeeds but\nAuthorizationClient does not return an access token (authentication-only /\nID-token login with default OIDC scopes). Use `idToken` for user authentication;\nrequest additional Google API scopes when an access token is required.",
1045
+ "docs": "OAuth access token for Google APIs.\n\nMay be `null` on Android when AuthorizationClient does not return an access token, or when\n`skipAuthOnlyAuthorizationAfterSignIn` is enabled during initialize (opt-in). Use `idToken`\nfor user authentication; request additional Google API scopes when an access token is required.",
1050
1046
  "complexTypes": [
1051
1047
  "AccessToken"
1052
1048
  ],
@@ -428,6 +428,23 @@ export interface InitializeOptions {
428
428
  * Google Redirect URL, should be your backend url that is configured in your google app
429
429
  */
430
430
  redirectUrl?: string;
431
+ /**
432
+ * Android only. When `true`, skip `AuthorizationClient.authorize()` after Credential Manager sign-in
433
+ * when `mode` is `online` and only default OIDC scopes are requested. Use this on stock `BridgeActivity`
434
+ * apps that hit a hang during authorize; login may return `accessToken: null` while still returning
435
+ * `idToken` and profile. When refresh runs past its early return (saved ID token expired or missing, or
436
+ * access token validation failed or timed out), authentication-only scopes skip authorize, update the saved
437
+ * `idToken`, and clear any saved access token.
438
+ * Enabling this after a session still has valid saved tokens does not clear a stored access token when
439
+ * refresh's early return applies: saved ID token valid and either no access token stored or validation
440
+ * succeeds. Default `false` keeps prior behavior: authorize runs on login and refresh when needed, and
441
+ * `accessToken` is returned when Google provides one. With default `false`, refresh still returns without
442
+ * authorize when saved tokens are already valid, including when no access token is stored.
443
+ *
444
+ * @default false
445
+ * @since 8.8.0
446
+ */
447
+ skipAuthOnlyAuthorizationAfterSignIn?: boolean;
431
448
  };
432
449
  apple?: {
433
450
  /**
@@ -797,10 +814,9 @@ export interface GoogleLoginResponseOnline {
797
814
  /**
798
815
  * OAuth access token for Google APIs.
799
816
  *
800
- * May be `null` on Android when Credential Manager authentication succeeds but
801
- * AuthorizationClient does not return an access token (authentication-only /
802
- * ID-token login with default OIDC scopes). Use `idToken` for user authentication;
803
- * request additional Google API scopes when an access token is required.
817
+ * May be `null` on Android when AuthorizationClient does not return an access token, or when
818
+ * `skipAuthOnlyAuthorizationAfterSignIn` is enabled during initialize (opt-in). Use `idToken`
819
+ * for user authentication; request additional Google API scopes when an access token is required.
804
820
  */
805
821
  accessToken: AccessToken | null;
806
822
  /**
@@ -1363,8 +1379,15 @@ export interface SocialLoginPlugin {
1363
1379
  */
1364
1380
  getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode>;
1365
1381
  /**
1366
- * Refresh the access token
1367
- * @description refresh the access token
1382
+ * Refresh the access token for the logged-in provider.
1383
+ *
1384
+ * **Google Android refresh behavior:**
1385
+ * On Android, when the saved ID token is still valid and either no access token is stored or Google access
1386
+ * token validation succeeds within the timeout, `refresh()` resolves without updating either token. That
1387
+ * early return applies regardless of `skipAuthOnlyAuthorizationAfterSignIn`.
1388
+ * If validation fails or times out, `refresh()` continues even when a token remains stored; with
1389
+ * `skipAuthOnlyAuthorizationAfterSignIn: true` and default OIDC scopes, a successful credential refresh
1390
+ * then clears that access token without obtaining a new one.
1368
1391
  *
1369
1392
  * **Google Offline Mode Limitation:**
1370
1393
  * This method is NOT supported when Google is initialized with `mode: 'offline'`.
@@ -1372,6 +1395,14 @@ export interface SocialLoginPlugin {
1372
1395
  * The plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,
1373
1396
  * refresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.
1374
1397
  *
1398
+ * **Google Android `skipAuthOnlyAuthorizationAfterSignIn`:**
1399
+ * When initialize sets `google.skipAuthOnlyAuthorizationAfterSignIn: true` and only default OIDC scopes are
1400
+ * requested, a refresh that runs past the early return skips `AuthorizationClient.authorize()`, updates the
1401
+ * saved `idToken`, and clears any saved access token; no new access token is obtained. Enabling the option
1402
+ * does not clear a stored access token while the early return applies (validation succeeded or no token
1403
+ * stored). With default `false`, refresh still skips authorize on the early return when no access token is
1404
+ * stored but the ID token is valid.
1405
+ *
1375
1406
  * **Google Web Limitation:**
1376
1407
  * On Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.
1377
1408
  * Call `login()` again on Web to obtain a fresh token instead.
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Configuration for a single OAuth2 provider instance\n */\nexport interface OAuth2ProviderConfig {\n /**\n * The OAuth 2.0 client identifier (App ID / Client ID).\n *\n * Note: this configuration object is only used by the plugin's built-in `oauth2` provider\n * (i.e. `SocialLogin.initialize({ oauth2: { ... } })`). It does not affect Google/Apple/Facebook/Twitter.\n * @example 'your-client-id'\n */\n appId?: string;\n /**\n * Alias for `appId` to match common OAuth/OIDC naming (`clientId`).\n * If both are provided, `appId` takes precedence.\n * @example 'your-client-id'\n */\n clientId?: string;\n /**\n * OpenID Connect issuer URL (enables discovery via `/.well-known/openid-configuration`).\n * When set, you may omit explicit endpoints like `authorizationBaseUrl` and `accessTokenEndpoint`.\n *\n * Notes:\n * - Explicit endpoints (authorization/token/logout) take precedence over discovered values.\n * - Discovery is supported for `oauth2` on Web, iOS, and Android.\n *\n * @example 'https://accounts.example.com'\n */\n issuerUrl?: string;\n /**\n * The base URL of the authorization endpoint\n * @example 'https://accounts.example.com/oauth2/authorize'\n */\n authorizationBaseUrl?: string;\n /**\n * Alias for `authorizationBaseUrl` (to match common OAuth/OIDC naming).\n * @example 'https://accounts.example.com/oauth2/authorize'\n */\n authorizationEndpoint?: string;\n /**\n * OAuth 2.0 client secret for token requests (e.g., when exchanging the code).\n * When provided, this value is sent using `clientSecretParamName` (default `client_secret`).\n */\n clientSecret?: string;\n /**\n * Override the client identifier parameter name used for authorization and token requests.\n * Some providers (e.g. TikTok) expect `client_key` instead of the default `client_id`.\n * @default 'client_id'\n */\n clientIdParamName?: string;\n /**\n * Override the client secret parameter name used for token requests.\n * Useful for providers that expect a different parameter name.\n * @default 'client_secret'\n */\n clientSecretParamName?: string;\n /**\n * The URL to exchange the authorization code for tokens\n * Required for authorization code flow\n * @example 'https://accounts.example.com/oauth2/token'\n */\n accessTokenEndpoint?: string;\n /**\n * Alias for `accessTokenEndpoint` (to match common OAuth/OIDC naming).\n * @example 'https://accounts.example.com/oauth2/token'\n */\n tokenEndpoint?: string;\n /**\n * Redirect URL that receives the OAuth callback\n * @example 'myapp://oauth/callback'\n */\n redirectUrl: string;\n /**\n * Optional URL to fetch user profile/resource data after authentication\n * The access token will be sent as Bearer token in the Authorization header\n * @example 'https://api.example.com/userinfo'\n */\n resourceUrl?: string;\n /**\n * The OAuth response type\n * - 'code': Authorization Code flow (recommended, requires accessTokenEndpoint)\n * - 'token': Implicit flow (less secure, tokens returned directly)\n * @default 'code'\n */\n responseType?: 'code' | 'token';\n /**\n * Enable PKCE (Proof Key for Code Exchange)\n * Strongly recommended for public clients (mobile/web apps)\n * @default true\n */\n pkceEnabled?: boolean;\n /**\n * Default scopes to request during authorization\n * @example 'openid profile email'\n * @example ['openid','profile','email']\n */\n scope?: string | string[];\n /**\n * Alias for `scope` using common naming (`scopes`).\n * If both are provided, `scope` takes precedence.\n */\n scopes?: string[];\n /**\n * Additional parameters to include in the authorization request\n * @example { prompt: 'consent', login_hint: 'user@example.com' }\n */\n additionalParameters?: Record<string, string>;\n /**\n * Convenience option for OIDC `login_hint`.\n * Equivalent to passing `additionalParameters.login_hint`.\n */\n loginHint?: string;\n /**\n * Convenience option for OAuth/OIDC `prompt`.\n * Equivalent to passing `additionalParameters.prompt`.\n */\n prompt?: string;\n /**\n * Additional parameters to include in token requests (code exchange / refresh).\n * Useful for providers that require non-standard parameters.\n */\n additionalTokenParameters?: Record<string, string>;\n /**\n * Additional headers to include when fetching the resource URL\n * @example { 'X-Custom-Header': 'value' }\n */\n additionalResourceHeaders?: Record<string, string>;\n /**\n * Custom logout URL for ending the session\n * @example 'https://accounts.example.com/logout'\n */\n logoutUrl?: string;\n /**\n * Alias for `logoutUrl` to match OIDC naming (`endSessionEndpoint`).\n * @example 'https://accounts.example.com/logout'\n */\n endSessionEndpoint?: string;\n /**\n * OIDC post logout redirect URL (sent as `post_logout_redirect_uri` when building the end-session URL).\n * @example 'myapp://logout/callback'\n */\n postLogoutRedirectUrl?: string;\n /**\n * Additional parameters to include in logout / end-session URL.\n */\n additionalLogoutParameters?: Record<string, string>;\n /**\n * iOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession.\n * Defaults to true to match existing behavior in this plugin.\n */\n iosPrefersEphemeralWebBrowserSession?: boolean;\n /**\n * Alias for `iosPrefersEphemeralWebBrowserSession` (to match Capawesome OAuth naming).\n */\n iosPrefersEphemeralSession?: boolean;\n /**\n * Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView\n * for the authorization request.\n *\n * Custom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered\n * IdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google\n * `disallowed_useragent`, SSO cookie sharing, password managers).\n *\n * Requires a custom-scheme or App Link `redirectUrl` with a matching intent filter in\n * your app's `AndroidManifest.xml` (same setup as `openSecureWindow()` / Apple on Android).\n *\n * Defaults to `false` to preserve the historical WebView flow.\n *\n * @default false\n * @example true\n */\n androidUseCustomTabs?: boolean;\n /**\n * Enable debug logging\n * @default false\n */\n logsEnabled?: boolean;\n}\n\n/**\n * LinkedIn provider configuration (convenience wrapper around the generic OAuth2 provider).\n *\n * Uses the OAuth2 engine with LinkedIn defaults:\n * - Authorization URL: https://www.linkedin.com/oauth/v2/authorization\n * - Token URL: https://www.linkedin.com/oauth/v2/accessToken\n * - Resource URL: https://api.linkedin.com/v2/userinfo\n * - Default scopes: `openid profile email`\n */\nexport interface LinkedInProviderConfig extends OAuth2ProviderConfig {\n /**\n * LinkedIn Client ID from the LinkedIn Developer Portal.\n */\n clientId: string;\n /**\n * Redirect URL that receives the OAuth callback.\n * Must match a redirect URL configured in the LinkedIn Developer Portal.\n * @example 'https://your-app.example/auth/linkedin'\n */\n redirectUrl: string;\n /**\n * LinkedIn Client Secret.\n *\n * Prefer exchanging the authorization code on a backend when possible.\n * Needed for confidential clients that do not use PKCE-only token exchange.\n */\n clientSecret?: string;\n}\n\n/**\n * TikTok Login Kit configuration (convenience wrapper around the generic OAuth2 provider).\n *\n * Uses TikTok OAuth 2.0 endpoints and `client_key` instead of `client_id`.\n * @see https://developers.tiktok.com/doc/login-kit-web\n */\nexport interface TikTokProviderConfig {\n /**\n * TikTok client key (also known as app key).\n * @example 'aw3y*****'\n */\n clientKey: string;\n /**\n * Redirect URL registered in your TikTok developer app.\n * @example 'myapp://auth/tiktok'\n */\n redirectUrl: string;\n /**\n * TikTok client secret. Optional.\n * When set, the plugin includes it on token and refresh requests.\n * On web this value is stored with the OAuth2 config.\n * Login always exchanges the authorization code in the plugin; the raw code is not returned to the app.\n */\n clientSecret?: string;\n /**\n * Scopes to request during login. Arrays are sent as a comma-separated string (TikTok Login Kit).\n * @default ['user.info.basic']\n * @example ['user.info.basic','video.list']\n */\n scopes?: string[];\n /**\n * Alias for `scopes`.\n */\n scope?: string | string[];\n /**\n * Toggle PKCE usage during the authorization code flow.\n * @default true\n */\n pkceEnabled?: boolean;\n /**\n * Enable verbose debug logging for the TikTok OAuth2 flow.\n * @default false\n */\n logsEnabled?: boolean;\n}\n\n/**\n * Options for `refreshToken()`.\n * `providerId` is required for generic `oauth2` and ignored for LinkedIn and TikTok.\n */\nexport type RefreshTokenOptions =\n | {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }\n | {\n provider: 'linkedin';\n providerId?: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }\n | {\n provider: 'tiktok';\n providerId?: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n };\n\nexport interface InitializeOptions {\n /**\n * OAuth2 provider configurations.\n * Supports multiple providers by using a Record with provider IDs as keys.\n * @example\n * {\n * github: { appId: '...', authorizationBaseUrl: 'https://github.com/login/oauth/authorize', ... },\n * azure: { appId: '...', authorizationBaseUrl: 'https://login.microsoftonline.com/.../oauth2/v2.0/authorize', ... }\n * }\n */\n oauth2?: Record<string, OAuth2ProviderConfig>;\n /**\n * Telegram Login Widget configuration.\n * Uses Telegram's OAuth widget (`oauth.telegram.org`), not standard OAuth2.\n */\n telegram?: {\n /**\n * Telegram bot ID (numeric, not the bot token).\n * @example '123456789'\n */\n botId: string;\n /**\n * Default redirect URL that will receive Telegram auth data.\n * For mobile apps, prefer a custom scheme (e.g. `myapp://telegram-auth`).\n * On iOS/Android this must be set here or per login; native login rejects if it is missing.\n */\n redirectUrl?: string;\n /**\n * Origin/domain registered for the Telegram login widget.\n * Required when `redirectUrl` is not `http`/`https` (for example a custom scheme like `myapp://telegram-auth`).\n * Defaults to the origin of `redirectUrl` only when that URL is already http(s).\n * @example 'https://example.com'\n */\n origin?: string;\n /**\n * Requested access level.\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n /**\n * Optional language code passed to Telegram (e.g. 'en', 'fr').\n */\n languageCode?: string;\n };\n /**\n * LinkedIn configuration.\n * Convenience wrapper that maps to the OAuth2 provider using LinkedIn defaults.\n */\n linkedin?: LinkedInProviderConfig;\n /**\n * TikTok Login Kit configuration.\n * Convenience wrapper that maps to the OAuth2 provider using TikTok defaults (`client_key`).\n */\n tiktok?: TikTokProviderConfig;\n twitter?: {\n /**\n * The OAuth 2.0 client identifier issued by X (Twitter) Developer Portal\n * @example 'Y2xpZW50SWQ'\n */\n clientId: string;\n /**\n * Redirect URL that is registered inside the X Developer Portal.\n * The plugin uses this URL on every platform to receive the authorization code.\n * @example 'myapp://auth/x'\n */\n redirectUrl: string;\n /**\n * Default scopes appended to every login request when no custom scopes are provided.\n * @description Defaults to the minimum required scopes for Log in with X.\n * @default ['tweet.read','users.read']\n */\n defaultScopes?: string[];\n /**\n * Force the consent screen to show on every login attempt.\n * Mirrors X's `force_login=true` flag.\n * @default false\n */\n forceLogin?: boolean;\n /**\n * Optional audience value when your application has been approved for multi-tenant access.\n */\n audience?: string;\n };\n facebook?: {\n /**\n * Facebook App ID, provided by Facebook for web, in mobile it's set in the native files\n * @description For business integrations, use your Business App ID from Facebook Developer Console.\n * Business apps can access additional permissions like Instagram API, Pages API, and business management features.\n * @see docs/facebook_business_login.md for business app setup guide\n */\n appId: string;\n /**\n * Facebook Client Token, provided by Facebook for web, in mobile it's set in the native files\n */\n clientToken?: string;\n /**\n * Locale\n * @description The locale to use for the Facebook SDK (e.g., 'en_US', 'fr_FR', 'es_ES')\n * @default 'en_US'\n * @example 'fr_FR'\n */\n locale?: string;\n };\n\n google?: {\n /**\n * The app's client ID, found and created in the Google Developers Console.\n * Required for iOS platform.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSClientId?: string;\n /**\n * The app's server client ID, required for offline mode on iOS.\n * Should be the same value as webClientId.\n * Found and created in the Google Developers Console.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSServerClientId?: string;\n /**\n * The app's web client ID, found and created in the Google Developers Console.\n * Required for Android and Web platforms.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n webClientId?: string;\n /**\n * The login mode, can be online or offline.\n *\n * **Online mode (default):**\n * - Returns user profile data and access tokens\n * - Supports all methods: login, logout, isLoggedIn, getAuthorizationCode\n *\n * **Offline mode:**\n * - Returns only serverAuthCode for backend authentication\n * - No user profile data available\n * - **Limitations:** The following methods are NOT supported in offline mode:\n * - `logout()` - Will reject with \"not implemented when using offline mode\"\n * - `isLoggedIn()` - Will reject with \"not implemented when using offline mode\"\n * - `getAuthorizationCode()` - Will reject with \"not implemented when using offline mode\"\n * - `refresh()` - Will reject because offline mode only returns `serverAuthCode`; token refresh must happen on your backend\n * - Only `login()` method works in offline mode, returning serverAuthCode only\n * - `serverAuthCode` must be exchanged on your backend for access/refresh tokens\n * - Requires `iOSServerClientId` to be set on iOS\n *\n * @example 'offline'\n * @default 'online'\n * @since 3.1.0\n */\n mode?: 'online' | 'offline';\n /**\n * Filter visible accounts by hosted domain\n * @description filter visible accounts by hosted domain\n */\n hostedDomain?: string;\n /**\n * Google Redirect URL, should be your backend url that is configured in your google app\n */\n redirectUrl?: string;\n };\n apple?: {\n /**\n * Apple Client ID, provided by Apple for web and Android\n */\n clientId?: string;\n /**\n * Apple Redirect URL, should be your backend url that is configured in your apple app\n *\n * **Note**: Use empty string `''` for iOS to prevent redirect.\n * **Note**: Not required when using Broadcast Channel mode on Android.\n */\n redirectUrl?: string;\n /**\n * Use proper token exchange for Apple Sign-In\n * @description Controls how Apple Sign-In tokens are handled and what gets returned:\n *\n * **When `true` (Recommended for new implementations):**\n * - Exchanges authorization code for proper access tokens via Apple's token endpoint\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: Proper access token from Apple (short-lived, ~1 hour)\n * - `authorizationCode`: Raw authorization code for backend token exchange\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses authorization code directly as access token for backward compatibility\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: The authorization code itself (not a real access token)\n * - `authorizationCode`: undefined\n *\n * @default false\n * @example\n * // Enable proper token exchange (recommended)\n * useProperTokenExchange: true\n * // Result: idToken=JWT, accessToken=real_token, authorizationCode=present\n *\n * // Legacy mode (backward compatibility)\n * useProperTokenExchange: false\n * // Result: idToken=JWT, accessToken=auth_code, authorizationCode=undefined\n */\n useProperTokenExchange?: boolean;\n /**\n * Use Broadcast Channel for Android Apple Sign-In (Recommended)\n * @description When enabled, Android uses Broadcast Channel API instead of URL redirects.\n * This eliminates the need for redirect URL configuration and server-side setup.\n *\n * **Benefits:**\n * - No redirect URL configuration required\n * - No backend server needed for Android\n * - Simpler setup and more reliable communication\n * - Direct client-server communication via Broadcast Channel\n *\n * **When `true`:**\n * - Uses Broadcast Channel for authentication flow\n * - `redirectUrl` is ignored\n * - Requires Broadcast Channel compatible backend or direct token handling\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses traditional URL redirect flow\n * - Requires `redirectUrl` configuration\n * - Requires backend server for token exchange\n *\n * @default false\n * @since 7.10.0\n * @example\n * // Enable Broadcast Channel mode (recommended for new Android implementations)\n * useBroadcastChannel: true\n * // Result: Simplified setup, no redirect URL needed\n *\n * // Legacy mode (backward compatibility)\n * useBroadcastChannel: false\n * // Result: Traditional URL redirect flow with server-side setup\n */\n useBroadcastChannel?: boolean;\n };\n}\n\nexport interface FacebookLoginOptions {\n /**\n * Permissions\n * @description Select permissions to login with. Supports both consumer and business permissions.\n *\n * **Consumer Permissions:**\n * - `email` - User's email address\n * - `public_profile` - User's public profile info\n * - `user_friends` - List of friends who also use your app\n *\n * **Business Permissions** (require business app configuration and may need App Review):\n * - `instagram_basic` - Instagram Basic Display API access\n * - `instagram_manage_insights` - Instagram Insights data\n * - `instagram_manage_comments` - Manage Instagram comments\n * - `instagram_content_publish` - Publish to Instagram\n * - `pages_show_list` - List of Pages managed by user\n * - `pages_read_engagement` - Read Page engagement metrics\n * - `pages_manage_posts` - Manage Page posts\n * - `pages_messaging` - Page messaging features\n * - `business_management` - Manage business assets\n * - `catalog_management` - Manage product catalogs\n * - `ads_management` - Manage advertising accounts\n *\n * @example ['email', 'public_profile'] // Consumer permissions\n * @example ['email', 'instagram_basic', 'pages_show_list'] // Business permissions\n * @see https://developers.facebook.com/docs/permissions/reference\n * @see docs/facebook_business_login.md for complete business integration guide\n */\n permissions: string[];\n /**\n * Is Limited Login\n * @description use limited login for Facebook iOS only. Important: This is iOS-only and doesn't affect Android.\n * Even if set to false, Facebook will automatically force it to true if App Tracking Transparency (ATT) permission is not granted.\n * Developers should always be prepared to handle both limited and full login scenarios.\n * @default false\n */\n limitedLogin?: boolean;\n /**\n * Nonce\n * @description A custom nonce to use for the login request\n */\n nonce?: string;\n}\n\nexport interface TwitterLoginOptions {\n /**\n * Additional scopes to request during login.\n * If omitted the plugin falls back to the default scopes configured during initialization.\n * @example ['tweet.read','users.read','offline.access']\n */\n scopes?: string[];\n /**\n * Provide a custom OAuth state value.\n * When not provided the plugin generates a cryptographically random value.\n */\n state?: string;\n /**\n * Provide a pre-computed PKCE code verifier (mostly used for testing).\n * When omitted the plugin generates a secure verifier automatically.\n */\n codeVerifier?: string;\n /**\n * Override the redirect URI for a single login call.\n * Useful when the same app supports multiple callback URLs per platform.\n */\n redirectUrl?: string;\n /**\n * Force the consent screen on every attempt, maps to `force_login=true`.\n */\n forceLogin?: boolean;\n}\n\nexport interface TelegramLoginOptions {\n /**\n * Override the redirect URL for this login attempt.\n * Defaults to the redirect configured during initialize().\n * Required on iOS/Android when initialize() did not set `redirectUrl`.\n */\n redirectUrl?: string;\n /**\n * Optional state parameter for CSRF protection.\n * If omitted, a secure random value is generated automatically.\n */\n state?: string;\n /**\n * Override requested access level for this login.\n * Defaults to the value configured during initialize().\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n}\n\nexport interface OAuth2LoginOptions {\n /**\n * The provider ID as configured in initialize()\n * This is required to identify which OAuth2 provider to use\n * @example 'github', 'azure', 'keycloak'\n */\n providerId: string;\n /**\n * Override the scopes for this login request\n * If not provided, uses the scopes from initialization\n */\n scope?: string | string[];\n /**\n * Alias for `scope` using common naming (`scopes`).\n * If both are provided, `scope` takes precedence.\n */\n scopes?: string[];\n /**\n * Custom state parameter for CSRF protection\n * If not provided, a random value is generated\n */\n state?: string;\n /**\n * Override PKCE code verifier (for testing purposes)\n * If not provided, a secure random verifier is generated\n */\n codeVerifier?: string;\n /**\n * Override redirect URL for this login request\n */\n redirectUrl?: string;\n /**\n * Additional parameters to add to the authorization URL\n */\n additionalParameters?: Record<string, string>;\n /**\n * Convenience option for OIDC `login_hint`.\n * Equivalent to passing `additionalParameters.login_hint`.\n */\n loginHint?: string;\n /**\n * Convenience option for OAuth/OIDC `prompt`.\n * Equivalent to passing `additionalParameters.prompt`.\n */\n prompt?: string;\n /**\n * Web-only (`oauth2` provider only): Use a full-page redirect instead of a popup window.\n *\n * When using `redirect`, the promise returned by `login()` will not resolve because the page navigates away.\n * After the redirect lands back in your app, call `SocialLogin.handleRedirectCallback()` on that page to\n * parse the result.\n *\n * @default 'popup'\n */\n flow?: 'popup' | 'redirect';\n}\n\n/**\n * LinkedIn login options (maps to the OAuth2 provider internally).\n * `providerId` is set to `linkedin` automatically.\n */\nexport type LinkedInLoginOptions = Omit<OAuth2LoginOptions, 'providerId'>;\n\nexport interface TikTokLoginOptions {\n /**\n * Optional scopes to override the initialization scopes.\n * @example ['user.info.basic']\n */\n scopes?: string[];\n /**\n * Alias for `scopes`.\n */\n scope?: string | string[];\n /**\n * Custom state parameter for CSRF protection.\n */\n state?: string;\n /**\n * Custom PKCE code verifier (mostly for testing).\n */\n codeVerifier?: string;\n /**\n * Override redirect URL for this login request.\n */\n redirectUrl?: string;\n}\n\nexport interface OAuth2LoginResponse {\n /**\n * The provider ID that was used for this login\n */\n providerId: string;\n /**\n * The access token received from the OAuth provider\n */\n accessToken: AccessToken | null;\n /**\n * The ID token (JWT) if provided by the OAuth server (e.g., OpenID Connect)\n */\n idToken: string | null;\n /**\n * The refresh token if provided (requires appropriate scope like offline_access)\n */\n refreshToken: string | null;\n /**\n * Resource data fetched from resourceUrl if configured\n * Contains the raw JSON response from the resource endpoint\n */\n resourceData: Record<string, unknown> | null;\n /**\n * The scopes that were granted\n */\n scope: string[];\n /**\n * Token type (usually 'bearer')\n */\n tokenType: string;\n /**\n * Token expiration time in seconds\n */\n expiresIn: number | null;\n}\n\n/**\n * LinkedIn login response (returned when using the LinkedIn convenience API).\n */\nexport type LinkedInLoginResponse = OAuth2LoginResponse;\n\n/**\n * TikTok login response (same shape as generic OAuth2).\n */\nexport type TikTokLoginResponse = OAuth2LoginResponse;\n\nexport interface GoogleLoginOptions {\n /**\n * Specifies the scopes required for accessing Google APIs\n * The default is defined in the configuration.\n * @example [\"profile\", \"email\"]\n * @see [Google OAuth2 Scopes](https://developers.google.com/identity/protocols/oauth2/scopes)\n */\n scopes?: string[];\n /**\n * Nonce. On iOS, a login with a nonce always shows the Google sign-in instead of restoring the\n * previous sign-in: a restored ID token was minted without this nonce, so a backend that verifies\n * it (for example Supabase `signInWithIdToken`) would reject the token.\n * @description nonce\n */\n nonce?: string;\n /**\n * Force refresh token (only for Android)\n * @description force refresh token\n * @default false\n * @note On Android, the OS caches access tokens, and if a token is invalid (e.g., user revoked app access), the plugin might return an invalid accessToken. Using getAuthorizationCode() is recommended to ensure the token is valid.\n */\n forceRefreshToken?: boolean;\n /**\n * Force account selection prompt (iOS)\n * @description forces the account selection prompt to appear on iOS\n * @default false\n */\n forcePrompt?: boolean;\n /**\n * Style\n * @description style\n * @default 'standard'\n */\n style?: 'bottom' | 'standard';\n /**\n * Filter by authorized accounts (Android only)\n * @description Only show accounts that have previously been used to sign in to the app.\n * This option is only available for the 'bottom' style.\n * Note: For Family Link supervised accounts, this should be set to false.\n * @default false\n */\n filterByAuthorizedAccounts?: boolean;\n /**\n * Auto select enabled (Android only)\n * @description Automatically select the account if only one Google account is available.\n * This option is only available for the 'bottom' style.\n * @default false\n */\n autoSelectEnabled?: boolean;\n /**\n * Prompt parameter for Google OAuth (Web only)\n * @description A space-delimited, case-sensitive list of prompts to present the user.\n * If you don't specify this parameter, the user will be prompted only the first time your project requests access.\n *\n * **Possible values:**\n * - `none`: Don't display any authentication or consent screens. Must not be specified with other values.\n * - `consent`: Prompt the user for consent.\n * - `select_account`: Prompt the user to select an account.\n *\n * **Examples:**\n * - `prompt: 'consent'` - Always show consent screen\n * - `prompt: 'select_account'` - Always show account selection\n * - `prompt: 'consent select_account'` - Show both consent and account selection\n *\n * **Note:** This parameter only affects web platform behavior. Mobile platforms use their own native prompts.\n *\n * @example 'consent'\n * @example 'select_account'\n * @example 'consent select_account'\n * @see [Google OAuth2 Prompt Parameter](https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt)\n * @since 7.12.0\n */\n prompt?: 'none' | 'consent' | 'select_account' | 'consent select_account' | 'select_account consent';\n}\n\nexport interface GoogleLoginResponseOnline {\n /**\n * OAuth access token for Google APIs.\n *\n * May be `null` on Android when Credential Manager authentication succeeds but\n * AuthorizationClient does not return an access token (authentication-only /\n * ID-token login with default OIDC scopes). Use `idToken` for user authentication;\n * request additional Google API scopes when an access token is required.\n */\n accessToken: AccessToken | null;\n /**\n * OpenID Connect ID token (JWT).\n *\n * Includes an `email_verified` claim when the `email` scope is granted. Use\n * `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but\n * always verify the token signature, `iss`, `aud`, and `exp` on your backend\n * before trusting `email_verified` for account linking.\n *\n * @see https://developers.google.com/identity/gsi/web/guides/verify-google-id-token\n */\n idToken: string | null;\n profile: {\n /**\n * Email from the ID token payload. Does not include a separate verification flag;\n * check `idToken` claims (`email_verified`) for whether Google attests the address.\n */\n email: string | null;\n familyName: string | null;\n givenName: string | null;\n id: string | null;\n name: string | null;\n imageUrl: string | null;\n };\n responseType: 'online';\n}\n\nexport interface GoogleLoginResponseOffline {\n serverAuthCode: string;\n responseType: 'offline';\n}\n\nexport type GoogleLoginResponse = GoogleLoginResponseOnline | GoogleLoginResponseOffline;\n\nexport interface AppleProviderOptions {\n /**\n * Scopes\n * @description An array of scopes to request during login\n * @example [\"name\", \"email\"]\n * default: [\"name\", \"email\"]\n */\n scopes?: string[];\n /**\n * Nonce\n * @description nonce\n */\n nonce?: string;\n /**\n * State\n * @description state\n */\n state?: string;\n /**\n * Use Broadcast Channel for authentication flow\n * @description When enabled, uses Broadcast Channel API for communication instead of URL redirects.\n * Only applicable on platforms that support Broadcast Channel (Android).\n * @default false\n */\n useBroadcastChannel?: boolean;\n}\n\nexport interface AppleProviderResponse {\n /**\n * Access token from Apple\n * @description Content depends on `useProperTokenExchange` setting:\n * - When `useProperTokenExchange: true`: Real access token from Apple (~1 hour validity)\n * - When `useProperTokenExchange: false`: Contains authorization code as token (legacy mode)\n * Use `idToken` for user authentication, `accessToken` for API calls when properly exchanged.\n */\n accessToken: AccessToken | null;\n\n /**\n * Identity token (JWT) from Apple.\n *\n * Includes standard OIDC claims such as `sub`, `email` (when granted), and\n * `email_verified` (boolean). Apple sets `email_verified` to `true` when it\n * attests the user controls the email (including Hide My Email relay addresses).\n *\n * Use `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but\n * verify the token signature, `iss`, `aud`, and `exp` on your backend before\n * trusting `email_verified` for account linking.\n *\n * @see https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\n */\n idToken: string | null;\n\n /**\n * User profile information\n * @description Basic user profile data extracted from the identity token and Apple response:\n * - `user`: Apple's user identifier (sub claim from idToken)\n * - `email`: User's email address (if permission granted)\n * - `givenName`: User's first name (if permission granted)\n * - `familyName`: User's last name (if permission granted)\n */\n profile: {\n user: string;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n };\n\n /**\n * Authorization code for proper token exchange (when useProperTokenExchange is enabled)\n * @description Only present when `useProperTokenExchange` is `true`. This code should be exchanged\n * for proper access tokens on your backend using Apple's token endpoint. Use this for secure\n * server-side token validation and to obtain refresh tokens.\n * @see https://developer.apple.com/documentation/sign_in_with_apple/tokenresponse\n */\n authorizationCode?: string;\n}\n\nexport type LoginOptions =\n | {\n provider: 'facebook';\n options: FacebookLoginOptions;\n }\n | {\n provider: 'google';\n options: GoogleLoginOptions;\n }\n | {\n provider: 'apple';\n options: AppleProviderOptions;\n }\n | {\n provider: 'twitter';\n options: TwitterLoginOptions;\n }\n | {\n provider: 'telegram';\n options: TelegramLoginOptions;\n }\n | {\n provider: 'linkedin';\n options: LinkedInLoginOptions;\n }\n | {\n provider: 'tiktok';\n options: TikTokLoginOptions;\n }\n | {\n provider: 'oauth2';\n options: OAuth2LoginOptions;\n };\n\nexport type LoginResult =\n | {\n provider: 'facebook';\n result: FacebookLoginResponse;\n }\n | {\n provider: 'google';\n result: GoogleLoginResponse;\n }\n | {\n provider: 'apple';\n result: AppleProviderResponse;\n }\n | {\n provider: 'twitter';\n result: TwitterLoginResponse;\n }\n | {\n provider: 'telegram';\n result: TelegramLoginResponse;\n }\n | {\n provider: 'linkedin';\n result: LinkedInLoginResponse;\n }\n | {\n provider: 'tiktok';\n result: TikTokLoginResponse;\n }\n | {\n provider: 'oauth2';\n result: OAuth2LoginResponse;\n };\n\nexport interface AccessToken {\n applicationId?: string;\n declinedPermissions?: string[];\n expires?: string;\n isExpired?: boolean;\n lastRefresh?: string;\n permissions?: string[];\n token: string;\n tokenType?: string;\n refreshToken?: string;\n userId?: string;\n}\n\nexport interface FacebookLoginResponse {\n accessToken: AccessToken | null;\n /**\n * Whether Facebook Limited Login was used for this session.\n * When `true`, `accessToken` is not valid for Graph API calls (Facebook error 190).\n * Validate `idToken` on your backend instead, or call `facebook#requestTracking` and log in again after ATT is granted.\n * @since 8.4.0\n */\n isLimitedLogin?: boolean;\n /**\n * OpenID Connect ID token (JWT) from Meta Limited Login (iOS native, when available).\n *\n * **Not equivalent to Google/Apple `email_verified`:** Meta's OIDC token may include\n * an `email` claim (when the `email` permission is granted) but does **not** publish an\n * `email_verified` claim like Google or Apple. Meta documents the value as the user's\n * primary account email, not as an OIDC-verified email assertion.\n *\n * On Android and Web this is usually `null` (Graph API access token flow instead).\n * Validate signature, `iss` (`https://www.facebook.com` or `https://limited.facebook.com`),\n * `aud`, `exp`, and nonce on your backend. Do not infer `email_verified: true` from the\n * presence of `email` alone when linking accounts across providers.\n *\n * @see https://developers.facebook.com/docs/facebook-login/limited-login/token/validating/\n */\n idToken: string | null;\n profile: {\n userID: string;\n /**\n * Primary email from the Meta profile / Graph API (`/me?fields=email`).\n *\n * **Not equivalent to Google/Apple `email_verified`:** this field has no verification\n * flag. Meta returns the account's primary email when the `email` permission is\n * granted; it does not expose an `email_verified` boolean comparable to Google or\n * Apple ID tokens. Treat this as an identifier hint only—verify ownership yourself\n * (e.g. magic link) before linking Meta sign-in to Google/Apple accounts by email.\n */\n email: string | null;\n friendIDs: string[];\n birthday: string | null;\n ageRange: { min?: number; max?: number } | null;\n gender: string | null;\n location: { id: string; name: string } | null;\n hometown: { id: string; name: string } | null;\n profileURL: string | null;\n name: string | null;\n imageURL: string | null;\n };\n}\n\nexport interface TwitterProfile {\n id: string;\n username: string;\n name: string | null;\n profileImageUrl: string | null;\n verified: boolean;\n email?: string | null;\n}\n\nexport interface TwitterLoginResponse {\n accessToken: AccessToken | null;\n refreshToken?: string | null;\n scope: string[];\n tokenType: 'bearer';\n expiresIn?: number | null;\n profile: TwitterProfile;\n}\n\nexport interface TelegramProfile {\n id: string;\n firstName: string;\n lastName?: string | null;\n username?: string | null;\n photoUrl?: string | null;\n}\n\nexport interface TelegramLoginResponse {\n profile: TelegramProfile;\n /**\n * Unix timestamp (seconds) when the user authorized the login.\n */\n authDate: number;\n /**\n * Telegram-provided hash for server-side verification.\n */\n hash: string;\n /**\n * Requested access level that was used for this login.\n */\n requestAccess: 'read' | 'write';\n}\n\nexport interface AuthorizationCode {\n /**\n * Jwt\n * @description A JSON web token\n */\n jwt?: string;\n /**\n * Access Token\n * @description An access token\n */\n accessToken?: string;\n}\n\nexport interface AuthorizationCodeOptions {\n /**\n * Provider\n * @description Provider for the authorization code\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'linkedin' | 'tiktok' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\nexport interface isLoggedInOptions {\n /**\n * Provider\n * @description Provider for the isLoggedIn\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'linkedin' | 'tiktok' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\n// Define the provider-specific call types\n/**\n * Options for `providerSpecificCall` with `google#createRestoreCredential`.\n *\n * Android-only. Creates a Restore Credential (restore key) via Credential Manager after the user\n * signs in. Your backend must supply WebAuthn PublicKeyCredentialCreationOptionsJSON (the same\n * FIDO2/passkey registration flow used for passkeys).\n *\n * @see https://developer.android.com/identity/sign-in/restore-credentials\n * @since 8.5.0\n */\nexport interface GoogleCreateRestoreCredentialOptions {\n /**\n * Credential creation options from your server in WebAuthn PublicKeyCredentialCreationOptionsJSON format.\n */\n requestJson: string;\n /**\n * When `true` (default), the restore key is backed up to the cloud when the user has backup and\n * end-to-end encryption (e.g. screen lock) enabled. If cloud backup creation fails with\n * `E2eeUnavailableException` on Android, the plugin automatically retries with local-only storage.\n * @default true\n */\n isCloudBackupEnabled?: boolean;\n}\n\n/**\n * Response from `google#createRestoreCredential`.\n *\n * Send `responseJson` to your server to complete restore key registration (same as passkey creation).\n */\nexport interface GoogleCreateRestoreCredentialResponse {\n /** Public key credential registration response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/**\n * Options for `providerSpecificCall` with `google#getRestoreCredential`.\n *\n * Android-only. Retrieves a Restore Credential silently (e.g. on first launch on a new device or from\n * BackupAgent `onRestoreFinished`). Your backend must supply WebAuthn authentication request JSON.\n */\nexport interface GoogleGetRestoreCredentialOptions {\n /**\n * Credential request options from your server (WebAuthn authentication request JSON).\n */\n requestJson: string;\n}\n\n/**\n * Response from `google#getRestoreCredential`.\n *\n * Send `responseJson` to your server to sign the user in (same server path as passkey authentication).\n */\nexport interface GoogleGetRestoreCredentialResponse {\n /** Restore credential authentication response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/** Options for `google#clearRestoreCredential` (no fields). */\nexport type GoogleClearRestoreCredentialOptions = Record<string, never>;\n\n/** Response from `google#clearRestoreCredential`. */\nexport interface GoogleClearRestoreCredentialResponse {\n /** Whether the restore credential clear request completed successfully. */\n cleared: boolean;\n}\n\nexport type ProviderSpecificCall =\n | 'facebook#getProfile'\n | 'facebook#requestTracking'\n | 'google#createRestoreCredential'\n | 'google#getRestoreCredential'\n | 'google#clearRestoreCredential';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile.\n * @default ['id', 'name', 'email', 'picture']\n * @example [\"id\", \"name\", \"email\", \"picture\"]\n */\n fields?: string[];\n}\n\nexport interface FacebookGetProfileResponse {\n /**\n * Facebook profile data\n */\n profile: {\n id: string | null;\n name: string | null;\n email: string | null;\n first_name: string | null;\n last_name: string | null;\n picture?: {\n data: {\n height: number | null;\n is_silhouette: boolean | null;\n url: string | null;\n width: number | null;\n };\n } | null;\n [key: string]: any; // For additional fields that might be requested\n };\n}\n\nexport interface OpenSecureWindowOptions {\n /**\n * The endpoint to open\n */\n authEndpoint: string;\n /**\n * The redirect URI to use for the openSecureWindow call.\n * This will be checked to make sure it matches the redirect URI after the window finishes the redirection.\n */\n redirectUri: string;\n /**\n * The name of the broadcast channel to listen to, relevant only for web\n */\n broadcastChannelName?: string;\n}\n\nexport interface OpenSecureWindowResponse {\n /**\n * The result of the openSecureWindow call\n */\n redirectedUri: string;\n}\n\nexport interface OpenAuthSessionOptions {\n /**\n * Authorization or login URL to open in the system browser session (OAuth/OIDC authorize endpoint, SSO login page, etc.).\n * @example 'https://login.example.com/oauth2/authorize?client_id=...&redirect_uri=...&state=...'\n */\n url: string;\n /**\n * Custom URL scheme that receives the redirect (without `://`).\n * Must match the scheme in your registered redirect URI and native URL handler (iOS/Android).\n * On Web, the plugin also accepts HTTPS redirect URLs when `redirect_uri` is present in `url`, or messages prefixed with `${callbackURLScheme}://` on the BroadcastChannel.\n * @example 'myapp'\n */\n callbackURLScheme: string;\n /**\n * iOS-only: prefer an ephemeral `ASWebAuthenticationSession` (no shared cookies with Safari).\n * Defaults to `false` so SSO cookies in the system browser can be reused.\n */\n prefersEphemeralSession?: boolean;\n /**\n * Web-only: `BroadcastChannel` name used by the redirect page to post the callback URL back to the app.\n * @default 'capgo-auth-session'\n */\n broadcastChannelName?: string;\n}\n\nexport interface OpenAuthSessionResult {\n /**\n * Full redirect URI returned by the identity provider, including query or fragment (e.g. `myapp://auth/callback?code=...&state=...`).\n */\n callbackURL: string;\n}\n\nexport type FacebookRequestTrackingOptions = Record<string, never>;\n\nexport interface FacebookRequestTrackingResponse {\n /**\n * App tracking authorization status\n */\n status: 'authorized' | 'denied' | 'notDetermined' | 'restricted';\n}\n\n// Map call strings to their options and response types\nexport type ProviderSpecificCallOptionsMap = {\n 'facebook#getProfile': FacebookGetProfileOptions;\n 'facebook#requestTracking': FacebookRequestTrackingOptions;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialOptions;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialOptions;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialOptions;\n};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialResponse;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialResponse;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialResponse;\n};\n\n// Add a helper type to map providers to their response types\nexport type ProviderResponseMap = {\n facebook: FacebookLoginResponse;\n google: GoogleLoginResponse;\n apple: AppleProviderResponse;\n twitter: TwitterLoginResponse;\n telegram: TelegramLoginResponse;\n linkedin: LinkedInLoginResponse;\n tiktok: TikTokLoginResponse;\n oauth2: OAuth2LoginResponse;\n};\n\n/**\n * Error codes returned by the plugin.\n * @since 8.3.x\n */\nexport type SocialLoginErrorCode = 'USER_CANCELLED';\n\n/**\n * Errors thrown by SocialLogin methods.\n *\n * When a user dismisses or cancels the provider UI (popup closed, system dialog cancelled, access denied, etc.),\n * the plugin rejects with `code === 'USER_CANCELLED'` so the caller can distinguish user intent from real failures.\n * Other errors may omit the code or use provider-specific values.\n */\nexport interface SocialLoginError extends Error {\n code?: SocialLoginErrorCode | string;\n}\n\nexport interface SocialLoginPlugin {\n /**\n * Initialize the plugin\n * @description initialize the plugin with the required options\n */\n initialize(options: InitializeOptions): Promise<void>;\n /**\n * Login with the selected provider\n * @description login with the selected provider\n *\n * On user dismissal/cancellation, the Promise is rejected with `code === 'USER_CANCELLED'` (see `SocialLoginError`).\n */\n login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }>;\n /**\n * Logout\n * @description Logout the user from the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"logout is not implemented when using offline mode\"\n *\n * **Google Restore Credentials (Android):**\n * When logging out from Google, the plugin also clears any stored Restore Credential\n * (`google#clearRestoreCredential`) in addition to Credential Manager sign-in state.\n *\n * **Apple cached name (iOS):**\n * The plugin keeps the name Apple returns only on the first authorization, and logging out\n * keeps it. Pass `clearCachedUserInfo: true` to remove it too, for example on account deletion.\n *\n * @throws Error if Google provider is in offline mode\n */\n logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'linkedin' | 'tiktok' | 'oauth2';\n providerId?: string;\n /**\n * Apple on iOS: also remove the first and family name the plugin keeps on the device. Apple\n * returns the name only on the first authorization, so the plugin caches it to fill `givenName`\n * and `familyName` on later logins. Pass `true` when the user deletes their account, or should\n * otherwise leave no trace on the device. The name is removed even if no Apple session is held.\n * Ignored by other providers and platforms.\n * @default false\n */\n clearCachedUserInfo?: boolean;\n }): Promise<void>;\n /**\n * IsLoggedIn\n * @description Check if the user is currently logged in with the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"isLoggedIn is not implemented when using offline mode\"\n *\n * @throws Error if Google provider is in offline mode\n */\n isLoggedIn(options: isLoggedInOptions): Promise<{ isLoggedIn: boolean }>;\n\n /**\n * Get the current authorization code\n * @description Get the authorization code for server-side authentication\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"getAuthorizationCode is not implemented when using offline mode\"\n *\n * In offline mode, the authorization code (serverAuthCode) is already returned by the `login()` method.\n *\n * Telegram login does not produce an authorization code; use the `hash` from `login()` and verify it on your backend.\n *\n * @throws Error if Google provider is in offline mode\n */\n getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode>;\n /**\n * Refresh the access token\n * @description refresh the access token\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * Offline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.\n * The plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,\n * refresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.\n *\n * **Google Web Limitation:**\n * On Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.\n * Call `login()` again on Web to obtain a fresh token instead.\n *\n * @throws Error if Google provider is in offline mode, or on Web where Google `refresh()` is not implemented\n */\n refresh(options: LoginOptions): Promise<void>;\n\n /**\n * OAuth2 refresh-token helper (feature parity with Capawesome OAuth).\n *\n * Scope:\n * - Applies to the built-in `oauth2` provider and the LinkedIn and TikTok convenience wrappers.\n * - Requires a token endpoint (either `accessTokenEndpoint`/`tokenEndpoint` or `issuerUrl` discovery).\n *\n * Security note:\n * - This does not validate JWT signatures. It only exchanges/refreshes tokens.\n *\n * If `refreshToken` is omitted, the plugin will attempt to use the stored refresh token (if available).\n */\n refreshToken(options: RefreshTokenOptions): Promise<OAuth2LoginResponse>;\n\n /**\n * Web-only: handle the OAuth redirect callback and return the parsed result.\n *\n * Notes:\n * - This is only meaningful on Web. iOS/Android implementations will reject.\n * - Intended for redirect-based flows (e.g. `oauth2` with `flow: 'redirect'`) where the page navigates away.\n * - LinkedIn convenience logins (`provider: 'linkedin'`, `flow: 'redirect'`) return `provider: 'linkedin'`.\n * The same app used as `oauth2` with `providerId: 'linkedin'` keeps `provider: 'oauth2'`.\n */\n handleRedirectCallback(): Promise<LoginResult | null>;\n\n /**\n * Decode a JWT (typically an OIDC ID token) into its claims.\n *\n * Notes:\n * - Accepts both `idToken` and `token` to match common naming (Capawesome uses `token`).\n * - This does not validate the signature or issuer/audience. It only base64url-decodes the payload.\n *\n * **`email_verified` semantics by provider (for account linking):**\n * - **Google** — ID token includes `email_verified` (boolean). When `true`, Google attests\n * the user controls that email. Verify the JWT on your backend before trusting it.\n * - **Apple** — ID token includes `email_verified` (boolean). When `true`, Apple attests\n * the user controls that email (including private relay). Verify the JWT on your backend.\n * - **Meta (Facebook)** — Limited Login OIDC tokens may include `email` but **do not**\n * include `email_verified`. The presence of `email` is not the same guarantee as\n * `email_verified: true` from Google or Apple. Do not link accounts by email across\n * providers using Meta claims alone; perform your own email verification if needed.\n */\n decodeIdToken(options: { idToken?: string; token?: string }): Promise<{ claims: Record<string, any> }>;\n\n /**\n * Convert an access token expiration timestamp (milliseconds since epoch) to an ISO date string.\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n getAccessTokenExpirationDate(options: {\n /**\n * Access token expiration date in milliseconds since epoch.\n * Typically: `Date.now() + expiresInSeconds * 1000`.\n */\n accessTokenExpirationDate: number;\n }): Promise<{ date: string }>;\n\n /**\n * Check if an access token is available (non-empty).\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isAccessTokenAvailable(options: { accessToken: string | null }): Promise<{ isAvailable: boolean }>;\n\n /**\n * Check if an access token is expired.\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isAccessTokenExpired(options: { accessTokenExpirationDate: number }): Promise<{ isExpired: boolean }>;\n\n /**\n * Check if a refresh token is available (non-empty).\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isRefreshTokenAvailable(options: { refreshToken: string | null }): Promise<{ isAvailable: boolean }>;\n\n /**\n * Execute provider-specific calls\n * @description Execute a provider-specific functionality\n */\n providerSpecificCall<T extends ProviderSpecificCall>(options: {\n call: T;\n options: ProviderSpecificCallOptionsMap[T];\n }): Promise<ProviderSpecificCallResponseMap[T]>;\n\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Opens a secured window for OAuth2 authentication.\n * For web, you should have the code in the redirected page to use a broadcast channel to send the redirected url to the app\n * Something like:\n * ```html\n * <html>\n * <head></head>\n * <body>\n * <script>\n * const searchParams = new URLSearchParams(location.search)\n * if (searchParams.has(\"code\")) {\n * new BroadcastChannel(\"my-channel-name\").postMessage(location.href);\n * window.close();\n * }\n * </script>\n * </body>\n * </html>\n * ```\n * For mobile, you should have a redirect uri that opens the app, something like: `myapp://oauth_callback/`\n * And make sure to register it in the app's info.plist:\n * ```xml\n * <key>CFBundleURLTypes</key>\n * <array>\n * <dict>\n * <key>CFBundleURLSchemes</key>\n * <array>\n * <string>myapp</string>\n * </array>\n * </dict>\n * </array>\n * ```\n * And in the AndroidManifest.xml file:\n * ```xml\n * <activity>\n * <intent-filter>\n * <action android:name=\"android.intent.action.VIEW\" />\n * <category android:name=\"android.intent.category.DEFAULT\" />\n * <category android:name=\"android.intent.category.BROWSABLE\" />\n * <data android:host=\"oauth_callback\" android:scheme=\"myapp\" />\n * </intent-filter>\n * </activity>\n * ```\n * @param options - the options for the openSecureWindow call\n */\n openSecureWindow(options: OpenSecureWindowOptions): Promise<OpenSecureWindowResponse>;\n\n /**\n * Opens a system auth session for generic OAuth/OIDC or enterprise SSO.\n *\n * Use this when you build the authorize URL yourself (or your IdP SDK returns one) and only need\n * the plugin to run the secure browser flow and return the redirect callback URL. Exchange the\n * authorization code or tokens on your backend or with your own client logic.\n *\n * **iOS/Android:** system browser session (`ASWebAuthenticationSession` / Chrome Custom Tabs).\n * **Web:** popup window plus `BroadcastChannel` (not a native browser session).\n *\n * On user cancel or dismiss, the Promise rejects with `code === 'USER_CANCELLED'`.\n *\n * @param options - auth session options\n */\n openAuthSession(options: OpenAuthSessionOptions): Promise<OpenAuthSessionResult>;\n}\n"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Configuration for a single OAuth2 provider instance\n */\nexport interface OAuth2ProviderConfig {\n /**\n * The OAuth 2.0 client identifier (App ID / Client ID).\n *\n * Note: this configuration object is only used by the plugin's built-in `oauth2` provider\n * (i.e. `SocialLogin.initialize({ oauth2: { ... } })`). It does not affect Google/Apple/Facebook/Twitter.\n * @example 'your-client-id'\n */\n appId?: string;\n /**\n * Alias for `appId` to match common OAuth/OIDC naming (`clientId`).\n * If both are provided, `appId` takes precedence.\n * @example 'your-client-id'\n */\n clientId?: string;\n /**\n * OpenID Connect issuer URL (enables discovery via `/.well-known/openid-configuration`).\n * When set, you may omit explicit endpoints like `authorizationBaseUrl` and `accessTokenEndpoint`.\n *\n * Notes:\n * - Explicit endpoints (authorization/token/logout) take precedence over discovered values.\n * - Discovery is supported for `oauth2` on Web, iOS, and Android.\n *\n * @example 'https://accounts.example.com'\n */\n issuerUrl?: string;\n /**\n * The base URL of the authorization endpoint\n * @example 'https://accounts.example.com/oauth2/authorize'\n */\n authorizationBaseUrl?: string;\n /**\n * Alias for `authorizationBaseUrl` (to match common OAuth/OIDC naming).\n * @example 'https://accounts.example.com/oauth2/authorize'\n */\n authorizationEndpoint?: string;\n /**\n * OAuth 2.0 client secret for token requests (e.g., when exchanging the code).\n * When provided, this value is sent using `clientSecretParamName` (default `client_secret`).\n */\n clientSecret?: string;\n /**\n * Override the client identifier parameter name used for authorization and token requests.\n * Some providers (e.g. TikTok) expect `client_key` instead of the default `client_id`.\n * @default 'client_id'\n */\n clientIdParamName?: string;\n /**\n * Override the client secret parameter name used for token requests.\n * Useful for providers that expect a different parameter name.\n * @default 'client_secret'\n */\n clientSecretParamName?: string;\n /**\n * The URL to exchange the authorization code for tokens\n * Required for authorization code flow\n * @example 'https://accounts.example.com/oauth2/token'\n */\n accessTokenEndpoint?: string;\n /**\n * Alias for `accessTokenEndpoint` (to match common OAuth/OIDC naming).\n * @example 'https://accounts.example.com/oauth2/token'\n */\n tokenEndpoint?: string;\n /**\n * Redirect URL that receives the OAuth callback\n * @example 'myapp://oauth/callback'\n */\n redirectUrl: string;\n /**\n * Optional URL to fetch user profile/resource data after authentication\n * The access token will be sent as Bearer token in the Authorization header\n * @example 'https://api.example.com/userinfo'\n */\n resourceUrl?: string;\n /**\n * The OAuth response type\n * - 'code': Authorization Code flow (recommended, requires accessTokenEndpoint)\n * - 'token': Implicit flow (less secure, tokens returned directly)\n * @default 'code'\n */\n responseType?: 'code' | 'token';\n /**\n * Enable PKCE (Proof Key for Code Exchange)\n * Strongly recommended for public clients (mobile/web apps)\n * @default true\n */\n pkceEnabled?: boolean;\n /**\n * Default scopes to request during authorization\n * @example 'openid profile email'\n * @example ['openid','profile','email']\n */\n scope?: string | string[];\n /**\n * Alias for `scope` using common naming (`scopes`).\n * If both are provided, `scope` takes precedence.\n */\n scopes?: string[];\n /**\n * Additional parameters to include in the authorization request\n * @example { prompt: 'consent', login_hint: 'user@example.com' }\n */\n additionalParameters?: Record<string, string>;\n /**\n * Convenience option for OIDC `login_hint`.\n * Equivalent to passing `additionalParameters.login_hint`.\n */\n loginHint?: string;\n /**\n * Convenience option for OAuth/OIDC `prompt`.\n * Equivalent to passing `additionalParameters.prompt`.\n */\n prompt?: string;\n /**\n * Additional parameters to include in token requests (code exchange / refresh).\n * Useful for providers that require non-standard parameters.\n */\n additionalTokenParameters?: Record<string, string>;\n /**\n * Additional headers to include when fetching the resource URL\n * @example { 'X-Custom-Header': 'value' }\n */\n additionalResourceHeaders?: Record<string, string>;\n /**\n * Custom logout URL for ending the session\n * @example 'https://accounts.example.com/logout'\n */\n logoutUrl?: string;\n /**\n * Alias for `logoutUrl` to match OIDC naming (`endSessionEndpoint`).\n * @example 'https://accounts.example.com/logout'\n */\n endSessionEndpoint?: string;\n /**\n * OIDC post logout redirect URL (sent as `post_logout_redirect_uri` when building the end-session URL).\n * @example 'myapp://logout/callback'\n */\n postLogoutRedirectUrl?: string;\n /**\n * Additional parameters to include in logout / end-session URL.\n */\n additionalLogoutParameters?: Record<string, string>;\n /**\n * iOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession.\n * Defaults to true to match existing behavior in this plugin.\n */\n iosPrefersEphemeralWebBrowserSession?: boolean;\n /**\n * Alias for `iosPrefersEphemeralWebBrowserSession` (to match Capawesome OAuth naming).\n */\n iosPrefersEphemeralSession?: boolean;\n /**\n * Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView\n * for the authorization request.\n *\n * Custom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered\n * IdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google\n * `disallowed_useragent`, SSO cookie sharing, password managers).\n *\n * Requires a custom-scheme or App Link `redirectUrl` with a matching intent filter in\n * your app's `AndroidManifest.xml` (same setup as `openSecureWindow()` / Apple on Android).\n *\n * Defaults to `false` to preserve the historical WebView flow.\n *\n * @default false\n * @example true\n */\n androidUseCustomTabs?: boolean;\n /**\n * Enable debug logging\n * @default false\n */\n logsEnabled?: boolean;\n}\n\n/**\n * LinkedIn provider configuration (convenience wrapper around the generic OAuth2 provider).\n *\n * Uses the OAuth2 engine with LinkedIn defaults:\n * - Authorization URL: https://www.linkedin.com/oauth/v2/authorization\n * - Token URL: https://www.linkedin.com/oauth/v2/accessToken\n * - Resource URL: https://api.linkedin.com/v2/userinfo\n * - Default scopes: `openid profile email`\n */\nexport interface LinkedInProviderConfig extends OAuth2ProviderConfig {\n /**\n * LinkedIn Client ID from the LinkedIn Developer Portal.\n */\n clientId: string;\n /**\n * Redirect URL that receives the OAuth callback.\n * Must match a redirect URL configured in the LinkedIn Developer Portal.\n * @example 'https://your-app.example/auth/linkedin'\n */\n redirectUrl: string;\n /**\n * LinkedIn Client Secret.\n *\n * Prefer exchanging the authorization code on a backend when possible.\n * Needed for confidential clients that do not use PKCE-only token exchange.\n */\n clientSecret?: string;\n}\n\n/**\n * TikTok Login Kit configuration (convenience wrapper around the generic OAuth2 provider).\n *\n * Uses TikTok OAuth 2.0 endpoints and `client_key` instead of `client_id`.\n * @see https://developers.tiktok.com/doc/login-kit-web\n */\nexport interface TikTokProviderConfig {\n /**\n * TikTok client key (also known as app key).\n * @example 'aw3y*****'\n */\n clientKey: string;\n /**\n * Redirect URL registered in your TikTok developer app.\n * @example 'myapp://auth/tiktok'\n */\n redirectUrl: string;\n /**\n * TikTok client secret. Optional.\n * When set, the plugin includes it on token and refresh requests.\n * On web this value is stored with the OAuth2 config.\n * Login always exchanges the authorization code in the plugin; the raw code is not returned to the app.\n */\n clientSecret?: string;\n /**\n * Scopes to request during login. Arrays are sent as a comma-separated string (TikTok Login Kit).\n * @default ['user.info.basic']\n * @example ['user.info.basic','video.list']\n */\n scopes?: string[];\n /**\n * Alias for `scopes`.\n */\n scope?: string | string[];\n /**\n * Toggle PKCE usage during the authorization code flow.\n * @default true\n */\n pkceEnabled?: boolean;\n /**\n * Enable verbose debug logging for the TikTok OAuth2 flow.\n * @default false\n */\n logsEnabled?: boolean;\n}\n\n/**\n * Options for `refreshToken()`.\n * `providerId` is required for generic `oauth2` and ignored for LinkedIn and TikTok.\n */\nexport type RefreshTokenOptions =\n | {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }\n | {\n provider: 'linkedin';\n providerId?: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }\n | {\n provider: 'tiktok';\n providerId?: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n };\n\nexport interface InitializeOptions {\n /**\n * OAuth2 provider configurations.\n * Supports multiple providers by using a Record with provider IDs as keys.\n * @example\n * {\n * github: { appId: '...', authorizationBaseUrl: 'https://github.com/login/oauth/authorize', ... },\n * azure: { appId: '...', authorizationBaseUrl: 'https://login.microsoftonline.com/.../oauth2/v2.0/authorize', ... }\n * }\n */\n oauth2?: Record<string, OAuth2ProviderConfig>;\n /**\n * Telegram Login Widget configuration.\n * Uses Telegram's OAuth widget (`oauth.telegram.org`), not standard OAuth2.\n */\n telegram?: {\n /**\n * Telegram bot ID (numeric, not the bot token).\n * @example '123456789'\n */\n botId: string;\n /**\n * Default redirect URL that will receive Telegram auth data.\n * For mobile apps, prefer a custom scheme (e.g. `myapp://telegram-auth`).\n * On iOS/Android this must be set here or per login; native login rejects if it is missing.\n */\n redirectUrl?: string;\n /**\n * Origin/domain registered for the Telegram login widget.\n * Required when `redirectUrl` is not `http`/`https` (for example a custom scheme like `myapp://telegram-auth`).\n * Defaults to the origin of `redirectUrl` only when that URL is already http(s).\n * @example 'https://example.com'\n */\n origin?: string;\n /**\n * Requested access level.\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n /**\n * Optional language code passed to Telegram (e.g. 'en', 'fr').\n */\n languageCode?: string;\n };\n /**\n * LinkedIn configuration.\n * Convenience wrapper that maps to the OAuth2 provider using LinkedIn defaults.\n */\n linkedin?: LinkedInProviderConfig;\n /**\n * TikTok Login Kit configuration.\n * Convenience wrapper that maps to the OAuth2 provider using TikTok defaults (`client_key`).\n */\n tiktok?: TikTokProviderConfig;\n twitter?: {\n /**\n * The OAuth 2.0 client identifier issued by X (Twitter) Developer Portal\n * @example 'Y2xpZW50SWQ'\n */\n clientId: string;\n /**\n * Redirect URL that is registered inside the X Developer Portal.\n * The plugin uses this URL on every platform to receive the authorization code.\n * @example 'myapp://auth/x'\n */\n redirectUrl: string;\n /**\n * Default scopes appended to every login request when no custom scopes are provided.\n * @description Defaults to the minimum required scopes for Log in with X.\n * @default ['tweet.read','users.read']\n */\n defaultScopes?: string[];\n /**\n * Force the consent screen to show on every login attempt.\n * Mirrors X's `force_login=true` flag.\n * @default false\n */\n forceLogin?: boolean;\n /**\n * Optional audience value when your application has been approved for multi-tenant access.\n */\n audience?: string;\n };\n facebook?: {\n /**\n * Facebook App ID, provided by Facebook for web, in mobile it's set in the native files\n * @description For business integrations, use your Business App ID from Facebook Developer Console.\n * Business apps can access additional permissions like Instagram API, Pages API, and business management features.\n * @see docs/facebook_business_login.md for business app setup guide\n */\n appId: string;\n /**\n * Facebook Client Token, provided by Facebook for web, in mobile it's set in the native files\n */\n clientToken?: string;\n /**\n * Locale\n * @description The locale to use for the Facebook SDK (e.g., 'en_US', 'fr_FR', 'es_ES')\n * @default 'en_US'\n * @example 'fr_FR'\n */\n locale?: string;\n };\n\n google?: {\n /**\n * The app's client ID, found and created in the Google Developers Console.\n * Required for iOS platform.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSClientId?: string;\n /**\n * The app's server client ID, required for offline mode on iOS.\n * Should be the same value as webClientId.\n * Found and created in the Google Developers Console.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSServerClientId?: string;\n /**\n * The app's web client ID, found and created in the Google Developers Console.\n * Required for Android and Web platforms.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n webClientId?: string;\n /**\n * The login mode, can be online or offline.\n *\n * **Online mode (default):**\n * - Returns user profile data and access tokens\n * - Supports all methods: login, logout, isLoggedIn, getAuthorizationCode\n *\n * **Offline mode:**\n * - Returns only serverAuthCode for backend authentication\n * - No user profile data available\n * - **Limitations:** The following methods are NOT supported in offline mode:\n * - `logout()` - Will reject with \"not implemented when using offline mode\"\n * - `isLoggedIn()` - Will reject with \"not implemented when using offline mode\"\n * - `getAuthorizationCode()` - Will reject with \"not implemented when using offline mode\"\n * - `refresh()` - Will reject because offline mode only returns `serverAuthCode`; token refresh must happen on your backend\n * - Only `login()` method works in offline mode, returning serverAuthCode only\n * - `serverAuthCode` must be exchanged on your backend for access/refresh tokens\n * - Requires `iOSServerClientId` to be set on iOS\n *\n * @example 'offline'\n * @default 'online'\n * @since 3.1.0\n */\n mode?: 'online' | 'offline';\n /**\n * Filter visible accounts by hosted domain\n * @description filter visible accounts by hosted domain\n */\n hostedDomain?: string;\n /**\n * Google Redirect URL, should be your backend url that is configured in your google app\n */\n redirectUrl?: string;\n /**\n * Android only. When `true`, skip `AuthorizationClient.authorize()` after Credential Manager sign-in\n * when `mode` is `online` and only default OIDC scopes are requested. Use this on stock `BridgeActivity`\n * apps that hit a hang during authorize; login may return `accessToken: null` while still returning\n * `idToken` and profile. When refresh runs past its early return (saved ID token expired or missing, or\n * access token validation failed or timed out), authentication-only scopes skip authorize, update the saved\n * `idToken`, and clear any saved access token.\n * Enabling this after a session still has valid saved tokens does not clear a stored access token when\n * refresh's early return applies: saved ID token valid and either no access token stored or validation\n * succeeds. Default `false` keeps prior behavior: authorize runs on login and refresh when needed, and\n * `accessToken` is returned when Google provides one. With default `false`, refresh still returns without\n * authorize when saved tokens are already valid, including when no access token is stored.\n *\n * @default false\n * @since 8.8.0\n */\n skipAuthOnlyAuthorizationAfterSignIn?: boolean;\n };\n apple?: {\n /**\n * Apple Client ID, provided by Apple for web and Android\n */\n clientId?: string;\n /**\n * Apple Redirect URL, should be your backend url that is configured in your apple app\n *\n * **Note**: Use empty string `''` for iOS to prevent redirect.\n * **Note**: Not required when using Broadcast Channel mode on Android.\n */\n redirectUrl?: string;\n /**\n * Use proper token exchange for Apple Sign-In\n * @description Controls how Apple Sign-In tokens are handled and what gets returned:\n *\n * **When `true` (Recommended for new implementations):**\n * - Exchanges authorization code for proper access tokens via Apple's token endpoint\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: Proper access token from Apple (short-lived, ~1 hour)\n * - `authorizationCode`: Raw authorization code for backend token exchange\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses authorization code directly as access token for backward compatibility\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: The authorization code itself (not a real access token)\n * - `authorizationCode`: undefined\n *\n * @default false\n * @example\n * // Enable proper token exchange (recommended)\n * useProperTokenExchange: true\n * // Result: idToken=JWT, accessToken=real_token, authorizationCode=present\n *\n * // Legacy mode (backward compatibility)\n * useProperTokenExchange: false\n * // Result: idToken=JWT, accessToken=auth_code, authorizationCode=undefined\n */\n useProperTokenExchange?: boolean;\n /**\n * Use Broadcast Channel for Android Apple Sign-In (Recommended)\n * @description When enabled, Android uses Broadcast Channel API instead of URL redirects.\n * This eliminates the need for redirect URL configuration and server-side setup.\n *\n * **Benefits:**\n * - No redirect URL configuration required\n * - No backend server needed for Android\n * - Simpler setup and more reliable communication\n * - Direct client-server communication via Broadcast Channel\n *\n * **When `true`:**\n * - Uses Broadcast Channel for authentication flow\n * - `redirectUrl` is ignored\n * - Requires Broadcast Channel compatible backend or direct token handling\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses traditional URL redirect flow\n * - Requires `redirectUrl` configuration\n * - Requires backend server for token exchange\n *\n * @default false\n * @since 7.10.0\n * @example\n * // Enable Broadcast Channel mode (recommended for new Android implementations)\n * useBroadcastChannel: true\n * // Result: Simplified setup, no redirect URL needed\n *\n * // Legacy mode (backward compatibility)\n * useBroadcastChannel: false\n * // Result: Traditional URL redirect flow with server-side setup\n */\n useBroadcastChannel?: boolean;\n };\n}\n\nexport interface FacebookLoginOptions {\n /**\n * Permissions\n * @description Select permissions to login with. Supports both consumer and business permissions.\n *\n * **Consumer Permissions:**\n * - `email` - User's email address\n * - `public_profile` - User's public profile info\n * - `user_friends` - List of friends who also use your app\n *\n * **Business Permissions** (require business app configuration and may need App Review):\n * - `instagram_basic` - Instagram Basic Display API access\n * - `instagram_manage_insights` - Instagram Insights data\n * - `instagram_manage_comments` - Manage Instagram comments\n * - `instagram_content_publish` - Publish to Instagram\n * - `pages_show_list` - List of Pages managed by user\n * - `pages_read_engagement` - Read Page engagement metrics\n * - `pages_manage_posts` - Manage Page posts\n * - `pages_messaging` - Page messaging features\n * - `business_management` - Manage business assets\n * - `catalog_management` - Manage product catalogs\n * - `ads_management` - Manage advertising accounts\n *\n * @example ['email', 'public_profile'] // Consumer permissions\n * @example ['email', 'instagram_basic', 'pages_show_list'] // Business permissions\n * @see https://developers.facebook.com/docs/permissions/reference\n * @see docs/facebook_business_login.md for complete business integration guide\n */\n permissions: string[];\n /**\n * Is Limited Login\n * @description use limited login for Facebook iOS only. Important: This is iOS-only and doesn't affect Android.\n * Even if set to false, Facebook will automatically force it to true if App Tracking Transparency (ATT) permission is not granted.\n * Developers should always be prepared to handle both limited and full login scenarios.\n * @default false\n */\n limitedLogin?: boolean;\n /**\n * Nonce\n * @description A custom nonce to use for the login request\n */\n nonce?: string;\n}\n\nexport interface TwitterLoginOptions {\n /**\n * Additional scopes to request during login.\n * If omitted the plugin falls back to the default scopes configured during initialization.\n * @example ['tweet.read','users.read','offline.access']\n */\n scopes?: string[];\n /**\n * Provide a custom OAuth state value.\n * When not provided the plugin generates a cryptographically random value.\n */\n state?: string;\n /**\n * Provide a pre-computed PKCE code verifier (mostly used for testing).\n * When omitted the plugin generates a secure verifier automatically.\n */\n codeVerifier?: string;\n /**\n * Override the redirect URI for a single login call.\n * Useful when the same app supports multiple callback URLs per platform.\n */\n redirectUrl?: string;\n /**\n * Force the consent screen on every attempt, maps to `force_login=true`.\n */\n forceLogin?: boolean;\n}\n\nexport interface TelegramLoginOptions {\n /**\n * Override the redirect URL for this login attempt.\n * Defaults to the redirect configured during initialize().\n * Required on iOS/Android when initialize() did not set `redirectUrl`.\n */\n redirectUrl?: string;\n /**\n * Optional state parameter for CSRF protection.\n * If omitted, a secure random value is generated automatically.\n */\n state?: string;\n /**\n * Override requested access level for this login.\n * Defaults to the value configured during initialize().\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n}\n\nexport interface OAuth2LoginOptions {\n /**\n * The provider ID as configured in initialize()\n * This is required to identify which OAuth2 provider to use\n * @example 'github', 'azure', 'keycloak'\n */\n providerId: string;\n /**\n * Override the scopes for this login request\n * If not provided, uses the scopes from initialization\n */\n scope?: string | string[];\n /**\n * Alias for `scope` using common naming (`scopes`).\n * If both are provided, `scope` takes precedence.\n */\n scopes?: string[];\n /**\n * Custom state parameter for CSRF protection\n * If not provided, a random value is generated\n */\n state?: string;\n /**\n * Override PKCE code verifier (for testing purposes)\n * If not provided, a secure random verifier is generated\n */\n codeVerifier?: string;\n /**\n * Override redirect URL for this login request\n */\n redirectUrl?: string;\n /**\n * Additional parameters to add to the authorization URL\n */\n additionalParameters?: Record<string, string>;\n /**\n * Convenience option for OIDC `login_hint`.\n * Equivalent to passing `additionalParameters.login_hint`.\n */\n loginHint?: string;\n /**\n * Convenience option for OAuth/OIDC `prompt`.\n * Equivalent to passing `additionalParameters.prompt`.\n */\n prompt?: string;\n /**\n * Web-only (`oauth2` provider only): Use a full-page redirect instead of a popup window.\n *\n * When using `redirect`, the promise returned by `login()` will not resolve because the page navigates away.\n * After the redirect lands back in your app, call `SocialLogin.handleRedirectCallback()` on that page to\n * parse the result.\n *\n * @default 'popup'\n */\n flow?: 'popup' | 'redirect';\n}\n\n/**\n * LinkedIn login options (maps to the OAuth2 provider internally).\n * `providerId` is set to `linkedin` automatically.\n */\nexport type LinkedInLoginOptions = Omit<OAuth2LoginOptions, 'providerId'>;\n\nexport interface TikTokLoginOptions {\n /**\n * Optional scopes to override the initialization scopes.\n * @example ['user.info.basic']\n */\n scopes?: string[];\n /**\n * Alias for `scopes`.\n */\n scope?: string | string[];\n /**\n * Custom state parameter for CSRF protection.\n */\n state?: string;\n /**\n * Custom PKCE code verifier (mostly for testing).\n */\n codeVerifier?: string;\n /**\n * Override redirect URL for this login request.\n */\n redirectUrl?: string;\n}\n\nexport interface OAuth2LoginResponse {\n /**\n * The provider ID that was used for this login\n */\n providerId: string;\n /**\n * The access token received from the OAuth provider\n */\n accessToken: AccessToken | null;\n /**\n * The ID token (JWT) if provided by the OAuth server (e.g., OpenID Connect)\n */\n idToken: string | null;\n /**\n * The refresh token if provided (requires appropriate scope like offline_access)\n */\n refreshToken: string | null;\n /**\n * Resource data fetched from resourceUrl if configured\n * Contains the raw JSON response from the resource endpoint\n */\n resourceData: Record<string, unknown> | null;\n /**\n * The scopes that were granted\n */\n scope: string[];\n /**\n * Token type (usually 'bearer')\n */\n tokenType: string;\n /**\n * Token expiration time in seconds\n */\n expiresIn: number | null;\n}\n\n/**\n * LinkedIn login response (returned when using the LinkedIn convenience API).\n */\nexport type LinkedInLoginResponse = OAuth2LoginResponse;\n\n/**\n * TikTok login response (same shape as generic OAuth2).\n */\nexport type TikTokLoginResponse = OAuth2LoginResponse;\n\nexport interface GoogleLoginOptions {\n /**\n * Specifies the scopes required for accessing Google APIs\n * The default is defined in the configuration.\n * @example [\"profile\", \"email\"]\n * @see [Google OAuth2 Scopes](https://developers.google.com/identity/protocols/oauth2/scopes)\n */\n scopes?: string[];\n /**\n * Nonce. On iOS, a login with a nonce always shows the Google sign-in instead of restoring the\n * previous sign-in: a restored ID token was minted without this nonce, so a backend that verifies\n * it (for example Supabase `signInWithIdToken`) would reject the token.\n * @description nonce\n */\n nonce?: string;\n /**\n * Force refresh token (only for Android)\n * @description force refresh token\n * @default false\n * @note On Android, the OS caches access tokens, and if a token is invalid (e.g., user revoked app access), the plugin might return an invalid accessToken. Using getAuthorizationCode() is recommended to ensure the token is valid.\n */\n forceRefreshToken?: boolean;\n /**\n * Force account selection prompt (iOS)\n * @description forces the account selection prompt to appear on iOS\n * @default false\n */\n forcePrompt?: boolean;\n /**\n * Style\n * @description style\n * @default 'standard'\n */\n style?: 'bottom' | 'standard';\n /**\n * Filter by authorized accounts (Android only)\n * @description Only show accounts that have previously been used to sign in to the app.\n * This option is only available for the 'bottom' style.\n * Note: For Family Link supervised accounts, this should be set to false.\n * @default false\n */\n filterByAuthorizedAccounts?: boolean;\n /**\n * Auto select enabled (Android only)\n * @description Automatically select the account if only one Google account is available.\n * This option is only available for the 'bottom' style.\n * @default false\n */\n autoSelectEnabled?: boolean;\n /**\n * Prompt parameter for Google OAuth (Web only)\n * @description A space-delimited, case-sensitive list of prompts to present the user.\n * If you don't specify this parameter, the user will be prompted only the first time your project requests access.\n *\n * **Possible values:**\n * - `none`: Don't display any authentication or consent screens. Must not be specified with other values.\n * - `consent`: Prompt the user for consent.\n * - `select_account`: Prompt the user to select an account.\n *\n * **Examples:**\n * - `prompt: 'consent'` - Always show consent screen\n * - `prompt: 'select_account'` - Always show account selection\n * - `prompt: 'consent select_account'` - Show both consent and account selection\n *\n * **Note:** This parameter only affects web platform behavior. Mobile platforms use their own native prompts.\n *\n * @example 'consent'\n * @example 'select_account'\n * @example 'consent select_account'\n * @see [Google OAuth2 Prompt Parameter](https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt)\n * @since 7.12.0\n */\n prompt?: 'none' | 'consent' | 'select_account' | 'consent select_account' | 'select_account consent';\n}\n\nexport interface GoogleLoginResponseOnline {\n /**\n * OAuth access token for Google APIs.\n *\n * May be `null` on Android when AuthorizationClient does not return an access token, or when\n * `skipAuthOnlyAuthorizationAfterSignIn` is enabled during initialize (opt-in). Use `idToken`\n * for user authentication; request additional Google API scopes when an access token is required.\n */\n accessToken: AccessToken | null;\n /**\n * OpenID Connect ID token (JWT).\n *\n * Includes an `email_verified` claim when the `email` scope is granted. Use\n * `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but\n * always verify the token signature, `iss`, `aud`, and `exp` on your backend\n * before trusting `email_verified` for account linking.\n *\n * @see https://developers.google.com/identity/gsi/web/guides/verify-google-id-token\n */\n idToken: string | null;\n profile: {\n /**\n * Email from the ID token payload. Does not include a separate verification flag;\n * check `idToken` claims (`email_verified`) for whether Google attests the address.\n */\n email: string | null;\n familyName: string | null;\n givenName: string | null;\n id: string | null;\n name: string | null;\n imageUrl: string | null;\n };\n responseType: 'online';\n}\n\nexport interface GoogleLoginResponseOffline {\n serverAuthCode: string;\n responseType: 'offline';\n}\n\nexport type GoogleLoginResponse = GoogleLoginResponseOnline | GoogleLoginResponseOffline;\n\nexport interface AppleProviderOptions {\n /**\n * Scopes\n * @description An array of scopes to request during login\n * @example [\"name\", \"email\"]\n * default: [\"name\", \"email\"]\n */\n scopes?: string[];\n /**\n * Nonce\n * @description nonce\n */\n nonce?: string;\n /**\n * State\n * @description state\n */\n state?: string;\n /**\n * Use Broadcast Channel for authentication flow\n * @description When enabled, uses Broadcast Channel API for communication instead of URL redirects.\n * Only applicable on platforms that support Broadcast Channel (Android).\n * @default false\n */\n useBroadcastChannel?: boolean;\n}\n\nexport interface AppleProviderResponse {\n /**\n * Access token from Apple\n * @description Content depends on `useProperTokenExchange` setting:\n * - When `useProperTokenExchange: true`: Real access token from Apple (~1 hour validity)\n * - When `useProperTokenExchange: false`: Contains authorization code as token (legacy mode)\n * Use `idToken` for user authentication, `accessToken` for API calls when properly exchanged.\n */\n accessToken: AccessToken | null;\n\n /**\n * Identity token (JWT) from Apple.\n *\n * Includes standard OIDC claims such as `sub`, `email` (when granted), and\n * `email_verified` (boolean). Apple sets `email_verified` to `true` when it\n * attests the user controls the email (including Hide My Email relay addresses).\n *\n * Use `SocialLogin.decodeIdToken({ idToken })` to read claims on the client, but\n * verify the token signature, `iss`, `aud`, and `exp` on your backend before\n * trusting `email_verified` for account linking.\n *\n * @see https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\n */\n idToken: string | null;\n\n /**\n * User profile information\n * @description Basic user profile data extracted from the identity token and Apple response:\n * - `user`: Apple's user identifier (sub claim from idToken)\n * - `email`: User's email address (if permission granted)\n * - `givenName`: User's first name (if permission granted)\n * - `familyName`: User's last name (if permission granted)\n */\n profile: {\n user: string;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n };\n\n /**\n * Authorization code for proper token exchange (when useProperTokenExchange is enabled)\n * @description Only present when `useProperTokenExchange` is `true`. This code should be exchanged\n * for proper access tokens on your backend using Apple's token endpoint. Use this for secure\n * server-side token validation and to obtain refresh tokens.\n * @see https://developer.apple.com/documentation/sign_in_with_apple/tokenresponse\n */\n authorizationCode?: string;\n}\n\nexport type LoginOptions =\n | {\n provider: 'facebook';\n options: FacebookLoginOptions;\n }\n | {\n provider: 'google';\n options: GoogleLoginOptions;\n }\n | {\n provider: 'apple';\n options: AppleProviderOptions;\n }\n | {\n provider: 'twitter';\n options: TwitterLoginOptions;\n }\n | {\n provider: 'telegram';\n options: TelegramLoginOptions;\n }\n | {\n provider: 'linkedin';\n options: LinkedInLoginOptions;\n }\n | {\n provider: 'tiktok';\n options: TikTokLoginOptions;\n }\n | {\n provider: 'oauth2';\n options: OAuth2LoginOptions;\n };\n\nexport type LoginResult =\n | {\n provider: 'facebook';\n result: FacebookLoginResponse;\n }\n | {\n provider: 'google';\n result: GoogleLoginResponse;\n }\n | {\n provider: 'apple';\n result: AppleProviderResponse;\n }\n | {\n provider: 'twitter';\n result: TwitterLoginResponse;\n }\n | {\n provider: 'telegram';\n result: TelegramLoginResponse;\n }\n | {\n provider: 'linkedin';\n result: LinkedInLoginResponse;\n }\n | {\n provider: 'tiktok';\n result: TikTokLoginResponse;\n }\n | {\n provider: 'oauth2';\n result: OAuth2LoginResponse;\n };\n\nexport interface AccessToken {\n applicationId?: string;\n declinedPermissions?: string[];\n expires?: string;\n isExpired?: boolean;\n lastRefresh?: string;\n permissions?: string[];\n token: string;\n tokenType?: string;\n refreshToken?: string;\n userId?: string;\n}\n\nexport interface FacebookLoginResponse {\n accessToken: AccessToken | null;\n /**\n * Whether Facebook Limited Login was used for this session.\n * When `true`, `accessToken` is not valid for Graph API calls (Facebook error 190).\n * Validate `idToken` on your backend instead, or call `facebook#requestTracking` and log in again after ATT is granted.\n * @since 8.4.0\n */\n isLimitedLogin?: boolean;\n /**\n * OpenID Connect ID token (JWT) from Meta Limited Login (iOS native, when available).\n *\n * **Not equivalent to Google/Apple `email_verified`:** Meta's OIDC token may include\n * an `email` claim (when the `email` permission is granted) but does **not** publish an\n * `email_verified` claim like Google or Apple. Meta documents the value as the user's\n * primary account email, not as an OIDC-verified email assertion.\n *\n * On Android and Web this is usually `null` (Graph API access token flow instead).\n * Validate signature, `iss` (`https://www.facebook.com` or `https://limited.facebook.com`),\n * `aud`, `exp`, and nonce on your backend. Do not infer `email_verified: true` from the\n * presence of `email` alone when linking accounts across providers.\n *\n * @see https://developers.facebook.com/docs/facebook-login/limited-login/token/validating/\n */\n idToken: string | null;\n profile: {\n userID: string;\n /**\n * Primary email from the Meta profile / Graph API (`/me?fields=email`).\n *\n * **Not equivalent to Google/Apple `email_verified`:** this field has no verification\n * flag. Meta returns the account's primary email when the `email` permission is\n * granted; it does not expose an `email_verified` boolean comparable to Google or\n * Apple ID tokens. Treat this as an identifier hint only—verify ownership yourself\n * (e.g. magic link) before linking Meta sign-in to Google/Apple accounts by email.\n */\n email: string | null;\n friendIDs: string[];\n birthday: string | null;\n ageRange: { min?: number; max?: number } | null;\n gender: string | null;\n location: { id: string; name: string } | null;\n hometown: { id: string; name: string } | null;\n profileURL: string | null;\n name: string | null;\n imageURL: string | null;\n };\n}\n\nexport interface TwitterProfile {\n id: string;\n username: string;\n name: string | null;\n profileImageUrl: string | null;\n verified: boolean;\n email?: string | null;\n}\n\nexport interface TwitterLoginResponse {\n accessToken: AccessToken | null;\n refreshToken?: string | null;\n scope: string[];\n tokenType: 'bearer';\n expiresIn?: number | null;\n profile: TwitterProfile;\n}\n\nexport interface TelegramProfile {\n id: string;\n firstName: string;\n lastName?: string | null;\n username?: string | null;\n photoUrl?: string | null;\n}\n\nexport interface TelegramLoginResponse {\n profile: TelegramProfile;\n /**\n * Unix timestamp (seconds) when the user authorized the login.\n */\n authDate: number;\n /**\n * Telegram-provided hash for server-side verification.\n */\n hash: string;\n /**\n * Requested access level that was used for this login.\n */\n requestAccess: 'read' | 'write';\n}\n\nexport interface AuthorizationCode {\n /**\n * Jwt\n * @description A JSON web token\n */\n jwt?: string;\n /**\n * Access Token\n * @description An access token\n */\n accessToken?: string;\n}\n\nexport interface AuthorizationCodeOptions {\n /**\n * Provider\n * @description Provider for the authorization code\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'linkedin' | 'tiktok' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\nexport interface isLoggedInOptions {\n /**\n * Provider\n * @description Provider for the isLoggedIn\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'linkedin' | 'tiktok' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\n// Define the provider-specific call types\n/**\n * Options for `providerSpecificCall` with `google#createRestoreCredential`.\n *\n * Android-only. Creates a Restore Credential (restore key) via Credential Manager after the user\n * signs in. Your backend must supply WebAuthn PublicKeyCredentialCreationOptionsJSON (the same\n * FIDO2/passkey registration flow used for passkeys).\n *\n * @see https://developer.android.com/identity/sign-in/restore-credentials\n * @since 8.5.0\n */\nexport interface GoogleCreateRestoreCredentialOptions {\n /**\n * Credential creation options from your server in WebAuthn PublicKeyCredentialCreationOptionsJSON format.\n */\n requestJson: string;\n /**\n * When `true` (default), the restore key is backed up to the cloud when the user has backup and\n * end-to-end encryption (e.g. screen lock) enabled. If cloud backup creation fails with\n * `E2eeUnavailableException` on Android, the plugin automatically retries with local-only storage.\n * @default true\n */\n isCloudBackupEnabled?: boolean;\n}\n\n/**\n * Response from `google#createRestoreCredential`.\n *\n * Send `responseJson` to your server to complete restore key registration (same as passkey creation).\n */\nexport interface GoogleCreateRestoreCredentialResponse {\n /** Public key credential registration response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/**\n * Options for `providerSpecificCall` with `google#getRestoreCredential`.\n *\n * Android-only. Retrieves a Restore Credential silently (e.g. on first launch on a new device or from\n * BackupAgent `onRestoreFinished`). Your backend must supply WebAuthn authentication request JSON.\n */\nexport interface GoogleGetRestoreCredentialOptions {\n /**\n * Credential request options from your server (WebAuthn authentication request JSON).\n */\n requestJson: string;\n}\n\n/**\n * Response from `google#getRestoreCredential`.\n *\n * Send `responseJson` to your server to sign the user in (same server path as passkey authentication).\n */\nexport interface GoogleGetRestoreCredentialResponse {\n /** Restore credential authentication response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/** Options for `google#clearRestoreCredential` (no fields). */\nexport type GoogleClearRestoreCredentialOptions = Record<string, never>;\n\n/** Response from `google#clearRestoreCredential`. */\nexport interface GoogleClearRestoreCredentialResponse {\n /** Whether the restore credential clear request completed successfully. */\n cleared: boolean;\n}\n\nexport type ProviderSpecificCall =\n | 'facebook#getProfile'\n | 'facebook#requestTracking'\n | 'google#createRestoreCredential'\n | 'google#getRestoreCredential'\n | 'google#clearRestoreCredential';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile.\n * @default ['id', 'name', 'email', 'picture']\n * @example [\"id\", \"name\", \"email\", \"picture\"]\n */\n fields?: string[];\n}\n\nexport interface FacebookGetProfileResponse {\n /**\n * Facebook profile data\n */\n profile: {\n id: string | null;\n name: string | null;\n email: string | null;\n first_name: string | null;\n last_name: string | null;\n picture?: {\n data: {\n height: number | null;\n is_silhouette: boolean | null;\n url: string | null;\n width: number | null;\n };\n } | null;\n [key: string]: any; // For additional fields that might be requested\n };\n}\n\nexport interface OpenSecureWindowOptions {\n /**\n * The endpoint to open\n */\n authEndpoint: string;\n /**\n * The redirect URI to use for the openSecureWindow call.\n * This will be checked to make sure it matches the redirect URI after the window finishes the redirection.\n */\n redirectUri: string;\n /**\n * The name of the broadcast channel to listen to, relevant only for web\n */\n broadcastChannelName?: string;\n}\n\nexport interface OpenSecureWindowResponse {\n /**\n * The result of the openSecureWindow call\n */\n redirectedUri: string;\n}\n\nexport interface OpenAuthSessionOptions {\n /**\n * Authorization or login URL to open in the system browser session (OAuth/OIDC authorize endpoint, SSO login page, etc.).\n * @example 'https://login.example.com/oauth2/authorize?client_id=...&redirect_uri=...&state=...'\n */\n url: string;\n /**\n * Custom URL scheme that receives the redirect (without `://`).\n * Must match the scheme in your registered redirect URI and native URL handler (iOS/Android).\n * On Web, the plugin also accepts HTTPS redirect URLs when `redirect_uri` is present in `url`, or messages prefixed with `${callbackURLScheme}://` on the BroadcastChannel.\n * @example 'myapp'\n */\n callbackURLScheme: string;\n /**\n * iOS-only: prefer an ephemeral `ASWebAuthenticationSession` (no shared cookies with Safari).\n * Defaults to `false` so SSO cookies in the system browser can be reused.\n */\n prefersEphemeralSession?: boolean;\n /**\n * Web-only: `BroadcastChannel` name used by the redirect page to post the callback URL back to the app.\n * @default 'capgo-auth-session'\n */\n broadcastChannelName?: string;\n}\n\nexport interface OpenAuthSessionResult {\n /**\n * Full redirect URI returned by the identity provider, including query or fragment (e.g. `myapp://auth/callback?code=...&state=...`).\n */\n callbackURL: string;\n}\n\nexport type FacebookRequestTrackingOptions = Record<string, never>;\n\nexport interface FacebookRequestTrackingResponse {\n /**\n * App tracking authorization status\n */\n status: 'authorized' | 'denied' | 'notDetermined' | 'restricted';\n}\n\n// Map call strings to their options and response types\nexport type ProviderSpecificCallOptionsMap = {\n 'facebook#getProfile': FacebookGetProfileOptions;\n 'facebook#requestTracking': FacebookRequestTrackingOptions;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialOptions;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialOptions;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialOptions;\n};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialResponse;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialResponse;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialResponse;\n};\n\n// Add a helper type to map providers to their response types\nexport type ProviderResponseMap = {\n facebook: FacebookLoginResponse;\n google: GoogleLoginResponse;\n apple: AppleProviderResponse;\n twitter: TwitterLoginResponse;\n telegram: TelegramLoginResponse;\n linkedin: LinkedInLoginResponse;\n tiktok: TikTokLoginResponse;\n oauth2: OAuth2LoginResponse;\n};\n\n/**\n * Error codes returned by the plugin.\n * @since 8.3.x\n */\nexport type SocialLoginErrorCode = 'USER_CANCELLED';\n\n/**\n * Errors thrown by SocialLogin methods.\n *\n * When a user dismisses or cancels the provider UI (popup closed, system dialog cancelled, access denied, etc.),\n * the plugin rejects with `code === 'USER_CANCELLED'` so the caller can distinguish user intent from real failures.\n * Other errors may omit the code or use provider-specific values.\n */\nexport interface SocialLoginError extends Error {\n code?: SocialLoginErrorCode | string;\n}\n\nexport interface SocialLoginPlugin {\n /**\n * Initialize the plugin\n * @description initialize the plugin with the required options\n */\n initialize(options: InitializeOptions): Promise<void>;\n /**\n * Login with the selected provider\n * @description login with the selected provider\n *\n * On user dismissal/cancellation, the Promise is rejected with `code === 'USER_CANCELLED'` (see `SocialLoginError`).\n */\n login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }>;\n /**\n * Logout\n * @description Logout the user from the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"logout is not implemented when using offline mode\"\n *\n * **Google Restore Credentials (Android):**\n * When logging out from Google, the plugin also clears any stored Restore Credential\n * (`google#clearRestoreCredential`) in addition to Credential Manager sign-in state.\n *\n * **Apple cached name (iOS):**\n * The plugin keeps the name Apple returns only on the first authorization, and logging out\n * keeps it. Pass `clearCachedUserInfo: true` to remove it too, for example on account deletion.\n *\n * @throws Error if Google provider is in offline mode\n */\n logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'linkedin' | 'tiktok' | 'oauth2';\n providerId?: string;\n /**\n * Apple on iOS: also remove the first and family name the plugin keeps on the device. Apple\n * returns the name only on the first authorization, so the plugin caches it to fill `givenName`\n * and `familyName` on later logins. Pass `true` when the user deletes their account, or should\n * otherwise leave no trace on the device. The name is removed even if no Apple session is held.\n * Ignored by other providers and platforms.\n * @default false\n */\n clearCachedUserInfo?: boolean;\n }): Promise<void>;\n /**\n * IsLoggedIn\n * @description Check if the user is currently logged in with the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"isLoggedIn is not implemented when using offline mode\"\n *\n * @throws Error if Google provider is in offline mode\n */\n isLoggedIn(options: isLoggedInOptions): Promise<{ isLoggedIn: boolean }>;\n\n /**\n * Get the current authorization code\n * @description Get the authorization code for server-side authentication\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"getAuthorizationCode is not implemented when using offline mode\"\n *\n * In offline mode, the authorization code (serverAuthCode) is already returned by the `login()` method.\n *\n * Telegram login does not produce an authorization code; use the `hash` from `login()` and verify it on your backend.\n *\n * @throws Error if Google provider is in offline mode\n */\n getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode>;\n /**\n * Refresh the access token for the logged-in provider.\n *\n * **Google Android refresh behavior:**\n * On Android, when the saved ID token is still valid and either no access token is stored or Google access\n * token validation succeeds within the timeout, `refresh()` resolves without updating either token. That\n * early return applies regardless of `skipAuthOnlyAuthorizationAfterSignIn`.\n * If validation fails or times out, `refresh()` continues even when a token remains stored; with\n * `skipAuthOnlyAuthorizationAfterSignIn: true` and default OIDC scopes, a successful credential refresh\n * then clears that access token without obtaining a new one.\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * Offline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.\n * The plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,\n * refresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.\n *\n * **Google Android `skipAuthOnlyAuthorizationAfterSignIn`:**\n * When initialize sets `google.skipAuthOnlyAuthorizationAfterSignIn: true` and only default OIDC scopes are\n * requested, a refresh that runs past the early return skips `AuthorizationClient.authorize()`, updates the\n * saved `idToken`, and clears any saved access token; no new access token is obtained. Enabling the option\n * does not clear a stored access token while the early return applies (validation succeeded or no token\n * stored). With default `false`, refresh still skips authorize on the early return when no access token is\n * stored but the ID token is valid.\n *\n * **Google Web Limitation:**\n * On Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.\n * Call `login()` again on Web to obtain a fresh token instead.\n *\n * @throws Error if Google provider is in offline mode, or on Web where Google `refresh()` is not implemented\n */\n refresh(options: LoginOptions): Promise<void>;\n\n /**\n * OAuth2 refresh-token helper (feature parity with Capawesome OAuth).\n *\n * Scope:\n * - Applies to the built-in `oauth2` provider and the LinkedIn and TikTok convenience wrappers.\n * - Requires a token endpoint (either `accessTokenEndpoint`/`tokenEndpoint` or `issuerUrl` discovery).\n *\n * Security note:\n * - This does not validate JWT signatures. It only exchanges/refreshes tokens.\n *\n * If `refreshToken` is omitted, the plugin will attempt to use the stored refresh token (if available).\n */\n refreshToken(options: RefreshTokenOptions): Promise<OAuth2LoginResponse>;\n\n /**\n * Web-only: handle the OAuth redirect callback and return the parsed result.\n *\n * Notes:\n * - This is only meaningful on Web. iOS/Android implementations will reject.\n * - Intended for redirect-based flows (e.g. `oauth2` with `flow: 'redirect'`) where the page navigates away.\n * - LinkedIn convenience logins (`provider: 'linkedin'`, `flow: 'redirect'`) return `provider: 'linkedin'`.\n * The same app used as `oauth2` with `providerId: 'linkedin'` keeps `provider: 'oauth2'`.\n */\n handleRedirectCallback(): Promise<LoginResult | null>;\n\n /**\n * Decode a JWT (typically an OIDC ID token) into its claims.\n *\n * Notes:\n * - Accepts both `idToken` and `token` to match common naming (Capawesome uses `token`).\n * - This does not validate the signature or issuer/audience. It only base64url-decodes the payload.\n *\n * **`email_verified` semantics by provider (for account linking):**\n * - **Google** — ID token includes `email_verified` (boolean). When `true`, Google attests\n * the user controls that email. Verify the JWT on your backend before trusting it.\n * - **Apple** — ID token includes `email_verified` (boolean). When `true`, Apple attests\n * the user controls that email (including private relay). Verify the JWT on your backend.\n * - **Meta (Facebook)** — Limited Login OIDC tokens may include `email` but **do not**\n * include `email_verified`. The presence of `email` is not the same guarantee as\n * `email_verified: true` from Google or Apple. Do not link accounts by email across\n * providers using Meta claims alone; perform your own email verification if needed.\n */\n decodeIdToken(options: { idToken?: string; token?: string }): Promise<{ claims: Record<string, any> }>;\n\n /**\n * Convert an access token expiration timestamp (milliseconds since epoch) to an ISO date string.\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n getAccessTokenExpirationDate(options: {\n /**\n * Access token expiration date in milliseconds since epoch.\n * Typically: `Date.now() + expiresInSeconds * 1000`.\n */\n accessTokenExpirationDate: number;\n }): Promise<{ date: string }>;\n\n /**\n * Check if an access token is available (non-empty).\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isAccessTokenAvailable(options: { accessToken: string | null }): Promise<{ isAvailable: boolean }>;\n\n /**\n * Check if an access token is expired.\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isAccessTokenExpired(options: { accessTokenExpirationDate: number }): Promise<{ isExpired: boolean }>;\n\n /**\n * Check if a refresh token is available (non-empty).\n *\n * This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.\n */\n isRefreshTokenAvailable(options: { refreshToken: string | null }): Promise<{ isAvailable: boolean }>;\n\n /**\n * Execute provider-specific calls\n * @description Execute a provider-specific functionality\n */\n providerSpecificCall<T extends ProviderSpecificCall>(options: {\n call: T;\n options: ProviderSpecificCallOptionsMap[T];\n }): Promise<ProviderSpecificCallResponseMap[T]>;\n\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Opens a secured window for OAuth2 authentication.\n * For web, you should have the code in the redirected page to use a broadcast channel to send the redirected url to the app\n * Something like:\n * ```html\n * <html>\n * <head></head>\n * <body>\n * <script>\n * const searchParams = new URLSearchParams(location.search)\n * if (searchParams.has(\"code\")) {\n * new BroadcastChannel(\"my-channel-name\").postMessage(location.href);\n * window.close();\n * }\n * </script>\n * </body>\n * </html>\n * ```\n * For mobile, you should have a redirect uri that opens the app, something like: `myapp://oauth_callback/`\n * And make sure to register it in the app's info.plist:\n * ```xml\n * <key>CFBundleURLTypes</key>\n * <array>\n * <dict>\n * <key>CFBundleURLSchemes</key>\n * <array>\n * <string>myapp</string>\n * </array>\n * </dict>\n * </array>\n * ```\n * And in the AndroidManifest.xml file:\n * ```xml\n * <activity>\n * <intent-filter>\n * <action android:name=\"android.intent.action.VIEW\" />\n * <category android:name=\"android.intent.category.DEFAULT\" />\n * <category android:name=\"android.intent.category.BROWSABLE\" />\n * <data android:host=\"oauth_callback\" android:scheme=\"myapp\" />\n * </intent-filter>\n * </activity>\n * ```\n * @param options - the options for the openSecureWindow call\n */\n openSecureWindow(options: OpenSecureWindowOptions): Promise<OpenSecureWindowResponse>;\n\n /**\n * Opens a system auth session for generic OAuth/OIDC or enterprise SSO.\n *\n * Use this when you build the authorize URL yourself (or your IdP SDK returns one) and only need\n * the plugin to run the secure browser flow and return the redirect callback URL. Exchange the\n * authorization code or tokens on your backend or with your own client logic.\n *\n * **iOS/Android:** system browser session (`ASWebAuthenticationSession` / Chrome Custom Tabs).\n * **Web:** popup window plus `BroadcastChannel` (not a native browser session).\n *\n * On user cancel or dismiss, the Promise rejects with `code === 'USER_CANCELLED'`.\n *\n * @param options - auth session options\n */\n openAuthSession(options: OpenAuthSessionOptions): Promise<OpenAuthSessionResult>;\n}\n"]}
@@ -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.7.5"
19
+ private let pluginVersion: String = "8.7.6"
20
20
  public let identifier = "SocialLoginPlugin"
21
21
  public let jsName = "SocialLogin"
22
22
  private static let userCancelledCode = "USER_CANCELLED"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-social-login",
3
- "version": "8.7.5",
3
+ "version": "8.7.6",
4
4
  "description": "All social logins in one plugin",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",