@capgo/capacitor-social-login 8.3.40 → 8.4.1

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
@@ -115,7 +115,7 @@ export default config;
115
115
  - This configuration only affects iOS and Android platforms; it does not affect the web platform.
116
116
  - **Important**: Using `false` means the dependency won't be bundled, but the plugin code still compiles against it. Ensure the consuming app includes the dependency if needed.
117
117
  - **Facebook**: When `facebook: false`, the Facebook SDK is omitted and the plugin compiles a provider stub in its own package — no `com.facebook.*` classes are shipped (avoids privacy-scanner false positives).
118
- - **Apple (iOS)**: Basic Sign in with Apple always works via AuthenticationServices (no external SDK). Alamofire is only required when using `redirectUrl` / backend token exchange. CocoaPods toggles Alamofire via `apple: true|false`; SPM always resolves Alamofire from `Package.swift` when the plugin is linked.
118
+ - **Apple (iOS)**: `apple: true` enables Sign in with Apple (AuthenticationServices; no external SDK for basic login). Alamofire is only linked when using `redirectUrl` / backend token exchange. `apple: false` removes Alamofire and disables Apple authentication at runtime—including basic Sign in with Apple—consistent with the rule above that `false` providers are unavailable at runtime. CocoaPods and Swift Package Manager both toggle Alamofire based on `apple: true|false`.
119
119
  - Apple Sign-In on Android uses OAuth flow without external SDK dependencies
120
120
  - Twitter uses standard OAuth 2.0 flow without external SDK dependencies
121
121
 
