@capgo/capacitor-social-login 8.7.1 → 8.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,6 +61,8 @@ public class AppleProvider implements SocialProvider {
61
61
  private static final String APPLE_DATA_PREFERENCE = "APPLE_LOGIN_APPLE_DATA_83b2d6db-17fe-49c9-8c33-e3f5d02f9f84";
62
62
 
63
63
  private PluginCall lastcall;
64
+ private String pendingRedirectState;
65
+ private final AppleRedirectLoginCoordinator redirectLoginCoordinator = new AppleRedirectLoginCoordinator();
64
66
  private String appleAuthURLFull;
65
67
 
66
68
  private String idToken;
@@ -125,6 +127,19 @@ public class AppleProvider implements SocialProvider {
125
127
  }
126
128
  }
127
129
 
130
+ /**
131
+ * Called when the host activity resumes after Custom Tabs without receiving a redirect.
132
+ */
133
+ void handleUserReturnedWithoutCallback() {
134
+ if (!redirectLoginCoordinator.shouldRejectOnActivityResume()) {
135
+ return;
136
+ }
137
+ if (lastcall != null) {
138
+ lastcall.reject(AppleRedirectLoginCoordinator.USER_CANCELLED_MESSAGE, AppleRedirectLoginCoordinator.USER_CANCELLED_CODE);
139
+ }
140
+ clearPendingLoginCall();
141
+ }
142
+
128
143
  public void handleIntent(Intent intent) {
129
144
  // Extract information from the URI
130
145
  Uri data = intent.getData();
@@ -222,6 +237,7 @@ public class AppleProvider implements SocialProvider {
222
237
 
223
238
  private void loginWithRedirect(PluginCall call, JSONObject config) {
224
239
  String state = UUID.randomUUID().toString();
240
+ this.pendingRedirectState = state;
225
241
 
226
242
  // Extract scopes from config
227
243
  String scopes = DEFAULT_SCOPE;
@@ -262,7 +278,7 @@ public class AppleProvider implements SocialProvider {
262
278
 
263
279
  if (context == null || activity == null) {
264
280
  this.lastcall.reject("Context or Activity is null");
265
- this.lastcall = null;
281
+ clearPendingLoginCall();
266
282
  return;
267
283
  }
268
284
 
@@ -320,6 +336,13 @@ public class AppleProvider implements SocialProvider {
320
336
  }
321
337
 
322
338
  Uri uri = Uri.parse(url);
339
+ String callbackState = uri.getQueryParameter("state");
340
+ if (!matchesPendingRedirectState(pendingRedirectState, callbackState)) {
341
+ return;
342
+ }
343
+
344
+ redirectLoginCoordinator.onRedirectReceived();
345
+
323
346
  String success = uri.getQueryParameter("success");
324
347
  if ("true".equals(success)) {
325
348
  String accessToken = uri.getQueryParameter("access_token");
@@ -359,6 +382,7 @@ public class AppleProvider implements SocialProvider {
359
382
  this.lastcall.reject("Expected proper tokens from backend but received authorization code only");
360
383
  } else {
361
384
  // Legacy mode: exchange the authorization code for tokens
385
+ redirectLoginCoordinator.onTokenExchangeStarted();
362
386
  requestForAccessToken(appleAuthCode, appleClientSecret);
363
387
  return; // Don't clear lastcall here, it will be cleared in the callback
364
388
  }
@@ -366,7 +390,17 @@ public class AppleProvider implements SocialProvider {
366
390
  } else {
367
391
  this.lastcall.reject("We couldn't get the Auth Code");
368
392
  }
393
+ clearPendingLoginCall();
394
+ }
395
+
396
+ private void clearPendingLoginCall() {
369
397
  this.lastcall = null;
398
+ this.pendingRedirectState = null;
399
+ redirectLoginCoordinator.onLoginFinished();
400
+ }
401
+
402
+ static boolean matchesPendingRedirectState(String pendingState, String callbackState) {
403
+ return pendingState != null && pendingState.equals(callbackState);
370
404
  }
371
405
 
372
406
  private void requestForAccessToken(String code, String clientSecret) {
@@ -389,7 +423,7 @@ public class AppleProvider implements SocialProvider {
389
423
  public void onFailure(@NonNull Call call, @NonNull IOException e) {
390
424
  if (AppleProvider.this.lastcall != null) {
391
425
  AppleProvider.this.lastcall.reject("Cannot get access_token", e);
392
- AppleProvider.this.lastcall = null;
426
+ clearPendingLoginCall();
393
427
  } else {
394
428
  Log.e(SocialLoginPlugin.LOG_TAG, "Cannot get access_token: lastcall is null. Error: " + e.getMessage(), e);
395
429
  }
@@ -423,14 +457,14 @@ public class AppleProvider implements SocialProvider {
423
457
 
424
458
  if (AppleProvider.this.lastcall != null) {
425
459
  AppleProvider.this.lastcall.resolve(appleResponse);
426
- AppleProvider.this.lastcall = null;
460
+ clearPendingLoginCall();
427
461
  } else {
428
462
  Log.e(SocialLoginPlugin.LOG_TAG, "Cannot resolve access_token response: lastcall is null");
429
463
  }
430
464
  } catch (Exception e) {
431
465
  if (AppleProvider.this.lastcall != null) {
432
466
  AppleProvider.this.lastcall.reject("Cannot get access_token", e);
433
- AppleProvider.this.lastcall = null;
467
+ clearPendingLoginCall();
434
468
  } else {
435
469
  Log.e(SocialLoginPlugin.LOG_TAG, "Cannot get access_token: lastcall is null. Error: " + e.getMessage(), e);
436
470
  }
@@ -472,6 +506,7 @@ public class AppleProvider implements SocialProvider {
472
506
 
473
507
  @SuppressLint("SetJavaScriptEnabled")
474
508
  private void setupWebview(Context context, Activity activity, PluginCall call, String url) {
509
+ redirectLoginCoordinator.onCustomTabLaunched();
475
510
  CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(getCustomTabsSession());
476
511
 
477
512
  builder.build().launchUrl(context, Uri.parse(url));
@@ -0,0 +1,36 @@
1
+ package ee.forgr.capacitor.social.login;
2
+
3
+ /**
4
+ * Tracks Custom Tabs redirect login state so we can detect when the user returns without a callback.
5
+ */
6
+ final class AppleRedirectLoginCoordinator {
7
+
8
+ static final String USER_CANCELLED_CODE = "USER_CANCELLED";
9
+ static final String USER_CANCELLED_MESSAGE = "User cancelled";
10
+
11
+ private boolean customTabsRedirectPending;
12
+ private boolean tokenExchangeInProgress;
13
+
14
+ void onCustomTabLaunched() {
15
+ customTabsRedirectPending = true;
16
+ tokenExchangeInProgress = false;
17
+ }
18
+
19
+ void onRedirectReceived() {
20
+ customTabsRedirectPending = false;
21
+ }
22
+
23
+ void onTokenExchangeStarted() {
24
+ customTabsRedirectPending = false;
25
+ tokenExchangeInProgress = true;
26
+ }
27
+
28
+ void onLoginFinished() {
29
+ customTabsRedirectPending = false;
30
+ tokenExchangeInProgress = false;
31
+ }
32
+
33
+ boolean shouldRejectOnActivityResume() {
34
+ return customTabsRedirectPending && !tokenExchangeInProgress;
35
+ }
36
+ }
@@ -957,7 +957,7 @@ public class OAuth2Provider implements SocialProvider {
957
957
  }
958
958
 
959
959
  private static String normalizePath(String path) {
960
- if (path == null || path.isEmpty()) {
960
+ if (path == null || path.isEmpty() || "/".equals(path)) {
961
961
  return "";
962
962
  }
963
963
  if (path.length() > 1 && path.endsWith("/")) {
@@ -27,7 +27,7 @@ import org.json.JSONObject;
27
27
  @CapacitorPlugin(name = "SocialLogin")
28
28
  public class SocialLoginPlugin extends Plugin {
29
29
 
30
- private final String pluginVersion = "8.7.1";
30
+ private final String pluginVersion = "8.7.3";
31
31
 
32
32
  public static String LOG_TAG = "CapgoSocialLogin";
33
33
  private static final String USER_CANCELLED_CODE = "USER_CANCELLED";
@@ -887,6 +887,11 @@ public class SocialLoginPlugin extends Plugin {
887
887
  ((OAuth2Provider) oauth2Provider).handleUserReturnedWithoutCallback();
888
888
  }
889
889
 
890
+ SocialProvider appleProvider = socialProviderHashMap.get("apple");
891
+ if (appleProvider instanceof AppleProvider) {
892
+ ((AppleProvider) appleProvider).handleUserReturnedWithoutCallback();
893
+ }
894
+
890
895
  // User returned without redirect: cancel when we saw pause, or after launch grace if pause was missed
891
896
  if (openAuthSessionSavedCall != null) {
892
897
  boolean pausedAfterLaunch = openAuthSessionPaused;
@@ -63,7 +63,8 @@ export function isOAuthPopupContext() {
63
63
  export function shouldAutoFinishOAuthRedirect() {
64
64
  if (!localStorage.getItem(OAUTH_STATE_KEY))
65
65
  return false;
66
- return isOAuthPopupContext() || hasOAuthRedirectParams();
66
+ // Popup only. Same-window redirect (flow: 'redirect') must call handleRedirectCallback().
67
+ return isOAuthPopupContext();
67
68
  }
68
69
  /**
69
70
  * Deliver OAuth result from popup to opener via all available channels.
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-popup-bridge.js","sourceRoot":"","sources":["../../src/oauth-popup-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,CAAC,MAAM,eAAe,GAAG,4BAA4B,CAAC;AAC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AAC,IAAI,CAAC,CAAC;IAC1B,CAAC,CAAC;IAEF,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAClD,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAClD,IAAI,gBAAgB,EAAE,CAAC;QACrB,gBAAgB,CAAC,SAAS,GAAG,eAAe,CAAC;IAC/C,CAAC;IAED,uFAAuF;IACvF,MAAM,YAAY,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE;QAC3C,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YAC5C,IAAI,CAAC,GAAG;gBAAE,OAAO;YACjB,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;YACnC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC7B,WAAW,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QAAC,WAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC,EAAE,GAAG,CAAC,CAAC;IAER,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;QACrD,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;QACrD,aAAa,CAAC,YAAY,CAAC,CAAC;QAC5B,IAAI,gBAAgB,EAAE,CAAC;YACrB,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC;YACH,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC;QAAC,WAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * COOP-safe OAuth popup communication bridge.\n *\n * When Cross-Origin-Opener-Policy severs window.opener, postMessage and popup.closed\n * checks fail. This module uses localStorage + storage events and BroadcastChannel\n * as reliable fallbacks that work across same-origin popup windows.\n */\n\nexport const OAUTH_STATE_KEY = 'social_login_oauth_pending';\nexport const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';\nexport const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';\nexport const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';\n\nexport const POPUP_WINDOW_NAMES = new Set([\n 'OAuth2Login',\n 'XLogin',\n 'Google Sign In',\n 'Authorization',\n 'TelegramLogin',\n]);\n\nexport type OAuthBridgeMessage = Record<string, unknown> & {\n type: 'oauth-response' | 'oauth-error';\n};\n\nexport function getOAuthResultKey(nonce: string): string {\n return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;\n}\n\nexport function getBroadcastChannelName(provider: string, nonceOrState: string): string {\n if (provider === 'oauth2') return `oauth2_${nonceOrState}`;\n if (provider === 'twitter') return `twitter_oauth_${nonceOrState}`;\n if (provider === 'telegram') return `telegram_oauth_${nonceOrState}`;\n return `google_oauth_${nonceOrState}`;\n}\n\nexport function markOAuthPopup(nonce: string): void {\n try {\n sessionStorage.removeItem(OAUTH_DELIVERED_KEY);\n sessionStorage.setItem(OAUTH_POPUP_SESSION_KEY, nonce);\n } catch {\n // sessionStorage may be unavailable in some contexts\n }\n}\n\nexport function clearOAuthPopupMarker(): void {\n try {\n sessionStorage.removeItem(OAUTH_POPUP_SESSION_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function hasOAuthRedirectParams(): boolean {\n const search = new URLSearchParams(window.location.search);\n const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));\n return (\n search.has('code') ||\n search.has('error') ||\n (search.has('hash') && search.has('auth_date')) ||\n hash.has('access_token') ||\n hash.has('id_token') ||\n hash.has('error')\n );\n}\n\nexport function isOAuthPopupContext(): boolean {\n if (typeof window === 'undefined') return false;\n return !!window.opener || POPUP_WINDOW_NAMES.has(window.name) || !!sessionStorage.getItem(OAUTH_POPUP_SESSION_KEY);\n}\n\nexport function shouldAutoFinishOAuthRedirect(): boolean {\n if (!localStorage.getItem(OAUTH_STATE_KEY)) return false;\n return isOAuthPopupContext() || hasOAuthRedirectParams();\n}\n\n/**\n * Deliver OAuth result from popup to opener via all available channels.\n */\nexport function deliverOAuthResult(\n provider: string,\n nonceOrState: string | undefined,\n message: OAuthBridgeMessage,\n): void {\n // Prevent duplicate delivery when both eager handler and plugin constructor run\n try {\n if (sessionStorage.getItem(OAUTH_DELIVERED_KEY)) return;\n sessionStorage.setItem(OAUTH_DELIVERED_KEY, '1');\n } catch {\n // sessionStorage unavailable\n }\n\n // postMessage when opener reference is still available\n try {\n if (window.opener) {\n window.opener.postMessage(message, window.location.origin);\n }\n } catch {\n // COOP may block opener access\n }\n\n // BroadcastChannel works across same-origin windows without opener\n if (nonceOrState) {\n try {\n const channel = new BroadcastChannel(getBroadcastChannelName(provider, nonceOrState));\n channel.postMessage(message);\n channel.close();\n } catch {\n // BroadcastChannel not supported\n }\n }\n\n // localStorage + storage event is the most COOP-resilient fallback\n if (nonceOrState) {\n try {\n localStorage.setItem(getOAuthResultKey(nonceOrState), JSON.stringify({ ...message, _ts: Date.now() }));\n } catch {\n // localStorage may be full or unavailable\n }\n }\n}\n\nexport interface OAuthResultListener {\n onResponse: (data: Record<string, unknown>) => void;\n onError: (error: string, code?: string) => void;\n}\n\n/**\n * Listen for OAuth results from popup via postMessage, BroadcastChannel, and localStorage.\n * Returns a cleanup function.\n */\nexport function listenForOAuthResult(\n provider: string,\n nonceOrState: string,\n handlers: OAuthResultListener,\n): () => void {\n const resultKey = getOAuthResultKey(nonceOrState);\n const channelName = getBroadcastChannelName(provider, nonceOrState);\n\n let broadcastChannel: BroadcastChannel | null = null;\n try {\n broadcastChannel = new BroadcastChannel(channelName);\n } catch {\n // BroadcastChannel not supported\n }\n\n const processData = (data: Record<string, unknown>): boolean => {\n if (data?.source && String(data.source).startsWith('angular')) return false;\n\n if (data?.type === 'oauth-response') {\n handlers.onResponse(data);\n return true;\n }\n if (data?.type === 'oauth-error') {\n handlers.onError((data.error as string) || 'User cancelled the OAuth flow', data.code as string | undefined);\n return true;\n }\n return false;\n };\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== window.location.origin) return;\n processData(event.data);\n };\n\n const handleStorage = (event: StorageEvent) => {\n if (event.key !== resultKey || !event.newValue) return;\n try {\n const data = JSON.parse(event.newValue);\n localStorage.removeItem(resultKey);\n processData(data);\n } catch {\n // ignore parse errors\n }\n };\n\n const handleBroadcast = (event: MessageEvent) => {\n processData(event.data);\n };\n\n window.addEventListener('message', handleMessage);\n window.addEventListener('storage', handleStorage);\n if (broadcastChannel) {\n broadcastChannel.onmessage = handleBroadcast;\n }\n\n // Poll localStorage as fallback when storage event is missed (e.g. same-window writes)\n const pollInterval = window.setInterval(() => {\n try {\n const raw = localStorage.getItem(resultKey);\n if (!raw) return;\n localStorage.removeItem(resultKey);\n const data = JSON.parse(raw);\n processData(data);\n } catch {\n // ignore\n }\n }, 300);\n\n return () => {\n window.removeEventListener('message', handleMessage);\n window.removeEventListener('storage', handleStorage);\n clearInterval(pollInterval);\n if (broadcastChannel) {\n broadcastChannel.close();\n }\n try {\n localStorage.removeItem(resultKey);\n } catch {\n // ignore\n }\n };\n}\n"]}
1
+ {"version":3,"file":"oauth-popup-bridge.js","sourceRoot":"","sources":["../../src/oauth-popup-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,CAAC,MAAM,eAAe,GAAG,4BAA4B,CAAC;AAC5D,MAAM,CAAC,MAAM,uBAAuB,GAAG,0BAA0B,CAAC;AAClE,MAAM,CAAC,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AACpE,MAAM,CAAC,MAAM,mBAAmB,GAAG,8BAA8B,CAAC;AAElE,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACxC,aAAa;IACb,QAAQ;IACR,gBAAgB;IAChB,eAAe;IACf,eAAe;CAChB,CAAC,CAAC;AAMH,MAAM,UAAU,iBAAiB,CAAC,KA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QAC3C,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YAC5C,IAAI,CAAC,GAAG;gBAAE,OAAO;YACjB,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;YACnC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC7B,WAAW,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QAAC,WAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC,EAAE,GAAG,CAAC,CAAC;IAER,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;QACrD,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;QACrD,aAAa,CAAC,YAAY,CAAC,CAAC;QAC5B,IAAI,gBAAgB,EAAE,CAAC;YACrB,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC;YACH,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC;QAAC,WAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * COOP-safe OAuth popup communication bridge.\n *\n * When Cross-Origin-Opener-Policy severs window.opener, postMessage and popup.closed\n * checks fail. This module uses localStorage + storage events and BroadcastChannel\n * as reliable fallbacks that work across same-origin popup windows.\n */\n\nexport const OAUTH_STATE_KEY = 'social_login_oauth_pending';\nexport const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';\nexport const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';\nexport const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';\n\nexport const POPUP_WINDOW_NAMES = new Set([\n 'OAuth2Login',\n 'XLogin',\n 'Google Sign In',\n 'Authorization',\n 'TelegramLogin',\n]);\n\nexport type OAuthBridgeMessage = Record<string, unknown> & {\n type: 'oauth-response' | 'oauth-error';\n};\n\nexport function getOAuthResultKey(nonce: string): string {\n return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;\n}\n\nexport function getBroadcastChannelName(provider: string, nonceOrState: string): string {\n if (provider === 'oauth2') return `oauth2_${nonceOrState}`;\n if (provider === 'twitter') return `twitter_oauth_${nonceOrState}`;\n if (provider === 'telegram') return `telegram_oauth_${nonceOrState}`;\n return `google_oauth_${nonceOrState}`;\n}\n\nexport function markOAuthPopup(nonce: string): void {\n try {\n sessionStorage.removeItem(OAUTH_DELIVERED_KEY);\n sessionStorage.setItem(OAUTH_POPUP_SESSION_KEY, nonce);\n } catch {\n // sessionStorage may be unavailable in some contexts\n }\n}\n\nexport function clearOAuthPopupMarker(): void {\n try {\n sessionStorage.removeItem(OAUTH_POPUP_SESSION_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function hasOAuthRedirectParams(): boolean {\n const search = new URLSearchParams(window.location.search);\n const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));\n return (\n search.has('code') ||\n search.has('error') ||\n (search.has('hash') && search.has('auth_date')) ||\n hash.has('access_token') ||\n hash.has('id_token') ||\n hash.has('error')\n );\n}\n\nexport function isOAuthPopupContext(): boolean {\n if (typeof window === 'undefined') return false;\n return !!window.opener || POPUP_WINDOW_NAMES.has(window.name) || !!sessionStorage.getItem(OAUTH_POPUP_SESSION_KEY);\n}\n\nexport function shouldAutoFinishOAuthRedirect(): boolean {\n if (!localStorage.getItem(OAUTH_STATE_KEY)) return false;\n // Popup only. Same-window redirect (flow: 'redirect') must call handleRedirectCallback().\n return isOAuthPopupContext();\n}\n\n/**\n * Deliver OAuth result from popup to opener via all available channels.\n */\nexport function deliverOAuthResult(\n provider: string,\n nonceOrState: string | undefined,\n message: OAuthBridgeMessage,\n): void {\n // Prevent duplicate delivery when both eager handler and plugin constructor run\n try {\n if (sessionStorage.getItem(OAUTH_DELIVERED_KEY)) return;\n sessionStorage.setItem(OAUTH_DELIVERED_KEY, '1');\n } catch {\n // sessionStorage unavailable\n }\n\n // postMessage when opener reference is still available\n try {\n if (window.opener) {\n window.opener.postMessage(message, window.location.origin);\n }\n } catch {\n // COOP may block opener access\n }\n\n // BroadcastChannel works across same-origin windows without opener\n if (nonceOrState) {\n try {\n const channel = new BroadcastChannel(getBroadcastChannelName(provider, nonceOrState));\n channel.postMessage(message);\n channel.close();\n } catch {\n // BroadcastChannel not supported\n }\n }\n\n // localStorage + storage event is the most COOP-resilient fallback\n if (nonceOrState) {\n try {\n localStorage.setItem(getOAuthResultKey(nonceOrState), JSON.stringify({ ...message, _ts: Date.now() }));\n } catch {\n // localStorage may be full or unavailable\n }\n }\n}\n\nexport interface OAuthResultListener {\n onResponse: (data: Record<string, unknown>) => void;\n onError: (error: string, code?: string) => void;\n}\n\n/**\n * Listen for OAuth results from popup via postMessage, BroadcastChannel, and localStorage.\n * Returns a cleanup function.\n */\nexport function listenForOAuthResult(\n provider: string,\n nonceOrState: string,\n handlers: OAuthResultListener,\n): () => void {\n const resultKey = getOAuthResultKey(nonceOrState);\n const channelName = getBroadcastChannelName(provider, nonceOrState);\n\n let broadcastChannel: BroadcastChannel | null = null;\n try {\n broadcastChannel = new BroadcastChannel(channelName);\n } catch {\n // BroadcastChannel not supported\n }\n\n const processData = (data: Record<string, unknown>): boolean => {\n if (data?.source && String(data.source).startsWith('angular')) return false;\n\n if (data?.type === 'oauth-response') {\n handlers.onResponse(data);\n return true;\n }\n if (data?.type === 'oauth-error') {\n handlers.onError((data.error as string) || 'User cancelled the OAuth flow', data.code as string | undefined);\n return true;\n }\n return false;\n };\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== window.location.origin) return;\n processData(event.data);\n };\n\n const handleStorage = (event: StorageEvent) => {\n if (event.key !== resultKey || !event.newValue) return;\n try {\n const data = JSON.parse(event.newValue);\n localStorage.removeItem(resultKey);\n processData(data);\n } catch {\n // ignore parse errors\n }\n };\n\n const handleBroadcast = (event: MessageEvent) => {\n processData(event.data);\n };\n\n window.addEventListener('message', handleMessage);\n window.addEventListener('storage', handleStorage);\n if (broadcastChannel) {\n broadcastChannel.onmessage = handleBroadcast;\n }\n\n // Poll localStorage as fallback when storage event is missed (e.g. same-window writes)\n const pollInterval = window.setInterval(() => {\n try {\n const raw = localStorage.getItem(resultKey);\n if (!raw) return;\n localStorage.removeItem(resultKey);\n const data = JSON.parse(raw);\n processData(data);\n } catch {\n // ignore\n }\n }, 300);\n\n return () => {\n window.removeEventListener('message', handleMessage);\n window.removeEventListener('storage', handleStorage);\n clearInterval(pollInterval);\n if (broadcastChannel) {\n broadcastChannel.close();\n }\n try {\n localStorage.removeItem(resultKey);\n } catch {\n // ignore\n }\n };\n}\n"]}
@@ -143,16 +143,6 @@ function clearOAuthPopupMarker() {
143
143
  // ignore
144
144
  }
145
145
  }
146
- function hasOAuthRedirectParams() {
147
- const search = new URLSearchParams(window.location.search);
148
- const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));
149
- return (search.has('code') ||
150
- search.has('error') ||
151
- (search.has('hash') && search.has('auth_date')) ||
152
- hash.has('access_token') ||
153
- hash.has('id_token') ||
154
- hash.has('error'));
155
- }
156
146
  function isOAuthPopupContext() {
157
147
  if (typeof window === 'undefined')
158
148
  return false;
@@ -161,7 +151,8 @@ function isOAuthPopupContext() {
161
151
  function shouldAutoFinishOAuthRedirect() {
162
152
  if (!localStorage.getItem(OAUTH_STATE_KEY))
163
153
  return false;
164
- return isOAuthPopupContext() || hasOAuthRedirectParams();
154
+ // Popup only. Same-window redirect (flow: 'redirect') must call handleRedirectCallback().
155
+ return isOAuthPopupContext();
165
156
  }
166
157
  /**
167
158
  * Deliver OAuth result from popup to opener via all available channels.