@@ -710,13 +710,14 @@ await SocialLogin.refresh({
710
710
  | `additionalParameters` | Record<string, string> | No | Extra params for authorization URL |
711
711
  | `additionalResourceHeaders` | Record<string, string> | No | Extra headers for resource request |
712
712
  | `logoutUrl` | string | No | URL to open on logout |
713
+ | `androidUseCustomTabs` | boolean | No | Android-only: use Chrome Custom Tabs instead of WebView (default: false). Requires a deep-linkable `redirectUrl` |
713
714
  | `logsEnabled` | boolean | No | Enable debug logging (default: false) |
714
715
 
715
716
  ### Platform-Specific Notes
716
717
 
717
718
  **iOS**: Uses `ASWebAuthenticationSession` for secure authentication.
718
719
 
719
- **Android**: Uses a WebView-based authentication flow.
720
+ **Android**: Uses an embedded WebView by default. Set `androidUseCustomTabs: true` to use Chrome Custom Tabs instead (RFC 8252 / system browser). Custom Tabs require a custom-scheme or App Link `redirectUrl` with a matching intent filter in your app's `AndroidManifest.xml`, and `android:launchMode="singleTask"` (or `singleTop`) on the main activity so redirects arrive via `onNewIntent`.
720
721
 
721
722
  **Web**: Opens a popup window for OAuth flow.
722
723
 
@@ -1208,34 +1209,35 @@ And in the AndroidManifest.xml file:
1208
1209
 
1209
1210
  Configuration for a single OAuth2 provider instance
1210
1211
 
1211
- | Prop | Type | Description | Default |
1212
- | ------------------------------------------ | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
1213
- | **`appId`** | <code>string</code> | The OAuth 2.0 client identifier (App ID / Client ID). Note: this configuration object is only used by the plugin's built-in `oauth2` provider (i.e. `SocialLogin.initialize({ oauth2: { ... } })`). It does not affect Google/Apple/Facebook/Twitter. | |
1214
- | **`clientId`** | <code>string</code> | Alias for `appId` to match common OAuth/OIDC naming (`clientId`). If both are provided, `appId` takes precedence. | |
1215
- | **`issuerUrl`** | <code>string</code> | OpenID Connect issuer URL (enables discovery via `/.well-known/openid-configuration`). When set, you may omit explicit endpoints like `authorizationBaseUrl` and `accessTokenEndpoint`. Notes: - Explicit endpoints (authorization/token/logout) take precedence over discovered values. - Discovery is supported for `oauth2` on Web, iOS, and Android. | |
1216
- | **`authorizationBaseUrl`** | <code>string</code> | The base URL of the authorization endpoint | |
1217
- | **`authorizationEndpoint`** | <code>string</code> | Alias for `authorizationBaseUrl` (to match common OAuth/OIDC naming). | |
1218
- | **`clientSecret`** | <code>string</code> | OAuth 2.0 client secret for token requests (e.g., when exchanging the code). This value is sent as `client_secret` in token/refresh requests when provided. | |
1219
- | **`accessTokenEndpoint`** | <code>string</code> | The URL to exchange the authorization code for tokens Required for authorization code flow | |
1220
- | **`tokenEndpoint`** | <code>string</code> | Alias for `accessTokenEndpoint` (to match common OAuth/OIDC naming). | |
1221
- | **`redirectUrl`** | <code>string</code> | Redirect URL that receives the OAuth callback | |
1222
- | **`resourceUrl`** | <code>string</code> | Optional URL to fetch user profile/resource data after authentication The access token will be sent as Bearer token in the Authorization header | |
1223
- | **`responseType`** | <code>'code' \| 'token'</code> | The OAuth response type - 'code': Authorization Code flow (recommended, requires accessTokenEndpoint) - 'token': Implicit flow (less secure, tokens returned directly) | <code>'code'</code> |
1224
- | **`pkceEnabled`** | <code>boolean</code> | Enable PKCE (Proof Key for Code Exchange) Strongly recommended for public clients (mobile/web apps) | <code>true</code> |
1225
- | **`scope`** | <code>string \| string[]</code> | Default scopes to request during authorization | |
1226
- | **`scopes`** | <code>string[]</code> | Alias for `scope` using common naming (`scopes`). If both are provided, `scope` takes precedence. | |
1227
- | **`additionalParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in the authorization request | |
1228
- | **`loginHint`** | <code>string</code> | Convenience option for OIDC `login_hint`. Equivalent to passing `additionalParameters.login_hint`. | |
1229
- | **`prompt`** | <code>string</code> | Convenience option for OAuth/OIDC `prompt`. Equivalent to passing `additionalParameters.prompt`. | |
1230
- | **`additionalTokenParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in token requests (code exchange / refresh). Useful for providers that require non-standard parameters. | |
1231
- | **`additionalResourceHeaders`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional headers to include when fetching the resource URL | |
1232
- | **`logoutUrl`** | <code>string</code> | Custom logout URL for ending the session | |
1233
- | **`endSessionEndpoint`** | <code>string</code> | Alias for `logoutUrl` to match OIDC naming (`endSessionEndpoint`). | |
1234
- | **`postLogoutRedirectUrl`** | <code>string</code> | OIDC post logout redirect URL (sent as `post_logout_redirect_uri` when building the end-session URL). | |
1235
- | **`additionalLogoutParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in logout / end-session URL. | |
1236
- | **`iosPrefersEphemeralWebBrowserSession`** | <code>boolean</code> | iOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession. Defaults to true to match existing behavior in this plugin. | |
1237
- | **`iosPrefersEphemeralSession`** | <code>boolean</code> | Alias for `iosPrefersEphemeralWebBrowserSession` (to match Capawesome OAuth naming). | |
1238
- | **`logsEnabled`** | <code>boolean</code> | Enable debug logging | <code>false</code> |
1212
+ | Prop | Type | Description | Default |
1213
+ | ------------------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
1214
+ | **`appId`** | <code>string</code> | The OAuth 2.0 client identifier (App ID / Client ID). Note: this configuration object is only used by the plugin's built-in `oauth2` provider (i.e. `SocialLogin.initialize({ oauth2: { ... } })`). It does not affect Google/Apple/Facebook/Twitter. | |
1215
+ | **`clientId`** | <code>string</code> | Alias for `appId` to match common OAuth/OIDC naming (`clientId`). If both are provided, `appId` takes precedence. | |
1216
+ | **`issuerUrl`** | <code>string</code> | OpenID Connect issuer URL (enables discovery via `/.well-known/openid-configuration`). When set, you may omit explicit endpoints like `authorizationBaseUrl` and `accessTokenEndpoint`. Notes: - Explicit endpoints (authorization/token/logout) take precedence over discovered values. - Discovery is supported for `oauth2` on Web, iOS, and Android. | |
1217
+ | **`authorizationBaseUrl`** | <code>string</code> | The base URL of the authorization endpoint | |
1218
+ | **`authorizationEndpoint`** | <code>string</code> | Alias for `authorizationBaseUrl` (to match common OAuth/OIDC naming). | |
1219
+ | **`clientSecret`** | <code>string</code> | OAuth 2.0 client secret for token requests (e.g., when exchanging the code). This value is sent as `client_secret` in token/refresh requests when provided. | |
1220
+ | **`accessTokenEndpoint`** | <code>string</code> | The URL to exchange the authorization code for tokens Required for authorization code flow | |
1221
+ | **`tokenEndpoint`** | <code>string</code> | Alias for `accessTokenEndpoint` (to match common OAuth/OIDC naming). | |
1222
+ | **`redirectUrl`** | <code>string</code> | Redirect URL that receives the OAuth callback | |
1223
+ | **`resourceUrl`** | <code>string</code> | Optional URL to fetch user profile/resource data after authentication The access token will be sent as Bearer token in the Authorization header | |
1224
+ | **`responseType`** | <code>'code' \| 'token'</code> | The OAuth response type - 'code': Authorization Code flow (recommended, requires accessTokenEndpoint) - 'token': Implicit flow (less secure, tokens returned directly) | <code>'code'</code> |
1225
+ | **`pkceEnabled`** | <code>boolean</code> | Enable PKCE (Proof Key for Code Exchange) Strongly recommended for public clients (mobile/web apps) | <code>true</code> |
1226
+ | **`scope`** | <code>string \| string[]</code> | Default scopes to request during authorization | |
1227
+ | **`scopes`** | <code>string[]</code> | Alias for `scope` using common naming (`scopes`). If both are provided, `scope` takes precedence. | |
1228
+ | **`additionalParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in the authorization request | |
1229
+ | **`loginHint`** | <code>string</code> | Convenience option for OIDC `login_hint`. Equivalent to passing `additionalParameters.login_hint`. | |
1230
+ | **`prompt`** | <code>string</code> | Convenience option for OAuth/OIDC `prompt`. Equivalent to passing `additionalParameters.prompt`. | |
1231
+ | **`additionalTokenParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in token requests (code exchange / refresh). Useful for providers that require non-standard parameters. | |
1232
+ | **`additionalResourceHeaders`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional headers to include when fetching the resource URL | |
1233
+ | **`logoutUrl`** | <code>string</code> | Custom logout URL for ending the session | |
1234
+ | **`endSessionEndpoint`** | <code>string</code> | Alias for `logoutUrl` to match OIDC naming (`endSessionEndpoint`). | |
1235
+ | **`postLogoutRedirectUrl`** | <code>string</code> | OIDC post logout redirect URL (sent as `post_logout_redirect_uri` when building the end-session URL). | |
1236
+ | **`additionalLogoutParameters`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional parameters to include in logout / end-session URL. | |
1237
+ | **`iosPrefersEphemeralWebBrowserSession`** | <code>boolean</code> | iOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession. Defaults to true to match existing behavior in this plugin. | |
1238
+ | **`iosPrefersEphemeralSession`** | <code>boolean</code> | Alias for `iosPrefersEphemeralWebBrowserSession` (to match Capawesome OAuth naming). | |
1239
+ | **`androidUseCustomTabs`** | <code>boolean</code> | Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView for the authorization request. Custom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered IdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google `disallowed_useragent`, SSO cookie sharing, password managers). Requires a custom-scheme or App Link `redirectUrl` with a matching intent filter in your app's `AndroidManifest.xml` (same setup as `openSecureWindow()` / Apple on Android). Defaults to `false` to preserve the historical WebView flow. | <code>false</code> |
1240
+ | **`logsEnabled`** | <code>boolean</code> | Enable debug logging | <code>false</code> |
1239
1241
 
1240
1242
 
1241
1243
  #### FacebookLoginResponse
@@ -7,6 +7,7 @@ import android.content.SharedPreferences;
7
7
  import android.net.Uri;
8
8
  import android.util.Base64;
9
9
  import android.util.Log;
10
+ import androidx.browser.customtabs.CustomTabsIntent;
10
11
  import com.getcapacitor.JSArray;
11
12
  import com.getcapacitor.JSObject;
12
13
  import com.getcapacitor.PluginCall;
@@ -42,6 +43,12 @@ public class OAuth2Provider implements SocialProvider {
42
43
  private static final String USER_CANCELLED_CODE = "USER_CANCELLED";
43
44
  private static final String PREFS_NAME = "CapgoOAuth2ProviderPrefs";
44
45
  private static final String PREFS_KEY_PREFIX = "OAuth2Tokens_";
46
+ private static final String CUSTOM_TABS_PENDING_IN_PROGRESS = "OAuth2CustomTabsInProgress";
47
+ private static final String CUSTOM_TABS_PENDING_PROVIDER_ID = "OAuth2CustomTabsProviderId";
48
+ private static final String CUSTOM_TABS_PENDING_STATE = "OAuth2CustomTabsState";
49
+ private static final String CUSTOM_TABS_PENDING_CODE_VERIFIER = "OAuth2CustomTabsCodeVerifier";
50
+ private static final String CUSTOM_TABS_PENDING_REDIRECT = "OAuth2CustomTabsRedirect";
51
+ private static final String CUSTOM_TABS_PENDING_SCOPE = "OAuth2CustomTabsScope";
45
52
 
46
53
  public interface ActivityLauncher {
47
54
  void launchForResult(Intent intent, int requestCode);
@@ -56,6 +63,7 @@ public class OAuth2Provider implements SocialProvider {
56
63
 
57
64
  private PluginCall pendingCall;
58
65
  private OAuth2PendingState pendingState;
66
+ private boolean pendingUseCustomTabs;
59
67
  private ActivityLauncher activityLauncher;
60
68
 
61
69
  public void setActivityLauncher(ActivityLauncher launcher) {
@@ -90,6 +98,7 @@ public class OAuth2Provider implements SocialProvider {
90
98
  final String logoutUrl;
91
99
  final String postLogoutRedirectUrl;
92
100
  final Map<String, String> additionalLogoutParameters;
101
+ final boolean androidUseCustomTabs;
93
102
  final boolean logsEnabled;
94
103
 
95
104
  OAuth2ProviderConfig(
@@ -111,6 +120,7 @@ public class OAuth2Provider implements SocialProvider {
111
120
  String logoutUrl,
112
121
  String postLogoutRedirectUrl,
113
122
  Map<String, String> additionalLogoutParameters,
123
+ boolean androidUseCustomTabs,
114
124
  boolean logsEnabled
115
125
  ) {
116
126
  this.appId = appId;
@@ -131,6 +141,7 @@ public class OAuth2Provider implements SocialProvider {
131
141
  this.logoutUrl = logoutUrl;
132
142
  this.postLogoutRedirectUrl = postLogoutRedirectUrl;
133
143
  this.additionalLogoutParameters = additionalLogoutParameters;
144
+ this.androidUseCustomTabs = androidUseCustomTabs;
134
145
  this.logsEnabled = logsEnabled;
135
146
  }
136
147
  }
@@ -241,6 +252,7 @@ public class OAuth2Provider implements SocialProvider {
241
252
  (config.logoutUrl != null && !config.logoutUrl.isEmpty()) ? config.logoutUrl : endSession,
242
253
  config.postLogoutRedirectUrl,
243
254
  config.additionalLogoutParameters,
255
+ config.androidUseCustomTabs,
244
256
  config.logsEnabled
245
257
  );
246
258
  providers.put(providerId, resolved);
@@ -334,6 +346,7 @@ public class OAuth2Provider implements SocialProvider {
334
346
  config.has("logoutUrl") ? config.optString("logoutUrl", null) : config.optString("endSessionEndpoint", null),
335
347
  config.optString("postLogoutRedirectUrl", null),
336
348
  additionalLogoutParameters,
349
+ config.optBoolean("androidUseCustomTabs", false),
337
350
  config.optBoolean("logsEnabled", false)
338
351
  );
339
352
 
@@ -486,22 +499,24 @@ public class OAuth2Provider implements SocialProvider {
486
499
  Log.d(LOG_TAG, "Opening authorization URL: " + builder.build().toString());
487
500
  }
488
501
 
489
- Intent intent = new Intent(activity, OAuth2LoginActivity.class);
490
- intent.putExtra(OAuth2LoginActivity.EXTRA_AUTH_URL, builder.build().toString());
491
- intent.putExtra(OAuth2LoginActivity.EXTRA_REDIRECT_URL, finalRedirect);
492
-
493
- activity.runOnUiThread(() -> {
494
- if (activityLauncher != null) {
495
- activityLauncher.launchForResult(intent, REQUEST_CODE);
496
- } else {
497
- Log.w(
498
- LOG_TAG,
499
- "activityLauncher is null — falling back to raw startActivityForResult. " +
500
- "Activity result routing through Capacitor will not work."
501
- );
502
- activity.startActivityForResult(intent, REQUEST_CODE);
502
+ pendingUseCustomTabs = resolved.androidUseCustomTabs;
503
+ if (resolved.androidUseCustomTabs) {
504
+ if (resolved.logsEnabled) {
505
+ Log.d(LOG_TAG, "Using Custom Tabs for OAuth2 authorization");
503
506
  }
504
- });
507
+ final String authUrl = builder.build().toString();
508
+ activity.runOnUiThread(() -> {
509
+ if (!launchCustomTabs(authUrl)) {
510
+ // No Custom Tabs browser — fall back to embedded WebView
511
+ pendingUseCustomTabs = false;
512
+ clearPersistedCustomTabsState();
513
+ launchWebViewActivity(authUrl, finalRedirect);
514
+ }
515
+ });
516
+ return;
517
+ }
518
+
519
+ activity.runOnUiThread(() -> launchWebViewActivity(builder.build().toString(), finalRedirect));
505
520
  }
506
521
 
507
522
  @Override
@@ -684,45 +699,257 @@ public class OAuth2Provider implements SocialProvider {
684
699
  return true;
685
700
  }
686
701
 
687
- String returnedState = data.getStringExtra("state");
702
+ return processCallbackData(data);
703
+ }
704
+
705
+ /**
706
+ * Handle OAuth redirect delivered via deep link / App Link after a Custom Tabs auth session.
707
+ * @return true if this URI was consumed as an OAuth2 Custom Tabs callback
708
+ */
709
+ public boolean handleRedirectUri(Uri uri) {
710
+ if (uri == null) {
711
+ return false;
712
+ }
713
+
714
+ // After process death, restore PKCE/state so we can still complete the exchange.
715
+ if (pendingState == null) {
716
+ restorePersistedCustomTabsState();
717
+ }
718
+
719
+ if (pendingState == null || !pendingUseCustomTabs) {
720
+ return false;
721
+ }
722
+
723
+ if (!matchesRedirectUri(pendingState.redirectUri, uri)) {
724
+ return false;
725
+ }
726
+
727
+ Intent data = callbackUriToIntent(uri);
728
+
729
+ // Prevent handleOnResume from treating the return as cancellation while token exchange runs
730
+ pendingUseCustomTabs = false;
731
+ clearPersistedCustomTabsState();
732
+ return processCallbackData(data);
733
+ }
734
+
735
+ /**
736
+ * Called when the host activity resumes after Custom Tabs without receiving a redirect.
737
+ * Treat as user cancellation (same pattern as {@code openSecureWindow}).
738
+ */
739
+ public void handleUserReturnedWithoutCallback() {
740
+ if (!pendingUseCustomTabs) {
741
+ return;
742
+ }
743
+
744
+ // Prefer consuming a redirect already attached to the activity intent (cold start / recreate)
745
+ Intent current = activity != null ? activity.getIntent() : null;
746
+ if (current != null && Intent.ACTION_VIEW.equals(current.getAction()) && current.getData() != null) {
747
+ if (handleRedirectUri(current.getData())) {
748
+ return;
749
+ }
750
+ }
751
+
752
+ if (pendingCall == null) {
753
+ clearPersistedCustomTabsState();
754
+ pendingUseCustomTabs = false;
755
+ pendingState = null;
756
+ return;
757
+ }
758
+ pendingCall.reject("User cancelled", USER_CANCELLED_CODE);
759
+ cleanupPending();
760
+ }
761
+
762
+ /**
763
+ * Restore any persisted Custom Tabs login state (e.g. after process death) and return whether
764
+ * a Custom Tabs session was in progress.
765
+ */
766
+ public boolean restorePersistedCustomTabsState() {
767
+ SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
768
+ String providerId = prefs.getString(CUSTOM_TABS_PENDING_PROVIDER_ID, null);
769
+ String state = prefs.getString(CUSTOM_TABS_PENDING_STATE, null);
770
+ String codeVerifier = prefs.getString(CUSTOM_TABS_PENDING_CODE_VERIFIER, null);
771
+ String redirectUri = prefs.getString(CUSTOM_TABS_PENDING_REDIRECT, null);
772
+ String scope = prefs.getString(CUSTOM_TABS_PENDING_SCOPE, null);
773
+ boolean inProgress = prefs.getBoolean(CUSTOM_TABS_PENDING_IN_PROGRESS, false);
774
+ if (!inProgress || providerId == null || state == null || redirectUri == null) {
775
+ return false;
776
+ }
777
+ pendingState = new OAuth2PendingState(providerId, state, codeVerifier, redirectUri, scope != null ? scope : "");
778
+ pendingUseCustomTabs = true;
779
+ return true;
780
+ }
781
+
782
+ private boolean processCallbackData(Intent data) {
783
+ if (pendingState == null) {
784
+ return true;
785
+ }
786
+
787
+ String returnedState = data != null ? data.getStringExtra("state") : null;
688
788
  if (returnedState == null || !returnedState.equals(pendingState.state)) {
689
- pendingCall.reject("State mismatch during OAuth2 login");
789
+ if (pendingCall != null) {
790
+ pendingCall.reject("State mismatch during OAuth2 login");
791
+ }
690
792
  cleanupPending();
691
793
  return true;
692
794
  }
693
795
 
694
- String error = data.getStringExtra("error");
796
+ String error = data != null ? data.getStringExtra("error") : null;
695
797
  if (error != null) {
696
798
  String description = data.getStringExtra("error_description");
697
799
  String message = description != null ? description : error;
698
- if (isUserDeniedRedirect(error, description)) {
699
- pendingCall.reject(message, USER_CANCELLED_CODE);
700
- } else {
701
- pendingCall.reject(message);
800
+ if (pendingCall != null) {
801
+ if (isUserDeniedRedirect(error, description)) {
802
+ pendingCall.reject(message, USER_CANCELLED_CODE);
803
+ } else {
804
+ pendingCall.reject(message);
805
+ }
702
806
  }
703
807
  cleanupPending();
704
808
  return true;
705
809
  }
706
810
 
707
811
  // Check for code (authorization code flow)
708
- String code = data.getStringExtra("code");
812
+ String code = data != null ? data.getStringExtra("code") : null;
709
813
  if (code != null) {
814
+ if (pendingCall == null) {
815
+ // Process death: original JS call is gone — still exchange & store tokens.
816
+ Log.w(LOG_TAG, "Completing OAuth2 Custom Tabs callback without pending PluginCall (process death?)");
817
+ }
710
818
  exchangeAuthorizationCode(code);
711
819
  return true;
712
820
  }
713
821
 
714
822
  // Check for access_token (implicit flow)
715
- String accessToken = data.getStringExtra("access_token");
823
+ String accessToken = data != null ? data.getStringExtra("access_token") : null;
716
824
  if (accessToken != null) {
825
+ if (pendingCall == null) {
826
+ Log.w(LOG_TAG, "Completing OAuth2 Custom Tabs implicit callback without pending PluginCall (process death?)");
827
+ }
717
828
  handleImplicitFlowResponse(data);
718
829
  return true;
719
830
  }
720
831
 
721
- pendingCall.reject("No authorization code or access token in callback");
832
+ if (pendingCall != null) {
833
+ pendingCall.reject("No authorization code or access token in callback");
834
+ }
722
835
  cleanupPending();
723
836
  return true;
724
837
  }
725
838
 
839
+ private void launchWebViewActivity(String authUrl, String redirectUrl) {
840
+ Intent intent = new Intent(activity, OAuth2LoginActivity.class);
841
+ intent.putExtra(OAuth2LoginActivity.EXTRA_AUTH_URL, authUrl);
842
+ intent.putExtra(OAuth2LoginActivity.EXTRA_REDIRECT_URL, redirectUrl);
843
+
844
+ if (activityLauncher != null) {
845
+ activityLauncher.launchForResult(intent, REQUEST_CODE);
846
+ } else {
847
+ Log.w(
848
+ LOG_TAG,
849
+ "activityLauncher is null — falling back to raw startActivityForResult. " +
850
+ "Activity result routing through Capacitor will not work."
851
+ );
852
+ activity.startActivityForResult(intent, REQUEST_CODE);
853
+ }
854
+ }
855
+
856
+ /**
857
+ * @return true if Custom Tabs launched successfully
858
+ */
859
+ private boolean launchCustomTabs(String url) {
860
+ try {
861
+ persistCustomTabsState();
862
+ CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
863
+ CustomTabsIntent customTabsIntent = builder.build();
864
+ customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
865
+ customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
866
+ customTabsIntent.launchUrl(activity, Uri.parse(url));
867
+ return true;
868
+ } catch (android.content.ActivityNotFoundException e) {
869
+ Log.w(LOG_TAG, "Custom Tabs unavailable, falling back to WebView", e);
870
+ clearPersistedCustomTabsState();
871
+ return false;
872
+ }
873
+ }
874
+
875
+ private void persistCustomTabsState() {
876
+ if (pendingState == null) {
877
+ return;
878
+ }
879
+ context
880
+ .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
881
+ .edit()
882
+ .putBoolean(CUSTOM_TABS_PENDING_IN_PROGRESS, true)
883
+ .putString(CUSTOM_TABS_PENDING_PROVIDER_ID, pendingState.providerId)
884
+ .putString(CUSTOM_TABS_PENDING_STATE, pendingState.state)
885
+ .putString(CUSTOM_TABS_PENDING_CODE_VERIFIER, pendingState.codeVerifier)
886
+ .putString(CUSTOM_TABS_PENDING_REDIRECT, pendingState.redirectUri)
887
+ .putString(CUSTOM_TABS_PENDING_SCOPE, pendingState.scope)
888
+ .apply();
889
+ }
890
+
891
+ private void clearPersistedCustomTabsState() {
892
+ context
893
+ .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
894
+ .edit()
895
+ .remove(CUSTOM_TABS_PENDING_IN_PROGRESS)
896
+ .remove(CUSTOM_TABS_PENDING_PROVIDER_ID)
897
+ .remove(CUSTOM_TABS_PENDING_STATE)
898
+ .remove(CUSTOM_TABS_PENDING_CODE_VERIFIER)
899
+ .remove(CUSTOM_TABS_PENDING_REDIRECT)
900
+ .remove(CUSTOM_TABS_PENDING_SCOPE)
901
+ .apply();
902
+ }
903
+
904
+ static boolean matchesRedirectUri(String expectedRedirect, Uri actual) {
905
+ if (expectedRedirect == null || expectedRedirect.isEmpty() || actual == null) {
906
+ return false;
907
+ }
908
+ Uri expected = Uri.parse(expectedRedirect);
909
+ if (expected.getScheme() == null || actual.getScheme() == null) {
910
+ return false;
911
+ }
912
+ if (!expected.getScheme().equalsIgnoreCase(actual.getScheme())) {
913
+ return false;
914
+ }
915
+ String expectedAuthority = expected.getAuthority();
916
+ String actualAuthority = actual.getAuthority();
917
+ if (expectedAuthority == null ? actualAuthority != null : !expectedAuthority.equalsIgnoreCase(actualAuthority)) {
918
+ return false;
919
+ }
920
+ String expectedPath = normalizePath(expected.getPath());
921
+ String actualPath = normalizePath(actual.getPath());
922
+ return expectedPath.equals(actualPath);
923
+ }
924
+
925
+ private static String normalizePath(String path) {
926
+ if (path == null || path.isEmpty()) {
927
+ return "";
928
+ }
929
+ if (path.length() > 1 && path.endsWith("/")) {
930
+ return path.substring(0, path.length() - 1);
931
+ }
932
+ return path;
933
+ }
934
+
935
+ static Intent callbackUriToIntent(Uri uri) {
936
+ Intent data = new Intent();
937
+ data.putExtra("code", uri.getQueryParameter("code"));
938
+ data.putExtra("state", uri.getQueryParameter("state"));
939
+ data.putExtra("error", uri.getQueryParameter("error"));
940
+ data.putExtra("error_description", uri.getQueryParameter("error_description"));
941
+
942
+ // Use encoded fragment so values containing encoded '&' (%26) are not split incorrectly
943
+ String encodedFragment = uri.getEncodedFragment();
944
+ if (encodedFragment != null && !encodedFragment.isEmpty()) {
945
+ Uri fragmentUri = Uri.parse("https://callback.invalid/?" + encodedFragment);
946
+ for (String key : fragmentUri.getQueryParameterNames()) {
947
+ data.putExtra(key, fragmentUri.getQueryParameter(key));
948
+ }
949
+ }
950
+ return data;
951
+ }
952
+
726
953
  private boolean isUserDeniedRedirect(String error, String description) {
727
954
  if ("access_denied".equalsIgnoreCase(error)) {
728
955
  return true;
@@ -795,7 +1022,9 @@ public class OAuth2Provider implements SocialProvider {
795
1022
  OAuth2ProviderConfig config = getProvider(providerId);
796
1023
 
797
1024
  if (config == null) {
798
- pendingCall.reject("OAuth2 provider '" + providerId + "' not found");
1025
+ if (pendingCall != null) {
1026
+ pendingCall.reject("OAuth2 provider '" + providerId + "' not found");
1027
+ }
799
1028
  cleanupPending();
800
1029
  return;
801
1030
  }
@@ -809,7 +1038,9 @@ public class OAuth2Provider implements SocialProvider {
809
1038
  @Override
810
1039
  public void onSuccess(OAuth2ProviderConfig resolved) {
811
1040
  if (resolved.accessTokenEndpoint == null || resolved.accessTokenEndpoint.isEmpty()) {
812
- pendingCall.reject("No accessTokenEndpoint configured for code exchange");
1041
+ if (pendingCall != null) {
1042
+ pendingCall.reject("No accessTokenEndpoint configured for code exchange");
1043
+ }
813
1044
  cleanupPending();
814
1045
  return;
815
1046
  }
@@ -818,7 +1049,9 @@ public class OAuth2Provider implements SocialProvider {
818
1049
 
819
1050
  @Override
820
1051
  public void onError(String message) {
821
- pendingCall.reject(message);
1052
+ if (pendingCall != null) {
1053
+ pendingCall.reject(message);
1054
+ }
822
1055
  cleanupPending();
823
1056
  }
824
1057
  }
@@ -830,7 +1063,7 @@ public class OAuth2Provider implements SocialProvider {
830
1063
  }
831
1064
 
832
1065
  private void exchangeAuthorizationCodeWithConfig(String code, OAuth2ProviderConfig config) {
833
- if (pendingState == null || pendingCall == null) {
1066
+ if (pendingState == null) {
834
1067
  cleanupPending();
835
1068
  return;
836
1069
  }
@@ -1001,10 +1234,6 @@ public class OAuth2Provider implements SocialProvider {
1001
1234
  String fallbackRefreshToken,
1002
1235
  boolean wrapResponse
1003
1236
  ) throws JSONException {
1004
- if (call == null) {
1005
- return;
1006
- }
1007
-
1008
1237
  final String accessToken = tokenPayload.getString("access_token");
1009
1238
  final String tokenType = tokenPayload.optString("token_type", "bearer");
1010
1239
  final int expiresIn = tokenPayload.optInt("expires_in", 3600);
@@ -1117,12 +1346,12 @@ public class OAuth2Provider implements SocialProvider {
1117
1346
  PluginCall call,
1118
1347
  boolean wrapResponse
1119
1348
  ) {
1349
+ persistTokens(providerId, accessToken, refreshToken, idToken, tokenType, expiresAt, scopes);
1350
+
1120
1351
  if (call == null) {
1121
1352
  return;
1122
1353
  }
1123
1354
 
1124
- persistTokens(providerId, accessToken, refreshToken, idToken, tokenType, expiresAt, scopes);
1125
-
1126
1355
  JSObject accessTokenObject = new JSObject();
1127
1356
  accessTokenObject.put("token", accessToken);
1128
1357
  accessTokenObject.put("tokenType", tokenType);
@@ -1248,6 +1477,8 @@ public class OAuth2Provider implements SocialProvider {
1248
1477
  private void cleanupPending() {
1249
1478
  pendingCall = null;
1250
1479
  pendingState = null;
1480
+ pendingUseCustomTabs = false;
1481
+ clearPersistedCustomTabsState();
1251
1482
  }
1252
1483
 
1253
1484
  private static Map<String, String> jsonObjectToMap(JSONObject json) throws JSONException {
@@ -24,13 +24,14 @@ import org.json.JSONObject;
24
24
  @CapacitorPlugin(name = "SocialLogin")
25
25
  public class SocialLoginPlugin extends Plugin {
26
26
 
27
- private final String pluginVersion = "8.3.40";
27
+ private final String pluginVersion = "8.4.1";
28
28
 
29
29
  public static String LOG_TAG = "CapgoSocialLogin";
30
30
  public HashMap<String, SocialProvider> socialProviderHashMap = new HashMap<>();
31
31
 
32
32
  private PluginCall openSecureWindowSavedCall;
33
33
  private String openSecureWindowRedirectUri;
34
+ private Uri pendingOAuth2RedirectUri;
34
35
 
35
36
  @PluginMethod
36
37
  public void initialize(PluginCall call) {
@@ -183,6 +184,19 @@ public class SocialLoginPlugin extends Plugin {
183
184
  Log.e(LOG_TAG, "OAuth2 activityLauncher fired but pendingCall is null, cannot route result");
184
185
  }
185
186
  });
187
+ // Replay a redirect that arrived before initialize (cold start / process death)
188
+ boolean handledRedirect = false;
189
+ if (pendingOAuth2RedirectUri != null) {
190
+ Uri buffered = pendingOAuth2RedirectUri;
191
+ pendingOAuth2RedirectUri = null;
192
+ handledRedirect = oauth2Provider.handleRedirectUri(buffered);
193
+ }
194
+ // If handleOnResume ran before initialize, persisted Custom Tabs state may still be
195
+ // present with no buffered redirect — restore then cancel/clear the orphaned session
196
+ // (or complete via activity.getIntent() if the redirect is attached there).
197
+ if (!handledRedirect && oauth2Provider.restorePersistedCustomTabsState()) {
198
+ oauth2Provider.handleUserReturnedWithoutCallback();
199
+ }
186
200
  } catch (JSONException e) {
187
201
  call.reject("Failed to initialize OAuth2 provider: " + e.getMessage());
188
202
  return;
@@ -597,6 +611,11 @@ public class SocialLoginPlugin extends Plugin {
597
611
  protected void handleOnResume() {
598
612
  super.handleOnResume();
599
613
 
614
+ SocialProvider oauth2Provider = socialProviderHashMap.get("oauth2");
615
+ if (oauth2Provider instanceof OAuth2Provider) {
616
+ ((OAuth2Provider) oauth2Provider).handleUserReturnedWithoutCallback();
617
+ }
618
+
600
619
  // If we have a saved call and user returned without callback, reject
601
620
  if (openSecureWindowSavedCall != null) {
602
621
  openSecureWindowSavedCall.reject("OAuth cancelled or no callback received");
@@ -617,6 +636,16 @@ public class SocialLoginPlugin extends Plugin {
617
636
  return;
618
637
  }
619
638
 
639
+ SocialProvider oauth2Provider = socialProviderHashMap.get("oauth2");
640
+ if (oauth2Provider instanceof OAuth2Provider) {
641
+ if (((OAuth2Provider) oauth2Provider).handleRedirectUri(uri)) {
642
+ return;
643
+ }
644
+ } else {
645
+ // Buffer until SocialLogin.initialize() registers the oauth2 provider
646
+ pendingOAuth2RedirectUri = uri;
647
+ }
648
+
620
649
  if (openSecureWindowRedirectUri == null) {
621
650
  return;
622
651
  }
package/dist/docs.json CHANGED
@@ -678,6 +678,22 @@
678
678
  "complexTypes": [],
679
679
  "type": "boolean | undefined"
680
680
  },
681
+ {
682
+ "name": "androidUseCustomTabs",
683
+ "tags": [
684
+ {
685
+ "text": "false",
686
+ "name": "default"
687
+ },
688
+ {
689
+ "text": "true",
690
+ "name": "example"
691
+ }
692
+ ],
693
+ "docs": "Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView\nfor the authorization request.\n\nCustom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered\nIdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google\n`disallowed_useragent`, SSO cookie sharing, password managers).\n\nRequires a custom-scheme or App Link `redirectUrl` with a matching intent filter in\nyour app's `AndroidManifest.xml` (same setup as `openSecureWindow()` / Apple on Android).\n\nDefaults to `false` to preserve the historical WebView flow.",
694
+ "complexTypes": [],
695
+ "type": "boolean | undefined"
696
+ },
681
697
  {
682
698
  "name": "logsEnabled",
683
699
  "tags": [
@@ -141,6 +141,23 @@ export interface OAuth2ProviderConfig {
141
141
  * Alias for `iosPrefersEphemeralWebBrowserSession` (to match Capawesome OAuth naming).
142
142
  */
143
143
  iosPrefersEphemeralSession?: boolean;
144
+ /**
145
+ * Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView
146
+ * for the authorization request.
147
+ *
148
+ * Custom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered
149
+ * IdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google
150
+ * `disallowed_useragent`, SSO cookie sharing, password managers).
151
+ *
152
+ * Requires a custom-scheme or App Link `redirectUrl` with a matching intent filter in
153
+ * your app's `AndroidManifest.xml` (same setup as `openSecureWindow()` / Apple on Android).
154
+ *
155
+ * Defaults to `false` to preserve the historical WebView flow.
156
+ *
157
+ * @default false
158
+ * @example true
159
+ */
160
+ androidUseCustomTabs?: boolean;
144
161
  /**
145
162
  * Enable debug logging
146
163
  * @default false
@@ -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 * This value is sent as `client_secret` in token/refresh requests when provided.\n */\n clientSecret?: 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 * Enable debug logging\n * @default false\n */\n logsEnabled?: boolean;\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 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 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\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\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\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: '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: '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 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' | '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' | '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\nexport type ProviderSpecificCall = 'facebook#getProfile' | 'facebook#requestTracking';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile\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 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};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\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 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 * @throws Error if Google provider is in offline mode\n */\n logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2';\n providerId?: string;\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 * @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 * - Only applies to the built-in `oauth2` provider (not Google/Apple/Facebook/Twitter).\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: {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }): 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 */\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"]}
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 * This value is sent as `client_secret` in token/refresh requests when provided.\n */\n clientSecret?: 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\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 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 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\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\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\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: '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: '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 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' | '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' | '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\nexport type ProviderSpecificCall = 'facebook#getProfile' | 'facebook#requestTracking';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile\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 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};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\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 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 * @throws Error if Google provider is in offline mode\n */\n logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2';\n providerId?: string;\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 * @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 * - Only applies to the built-in `oauth2` provider (not Google/Apple/Facebook/Twitter).\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: {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }): 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 */\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"]}
@@ -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.3.40"
19
+ private let pluginVersion: String = "8.4.1"
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.3.40",
3
+ "version": "8.4.1",
4
4
  "description": "All social logins in one plugin",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",
@@ -63,6 +63,7 @@ const PLATFORM = process.env.CAPACITOR_PLATFORM_NAME;
63
63
  // const androidGradlePath = path.join(PLUGIN_ROOT, 'android', 'build.gradle');
64
64
  const gradlePropertiesPath = path.join(PLUGIN_ROOT, 'android', 'gradle.properties');
65
65
  const podspecPath = path.join(PLUGIN_ROOT, 'CapgoCapacitorSocialLogin.podspec');
66
+ const packageSwiftPath = path.join(PLUGIN_ROOT, 'Package.swift');
66
67
  // Default provider configuration (backward compatible)
67
68
  const defaultProviders = {
68
69
  google: 'implementation',
@@ -250,60 +251,111 @@ function configureAndroid(providerConfig) {
250
251
  logError(`Error updating gradle.properties: ${error.message}`);
251
252
  }
252
253
  }
253
- // ============================================================================
254
- // iOS: Podspec Configuration
255
- // ============================================================================
254
+ function applyDependencyReplacements(content, replacements) {
255
+ let updatedContent = content;
256
+ let modified = false;
257
+ for (const replacement of replacements) {
258
+ if (replacement.old.test(updatedContent)) {
259
+ const before = updatedContent;
260
+ updatedContent = updatedContent.replace(replacement.old, replacement.new);
261
+ if (before !== updatedContent) {
262
+ modified = true;
263
+ }
264
+ }
265
+ }
266
+ return { content: updatedContent, modified };
267
+ }
268
+ function getPodspecReplacements(providerConfig) {
269
+ const podspecTrailingComment = '([ \\t]*#[^\\r\\n]*)?';
270
+ return [
271
+ {
272
+ // Google SignIn - handle both active and commented (including existing disabled comments)
273
+ old: new RegExp(`(#[ \\t]*)?s\\.dependency\\s+'GoogleSignIn',\\s*'~>\\s*9\\.0\\.0'${podspecTrailingComment}`),
274
+ new: providerConfig.google === 'implementation'
275
+ ? `s.dependency 'GoogleSignIn', '~> 9.0.0'`
276
+ : `# s.dependency 'GoogleSignIn', '~> 9.0.0' # Disabled via config (compileOnly)`,
277
+ },
278
+ {
279
+ // Facebook Core - handle both active and commented (including existing disabled comments)
280
+ old: new RegExp(`(#[ \\t]*)?s\\.dependency\\s+'FBSDKCoreKit',\\s*'~>\\s*18\\.0'${podspecTrailingComment}`),
281
+ new: providerConfig.facebook === 'implementation'
282
+ ? `s.dependency 'FBSDKCoreKit', '~> 18.0'`
283
+ : `# s.dependency 'FBSDKCoreKit', '~> 18.0' # Disabled via config (compileOnly)`,
284
+ },
285
+ {
286
+ // Facebook Login - handle both active and commented (including existing disabled comments)
287
+ old: new RegExp(`(#[ \\t]*)?s\\.dependency\\s+'FBSDKLoginKit',\\s*'~>\\s*18\\.0'${podspecTrailingComment}`),
288
+ new: providerConfig.facebook === 'implementation'
289
+ ? `s.dependency 'FBSDKLoginKit', '~> 18.0'`
290
+ : `# s.dependency 'FBSDKLoginKit', '~> 18.0' # Disabled via config (compileOnly)`,
291
+ },
292
+ {
293
+ // Alamofire (for Apple) - handle both active and commented (including existing disabled comments)
294
+ old: new RegExp(`(#[ \\t]*)?s\\.dependency\\s+'Alamofire',\\s*'~>\\s*5\\.10\\.2'${podspecTrailingComment}`),
295
+ new: providerConfig.apple === 'implementation'
296
+ ? `s.dependency 'Alamofire', '~> 5.10.2'`
297
+ : `# s.dependency 'Alamofire', '~> 5.10.2' # Disabled via config (compileOnly)`,
298
+ },
299
+ ];
300
+ }
301
+ function getPackageSwiftReplacements(providerConfig) {
302
+ const swiftCommentPrefix = '(?:\\/\\/[ \\t]*)*';
303
+ const swiftTrailingComment = '(?:[ \\t]*\\/\\/[^\\r\\n]*)?';
304
+ return [
305
+ {
306
+ old: new RegExp(`${swiftCommentPrefix}\\.package\\(url:\\s*"https:\\/\\/github\\.com\\/facebook\\/facebook-ios-sdk\\.git",\\s*\\.upToNextMajor\\(from:\\s*"[^"]+"\\)\\),${swiftTrailingComment}`),
307
+ new: providerConfig.facebook === 'implementation'
308
+ ? `.package(url: "https://github.com/facebook/facebook-ios-sdk.git", .upToNextMajor(from: "18.0.3")),`
309
+ : `// .package(url: "https://github.com/facebook/facebook-ios-sdk.git", .upToNextMajor(from: "18.0.3")), // Disabled via config (compileOnly)`,
310
+ },
311
+ {
312
+ old: new RegExp(`${swiftCommentPrefix}\\.package\\(url:\\s*"https:\\/\\/github\\.com\\/google\\/GoogleSignIn-iOS\\.git",\\s*\\.upToNextMajor\\(from:\\s*"[^"]+"\\)\\),${swiftTrailingComment}`),
313
+ new: providerConfig.google === 'implementation'
314
+ ? `.package(url: "https://github.com/google/GoogleSignIn-iOS.git", .upToNextMajor(from: "9.0.0")),`
315
+ : `// .package(url: "https://github.com/google/GoogleSignIn-iOS.git", .upToNextMajor(from: "9.0.0")), // Disabled via config (compileOnly)`,
316
+ },
317
+ {
318
+ old: new RegExp(`${swiftCommentPrefix}\\.package\\(url:\\s*"https:\\/\\/github\\.com\\/Alamofire\\/Alamofire\\.git",\\s*\\.upToNextMajor\\(from:\\s*"[^"]+"\\)\\)${swiftTrailingComment}`),
319
+ new: providerConfig.apple === 'implementation'
320
+ ? `.package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.11.2"))`
321
+ : `// .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.11.2")) // Disabled via config (compileOnly)`,
322
+ },
323
+ {
324
+ old: new RegExp(`${swiftCommentPrefix}\\.product\\(name:\\s*"FacebookCore",\\s*package:\\s*"facebook-ios-sdk"\\),${swiftTrailingComment}`),
325
+ new: providerConfig.facebook === 'implementation'
326
+ ? `.product(name: "FacebookCore", package: "facebook-ios-sdk"),`
327
+ : `// .product(name: "FacebookCore", package: "facebook-ios-sdk"), // Disabled via config (compileOnly)`,
328
+ },
329
+ {
330
+ old: new RegExp(`${swiftCommentPrefix}\\.product\\(name:\\s*"FacebookLogin",\\s*package:\\s*"facebook-ios-sdk"\\),${swiftTrailingComment}`),
331
+ new: providerConfig.facebook === 'implementation'
332
+ ? `.product(name: "FacebookLogin", package: "facebook-ios-sdk"),`
333
+ : `// .product(name: "FacebookLogin", package: "facebook-ios-sdk"), // Disabled via config (compileOnly)`,
334
+ },
335
+ {
336
+ old: new RegExp(`${swiftCommentPrefix}\\.product\\(name:\\s*"GoogleSignIn",\\s*package:\\s*"GoogleSignIn-iOS"\\),${swiftTrailingComment}`),
337
+ new: providerConfig.google === 'implementation'
338
+ ? `.product(name: "GoogleSignIn", package: "GoogleSignIn-iOS"),`
339
+ : `// .product(name: "GoogleSignIn", package: "GoogleSignIn-iOS"), // Disabled via config (compileOnly)`,
340
+ },
341
+ {
342
+ old: new RegExp(`${swiftCommentPrefix}\\.product\\(name:\\s*"Alamofire",\\s*package:\\s*"Alamofire"\\)${swiftTrailingComment}`),
343
+ new: providerConfig.apple === 'implementation'
344
+ ? `.product(name: "Alamofire", package: "Alamofire")`
345
+ : `// .product(name: "Alamofire", package: "Alamofire") // Disabled via config (compileOnly)`,
346
+ },
347
+ ];
348
+ }
256
349
  /**
257
- * Modify Podspec for iOS conditional dependencies
350
+ * Modify Podspec and Package.swift for iOS conditional dependencies
258
351
  */
259
352
  function configureIOS(providerConfig) {
260
353
  logInfo('Configuring iOS dependencies...');
354
+ let success = true;
261
355
  try {
262
- let podspecContent = fs.readFileSync(podspecPath, 'utf8');
263
- // Replace dependency declarations with conditional ones
264
- // Handle both active and commented-out dependencies (including existing disabled comments)
265
- const replacements = [
266
- {
267
- // Google SignIn - handle both active and commented (including existing disabled comments)
268
- old: /(#\s*)?s\.dependency\s+'GoogleSignIn',\s*'~>\s*9\.0\.0'(\s*#.*)?/,
269
- new: providerConfig.google === 'implementation'
270
- ? `s.dependency 'GoogleSignIn', '~> 9.0.0'`
271
- : `# s.dependency 'GoogleSignIn', '~> 9.0.0' # Disabled via config (compileOnly)`,
272
- },
273
- {
274
- // Facebook Core - handle both active and commented (including existing disabled comments)
275
- old: /(#\s*)?s\.dependency\s+'FBSDKCoreKit',\s*'~>\s*18\.0'(\s*#.*)?/,
276
- new: providerConfig.facebook === 'implementation'
277
- ? `s.dependency 'FBSDKCoreKit', '~> 18.0'`
278
- : `# s.dependency 'FBSDKCoreKit', '~> 18.0' # Disabled via config (compileOnly)`,
279
- },
280
- {
281
- // Facebook Login - handle both active and commented (including existing disabled comments)
282
- old: /(#\s*)?s\.dependency\s+'FBSDKLoginKit',\s*'~>\s*18\.0'(\s*#.*)?/,
283
- new: providerConfig.facebook === 'implementation'
284
- ? `s.dependency 'FBSDKLoginKit', '~> 18.0'`
285
- : `# s.dependency 'FBSDKLoginKit', '~> 18.0' # Disabled via config (compileOnly)`,
286
- },
287
- {
288
- // Alamofire (for Apple) - handle both active and commented (including existing disabled comments)
289
- old: /(#\s*)?s\.dependency\s+'Alamofire',\s*'~>\s*5\.10\.2'(\s*#.*)?/,
290
- new: providerConfig.apple === 'implementation'
291
- ? `s.dependency 'Alamofire', '~> 5.10.2'`
292
- : `# s.dependency 'Alamofire', '~> 5.10.2' # Disabled via config (compileOnly)`,
293
- },
294
- ];
295
- let modified = false;
296
- for (const replacement of replacements) {
297
- if (replacement.old.test(podspecContent)) {
298
- const before = podspecContent;
299
- podspecContent = podspecContent.replace(replacement.old, replacement.new);
300
- if (before !== podspecContent) {
301
- modified = true;
302
- }
303
- }
304
- }
305
- if (modified) {
306
- fs.writeFileSync(podspecPath, podspecContent, 'utf8');
356
+ const podspecResult = applyDependencyReplacements(fs.readFileSync(podspecPath, 'utf8'), getPodspecReplacements(providerConfig));
357
+ if (podspecResult.modified) {
358
+ fs.writeFileSync(podspecPath, podspecResult.content, 'utf8');
307
359
  logSuccess('Modified podspec');
308
360
  }
309
361
  else {
@@ -312,7 +364,27 @@ function configureIOS(providerConfig) {
312
364
  }
313
365
  catch (error) {
314
366
  logError(`Error modifying podspec: ${error.message}`);
367
+ success = false;
368
+ }
369
+ if (!fs.existsSync(packageSwiftPath)) {
370
+ logError('Package.swift not found; Swift Package Manager configuration is required');
371
+ return false;
372
+ }
373
+ try {
374
+ const packageSwiftResult = applyDependencyReplacements(fs.readFileSync(packageSwiftPath, 'utf8'), getPackageSwiftReplacements(providerConfig));
375
+ if (packageSwiftResult.modified) {
376
+ fs.writeFileSync(packageSwiftPath, packageSwiftResult.content, 'utf8');
377
+ logSuccess('Modified Package.swift');
378
+ }
379
+ else {
380
+ logInfo('Package.swift already up to date');
381
+ }
315
382
  }
383
+ catch (error) {
384
+ logError(`Error modifying Package.swift: ${error.message}`);
385
+ success = false;
386
+ }
387
+ return success;
316
388
  }
317
389
  // ============================================================================
318
390
  // Web: No Configuration Needed
@@ -331,6 +403,7 @@ function configureWeb() {
331
403
  * Main execution
332
404
  */
333
405
  function main() {
406
+ let configurationSucceeded = true;
334
407
  // Route to platform-specific configuration
335
408
  switch (PLATFORM) {
336
409
  case 'android':
@@ -339,15 +412,13 @@ function main() {
339
412
  logInfo('Configuring dynamic provider dependencies for SocialLogin');
340
413
  logProviderConfig(androidConfig);
341
414
  configureAndroid(androidConfig);
342
- logSuccess('Configuration complete\n');
343
415
  break;
344
416
  case 'ios':
345
417
  // eslint-disable-next-line no-case-declarations
346
418
  const iosConfig = getProviderConfig();
347
419
  logInfo('Configuring dynamic provider dependencies for SocialLogin');
348
420
  logProviderConfig(iosConfig);
349
- configureIOS(iosConfig);
350
- logSuccess('Configuration complete\n');
421
+ configurationSucceeded = configureIOS(iosConfig);
351
422
  break;
352
423
  case 'web':
353
424
  configureWeb();
@@ -360,10 +431,14 @@ function main() {
360
431
  logProviderConfig(defaultConfig);
361
432
  logWarning(`Unknown platform: ${PLATFORM || 'undefined'}, configuring all platforms`);
362
433
  configureAndroid(defaultConfig);
363
- configureIOS(defaultConfig);
364
- logSuccess('Configuration complete\n');
434
+ configurationSucceeded = configureIOS(defaultConfig);
365
435
  break;
366
436
  }
437
+ if (!configurationSucceeded) {
438
+ logError('Configuration failed\n');
439
+ process.exit(1);
440
+ }
441
+ logSuccess('Configuration complete\n');
367
442
  }
368
443
  // Run if executed directly
369
444
  if (require.main === module) {