@capgo/capacitor-social-login 8.4.4 → 8.4.5

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.
@@ -24,7 +24,7 @@ import org.json.JSONObject;
24
24
  @CapacitorPlugin(name = "SocialLogin")
25
25
  public class SocialLoginPlugin extends Plugin {
26
26
 
27
- private final String pluginVersion = "8.4.4";
27
+ private final String pluginVersion = "8.4.5";
28
28
 
29
29
  public static String LOG_TAG = "CapgoSocialLogin";
30
30
  public HashMap<String, SocialProvider> socialProviderHashMap = new HashMap<>();
@@ -1,5 +1,6 @@
1
1
  import { BaseSocialLogin } from './base';
2
2
  import { createUserCancelledError, inferUserCancelledError } from './errors';
3
+ import { listenForOAuthResult, markOAuthPopup } from './oauth-popup-bridge';
3
4
  const GOOGLE_OFFLINE_REFRESH_MESSAGE = "Google refresh() is not available when using offline mode. Offline mode only returns serverAuthCode for backend token exchange. Send serverAuthCode to your backend and refresh tokens there, or switch google.mode to 'online' for client-side refresh.";
4
5
  export class GoogleSocialLogin extends BaseSocialLogin {
5
6
  constructor() {
@@ -143,7 +144,6 @@ export class GoogleSocialLogin extends BaseSocialLogin {
143
144
  };
144
145
  }
145
146
  const hash = url.hash.substring(1);
146
- console.log('handleOAuthRedirect', url.hash);
147
147
  if (!hash)
148
148
  return null;
149
149
  const params = new URLSearchParams(hash);
@@ -154,7 +154,6 @@ export class GoogleSocialLogin extends BaseSocialLogin {
154
154
  const errorDescription = params.get('error_description') || error;
155
155
  return { error: errorDescription };
156
156
  }
157
- console.log('handleOAuthRedirect ok');
158
157
  const accessToken = params.get('access_token');
159
158
  const idToken = params.get('id_token');
160
159
  if (accessToken && idToken) {
@@ -306,30 +305,25 @@ export class GoogleSocialLogin extends BaseSocialLogin {
306
305
  const left = window.screenX + (window.outerWidth - width) / 2;
307
306
  const top = window.screenY + (window.outerHeight - height) / 2;
308
307
  localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'google', loginType: this.loginType, nonce }));
308
+ markOAuthPopup(nonce);
309
309
  const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);
310
310
  let popupClosedInterval;
311
311
  let timeoutHandle;
312
- // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)
313
- const channelName = `google_oauth_${nonce || Date.now()}`;
314
- let broadcastChannel = null;
315
- try {
316
- broadcastChannel = new BroadcastChannel(channelName);
317
- }
318
- catch (_b) {
319
- // BroadcastChannel not supported, fall back to postMessage only
320
- }
312
+ let removeOAuthListener = null;
321
313
  // This may never return...
322
314
  return new Promise((resolve, reject) => {
323
315
  if (!popup) {
324
316
  reject(new Error('Failed to open popup'));
325
317
  return;
326
318
  }
319
+ let settled = false;
320
+ let coopErrorDetected = false;
327
321
  const cleanup = (shouldClose = false) => {
328
- window.removeEventListener('message', handleMessage);
329
322
  clearInterval(popupClosedInterval);
330
323
  clearTimeout(timeoutHandle);
331
- if (broadcastChannel) {
332
- broadcastChannel.close();
324
+ if (removeOAuthListener) {
325
+ removeOAuthListener();
326
+ removeOAuthListener = null;
333
327
  }
334
328
  if (shouldClose) {
335
329
  try {
@@ -340,102 +334,93 @@ export class GoogleSocialLogin extends BaseSocialLogin {
340
334
  }
341
335
  }
342
336
  };
337
+ const settle = (shouldClose, action) => {
338
+ if (settled)
339
+ return;
340
+ settled = true;
341
+ cleanup(shouldClose);
342
+ action();
343
+ };
343
344
  const processOAuthResponse = (data) => {
344
345
  if (this.loginType === 'online') {
345
346
  const { accessToken, idToken } = data;
346
347
  if (accessToken && idToken) {
347
348
  const profile = this.parseJwt(idToken);
348
349
  this.persistStateGoogle(accessToken.token, idToken);
349
- resolve({
350
- provider: 'google',
351
- result: {
352
- accessToken: {
353
- token: accessToken.token,
350
+ settle(true, () => {
351
+ resolve({
352
+ provider: 'google',
353
+ result: {
354
+ accessToken: {
355
+ token: accessToken.token,
356
+ },
357
+ idToken,
358
+ profile: {
359
+ email: profile.email || null,
360
+ familyName: profile.family_name || null,
361
+ givenName: profile.given_name || null,
362
+ id: profile.sub || null,
363
+ name: profile.name || null,
364
+ imageUrl: profile.picture || null,
365
+ },
366
+ responseType: 'online',
354
367
  },
355
- idToken,
356
- profile: {
357
- email: profile.email || null,
358
- familyName: profile.family_name || null,
359
- givenName: profile.given_name || null,
360
- id: profile.sub || null,
361
- name: profile.name || null,
362
- imageUrl: profile.picture || null,
363
- },
364
- responseType: 'online',
365
- },
368
+ });
366
369
  });
367
370
  }
368
371
  else {
369
- reject(new Error('Invalid OAuth response: missing accessToken or idToken'));
372
+ settle(true, () => {
373
+ reject(new Error('Invalid OAuth response: missing accessToken or idToken'));
374
+ });
370
375
  }
371
376
  }
372
377
  else {
373
378
  const { serverAuthCode } = data;
374
379
  if (!serverAuthCode) {
375
- reject(new Error('Invalid OAuth response: missing serverAuthCode'));
380
+ settle(true, () => {
381
+ reject(new Error('Invalid OAuth response: missing serverAuthCode'));
382
+ });
376
383
  return;
377
384
  }
378
- resolve({
379
- provider: 'google',
380
- result: {
381
- responseType: 'offline',
382
- serverAuthCode,
383
- },
385
+ settle(true, () => {
386
+ resolve({
387
+ provider: 'google',
388
+ result: {
389
+ responseType: 'offline',
390
+ serverAuthCode,
391
+ },
392
+ });
384
393
  });
385
394
  }
386
395
  };
387
- const handleMessage = (event) => {
388
- var _a, _b, _c, _d;
389
- if (event.origin !== window.location.origin || ((_b = (_a = event.data) === null || _a === void 0 ? void 0 : _a.source) === null || _b === void 0 ? void 0 : _b.startsWith('angular')))
390
- return;
391
- if (((_c = event.data) === null || _c === void 0 ? void 0 : _c.type) === 'oauth-response') {
392
- cleanup(true);
393
- processOAuthResponse(event.data);
394
- }
395
- else if (((_d = event.data) === null || _d === void 0 ? void 0 : _d.type) === 'oauth-error') {
396
- cleanup(true);
397
- const errorMessage = event.data.error || 'User cancelled the OAuth flow';
398
- reject(inferUserCancelledError(errorMessage));
399
- }
400
- // Don't reject for non-OAuth messages, just ignore them
401
- };
402
- // Listen for BroadcastChannel messages
403
- if (broadcastChannel) {
404
- broadcastChannel.onmessage = (event) => {
405
- var _a;
406
- const data = event.data;
407
- if ((_a = data === null || data === void 0 ? void 0 : data.source) === null || _a === void 0 ? void 0 : _a.toString().startsWith('angular'))
408
- return;
409
- if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
410
- cleanup(true);
411
- processOAuthResponse(data);
412
- }
413
- else if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
414
- cleanup(true);
415
- const errorMessage = data.error || 'User cancelled the OAuth flow';
396
+ // COOP-safe listener: postMessage + BroadcastChannel + localStorage storage events
397
+ removeOAuthListener = listenForOAuthResult('google', nonce, {
398
+ onResponse: processOAuthResponse,
399
+ onError: (errorMessage) => {
400
+ settle(true, () => {
416
401
  reject(inferUserCancelledError(errorMessage));
417
- }
418
- };
419
- }
420
- window.addEventListener('message', handleMessage);
402
+ });
403
+ },
404
+ });
421
405
  // Timeout after 5 minutes
422
406
  timeoutHandle = setTimeout(() => {
423
- cleanup(true);
424
- reject(new Error('OAuth timeout'));
407
+ settle(true, () => {
408
+ reject(new Error('OAuth timeout'));
409
+ });
425
410
  }, 300000);
426
411
  popupClosedInterval = setInterval(() => {
412
+ if (coopErrorDetected)
413
+ return;
427
414
  try {
428
- // Check if popup is closed - this may throw cross-origin errors for some providers
429
415
  if (popup.closed) {
430
- cleanup();
431
- reject(createUserCancelledError('Popup closed'));
416
+ settle(false, () => {
417
+ reject(createUserCancelledError('Popup closed'));
418
+ });
432
419
  }
433
420
  }
434
421
  catch (_a) {
435
- // Cross-origin error when checking popup.closed - this happens when the popup
436
- // navigates to a third-party OAuth provider with strict security settings.
437
- // We can't detect if the window was closed, so we rely on timeout and message handlers.
438
- clearInterval(popupClosedInterval);
422
+ // COOP blocks popup.closed while on third-party origin — stop polling, rely on bridge
423
+ coopErrorDetected = true;
439
424
  }
440
425
  }, 1000);
441
426
  });
@@ -1 +1 @@
1
- {"version":3,"file":"google-provider.js","sourceRoot":"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gB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;YAElD,0BAA0B;YAC1B,aAAa,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC9B,OAAO,CAAC,IAAI,CAAC,CAAC;gBACd,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;YACrC,CAAC,EAAE,MAAM,CAAC,CAAC;YAEX,mBAAmB,GAAG,WAAW,CAAC,GAAG,EAAE;gBACrC,IAAI,CAAC;oBACH,mFAAmF;oBACnF,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;wBACjB,OAAO,EAAE,CAAC;wBACV,MAAM,CAAC,wBAAwB,CAAC,cAAc,CAAC,CAAC,CAAC;oBACnD,CAAC;gBACH,CAAC;gBAAC,WAAM,CAAC;oBACP,8EAA8E;oBAC9E,2EAA2E;oBAC3E,wFAAwF;oBACxF,aAAa,CAAC,mBAAmB,CAAC,CAAC;gBACrC,CAAC;YACH,CAAC,EAAE,IAAI,CAAC,CAAC;QACX,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseSocialLogin } from './base';\nimport type { AuthorizationCode, GoogleLoginOptions, LoginResult, ProviderResponseMap } from './definitions';\nimport { createUserCancelledError, inferUserCancelledError } from './errors';\n\nconst GOOGLE_OFFLINE_REFRESH_MESSAGE =\n \"Google refresh() is not available when using offline mode. Offline mode only returns serverAuthCode for backend token exchange. Send serverAuthCode to your backend and refresh tokens there, or switch google.mode to 'online' for client-side refresh.\";\n\nexport class GoogleSocialLogin extends BaseSocialLogin {\n private clientId: string | null = null;\n private hostedDomain?: string;\n private loginType: 'online' | 'offline' = 'online';\n private redirectUrl?: string;\n private GOOGLE_TOKEN_REQUEST_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';\n private readonly GOOGLE_STATE_KEY = 'capgo_social_login_google_state';\n\n async initialize(\n clientId: string | null,\n mode?: 'online' | 'offline',\n hostedDomain?: string | null,\n redirectUrl?: string,\n ): Promise<void> {\n this.clientId = clientId;\n if (mode) {\n this.loginType = mode;\n }\n this.hostedDomain = hostedDomain as string | undefined;\n this.redirectUrl = redirectUrl;\n }\n\n async login<T extends 'google'>(\n options: GoogleLoginOptions,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }> {\n if (!this.clientId) {\n throw new Error('Google Client ID not set. Call initialize() first.');\n }\n\n let scopes = options.scopes || [];\n\n if (scopes.length > 0) {\n // If scopes are provided, directly use the traditional OAuth flow\n if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {\n scopes.push('https://www.googleapis.com/auth/userinfo.email');\n }\n if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {\n scopes.push('https://www.googleapis.com/auth/userinfo.profile');\n }\n if (!scopes.includes('openid')) {\n scopes.push('openid');\n }\n } else {\n scopes = [\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'openid',\n ];\n }\n\n const nonce = options.nonce || Math.random().toString(36).substring(2);\n\n // If scopes are provided, directly use the traditional OAuth flow\n return this.traditionalOAuth({\n scopes,\n nonce,\n hostedDomain: this.hostedDomain,\n prompt: options.prompt,\n });\n }\n\n async logout(): Promise<void> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. logout is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) return;\n await this.rawLogoutGoogle(state.accessToken);\n }\n\n async isLoggedIn(): Promise<{ isLoggedIn: boolean }> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. isLoggedIn is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) return { isLoggedIn: false };\n\n try {\n const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);\n const isValidIdToken = this.idTokenValid(state.idToken);\n if (isValidAccessToken && isValidIdToken) {\n return { isLoggedIn: true };\n } else {\n try {\n await this.rawLogoutGoogle(state.accessToken, false);\n } catch (e) {\n console.error('Access token is not valid, but cannot logout', e);\n }\n return { isLoggedIn: false };\n }\n } catch (e) {\n return Promise.reject(e);\n }\n }\n\n async getAuthorizationCode(): Promise<AuthorizationCode> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. getAuthorizationCode is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) throw new Error('No Google authorization code available');\n\n try {\n const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);\n const isValidIdToken = this.idTokenValid(state.idToken);\n if (isValidAccessToken && isValidIdToken) {\n return { accessToken: state.accessToken, jwt: state.idToken };\n } else {\n try {\n await this.rawLogoutGoogle(state.accessToken, false);\n } catch (e) {\n console.error('Access token is not valid, but cannot logout', e);\n }\n throw new Error('No Google authorization code available');\n }\n } catch (e) {\n return Promise.reject(e);\n }\n }\n\n async refresh(): Promise<void> {\n if (this.loginType === 'offline') {\n console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);\n return Promise.reject(new Error(GOOGLE_OFFLINE_REFRESH_MESSAGE));\n }\n return Promise.reject(\n new Error('Google refresh is not implemented on web. Use login() again to obtain a new token.'),\n );\n }\n\n handleOAuthRedirect(url: URL): LoginResult | { error: string } | null {\n const paramsRaw = url.searchParams;\n\n // Check for errors in search params first (for offline mode)\n const errorInParams = paramsRaw.get('error');\n if (errorInParams) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const errorDescription = paramsRaw.get('error_description') || errorInParams;\n return { error: errorDescription };\n }\n\n const code = paramsRaw.get('code');\n\n if (code && paramsRaw.has('scope')) {\n return {\n provider: 'google',\n result: {\n serverAuthCode: code,\n responseType: 'offline',\n },\n };\n }\n\n const hash = url.hash.substring(1);\n console.log('handleOAuthRedirect', url.hash);\n\n if (!hash) return null;\n\n const params = new URLSearchParams(hash);\n\n // Check for error cases in hash (e.g., user cancelled)\n const error = params.get('error');\n if (error) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const errorDescription = params.get('error_description') || error;\n return { error: errorDescription };\n }\n\n console.log('handleOAuthRedirect ok');\n\n const accessToken = params.get('access_token');\n const idToken = params.get('id_token');\n\n if (accessToken && idToken) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const profile = this.parseJwt(idToken);\n return {\n provider: 'google',\n result: {\n accessToken: {\n token: accessToken,\n },\n idToken,\n profile: {\n email: profile.email || null,\n familyName: profile.family_name || null,\n givenName: profile.given_name || null,\n id: profile.sub || null,\n name: profile.name || null,\n imageUrl: profile.picture || null,\n },\n responseType: 'online',\n },\n };\n }\n return null;\n }\n\n private async accessTokenIsValid(accessToken: string): Promise<boolean> {\n const url = `${this.GOOGLE_TOKEN_REQUEST_URL}?access_token=${encodeURIComponent(accessToken)}`;\n\n try {\n // Make the GET request using fetch\n const response = await fetch(url);\n\n // Check if the response is successful\n if (!response.ok) {\n console.log(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response not successful. Status code: ${response.status}. Assuming that the token is not valid`,\n );\n return false;\n }\n\n // Get the response body as text\n const responseBody = await response.text();\n\n if (!responseBody) {\n console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);\n throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);\n }\n\n // Parse the response body as JSON\n let jsonObject: any;\n try {\n jsonObject = JSON.parse(responseBody);\n } catch (e) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`,\n );\n }\n\n // Extract the 'expires_in' field\n const expiresInStr = jsonObject['expires_in'];\n\n if (expiresInStr === undefined || expiresInStr === null) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`,\n );\n }\n\n // Parse 'expires_in' as an integer\n let expiresInInt: number;\n try {\n expiresInInt = parseInt(expiresInStr, 10);\n if (isNaN(expiresInInt)) {\n throw new Error(`'expires_in' is not a valid integer`);\n }\n } catch (e) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`,\n );\n }\n\n // Determine if the access token is valid based on 'expires_in'\n return expiresInInt > 5;\n } catch (error) {\n console.error(error);\n throw error;\n }\n }\n\n private idTokenValid(idToken: string): boolean {\n try {\n const parsed = this.parseJwt(idToken);\n const currentTime = Math.ceil(Date.now() / 1000) + 5; // Convert current time to seconds since epoch\n return parsed.exp && currentTime < parsed.exp;\n } catch (e) {\n return false;\n }\n }\n\n private async rawLogoutGoogle(accessToken: string, tokenValid: boolean | null = null) {\n if (tokenValid === null) {\n tokenValid = await this.accessTokenIsValid(accessToken);\n }\n\n if (tokenValid === true) {\n try {\n await fetch(`https://accounts.google.com/o/oauth2/revoke?token=${encodeURIComponent(accessToken)}`);\n this.clearStateGoogle();\n } catch (e) {\n // ignore\n }\n return;\n } else {\n this.clearStateGoogle();\n return;\n }\n }\n\n private persistStateGoogle(accessToken: string, idToken: string) {\n try {\n window.localStorage.setItem(this.GOOGLE_STATE_KEY, JSON.stringify({ accessToken, idToken }));\n } catch (e) {\n console.error('Cannot persist state google', e);\n }\n }\n\n private clearStateGoogle() {\n try {\n window.localStorage.removeItem(this.GOOGLE_STATE_KEY);\n } catch (e) {\n console.error('Cannot clear state google', e);\n }\n }\n\n private getGoogleState(): { accessToken: string; idToken: string } | null {\n try {\n const state = window.localStorage.getItem(this.GOOGLE_STATE_KEY);\n if (!state) return null;\n const { accessToken, idToken } = JSON.parse(state);\n return { accessToken, idToken };\n } catch (e) {\n console.error('Cannot get state google', e);\n return null;\n }\n }\n\n private async traditionalOAuth<T extends 'google'>({\n scopes,\n hostedDomain,\n nonce,\n prompt,\n }: GoogleLoginOptions & { hostedDomain?: string }): Promise<{ provider: T; result: ProviderResponseMap[T] }> {\n const uniqueScopes = [...new Set([...(scopes || []), 'openid'])];\n\n const params = new URLSearchParams({\n client_id: this.clientId ?? '',\n redirect_uri: this.redirectUrl || window.location.origin + window.location.pathname,\n response_type: this.loginType === 'offline' ? 'code' : 'token id_token',\n scope: uniqueScopes.join(' '),\n ...(nonce && { nonce }),\n include_granted_scopes: 'true',\n state: 'popup',\n });\n if (hostedDomain !== undefined) {\n params.append('hd', hostedDomain);\n }\n if (prompt !== undefined) {\n params.append('prompt', prompt);\n }\n\n const url = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;\n const width = 500;\n const height = 600;\n const left = window.screenX + (window.outerWidth - width) / 2;\n const top = window.screenY + (window.outerHeight - height) / 2;\n localStorage.setItem(\n BaseSocialLogin.OAUTH_STATE_KEY,\n JSON.stringify({ provider: 'google', loginType: this.loginType, nonce }),\n );\n const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);\n\n let popupClosedInterval: number;\n let timeoutHandle: number;\n\n // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)\n const channelName = `google_oauth_${nonce || Date.now()}`;\n let broadcastChannel: BroadcastChannel | null = null;\n\n try {\n broadcastChannel = new BroadcastChannel(channelName);\n } catch {\n // BroadcastChannel not supported, fall back to postMessage only\n }\n\n // This may never return...\n return new Promise((resolve, reject) => {\n if (!popup) {\n reject(new Error('Failed to open popup'));\n return;\n }\n\n const cleanup = (shouldClose = false) => {\n window.removeEventListener('message', handleMessage);\n clearInterval(popupClosedInterval);\n clearTimeout(timeoutHandle);\n if (broadcastChannel) {\n broadcastChannel.close();\n }\n if (shouldClose) {\n try {\n popup.close();\n } catch {\n // Ignore cross-origin errors when closing the popup\n }\n }\n };\n\n const processOAuthResponse = (data: Record<string, unknown>) => {\n if (this.loginType === 'online') {\n const { accessToken, idToken } = data as { accessToken?: { token: string }; idToken?: string };\n if (accessToken && idToken) {\n const profile = this.parseJwt(idToken);\n this.persistStateGoogle(accessToken.token, idToken);\n resolve({\n provider: 'google' as T,\n result: {\n accessToken: {\n token: accessToken.token,\n },\n idToken,\n profile: {\n email: profile.email || null,\n familyName: profile.family_name || null,\n givenName: profile.given_name || null,\n id: profile.sub || null,\n name: profile.name || null,\n imageUrl: profile.picture || null,\n },\n responseType: 'online',\n },\n });\n } else {\n reject(new Error('Invalid OAuth response: missing accessToken or idToken'));\n }\n } else {\n const { serverAuthCode } = data as { serverAuthCode: string };\n if (!serverAuthCode) {\n reject(new Error('Invalid OAuth response: missing serverAuthCode'));\n return;\n }\n resolve({\n provider: 'google' as T,\n result: {\n responseType: 'offline',\n serverAuthCode,\n },\n });\n }\n };\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== window.location.origin || event.data?.source?.startsWith('angular')) return;\n\n if (event.data?.type === 'oauth-response') {\n cleanup(true);\n processOAuthResponse(event.data);\n } else if (event.data?.type === 'oauth-error') {\n cleanup(true);\n const errorMessage = event.data.error || 'User cancelled the OAuth flow';\n reject(inferUserCancelledError(errorMessage));\n }\n // Don't reject for non-OAuth messages, just ignore them\n };\n\n // Listen for BroadcastChannel messages\n if (broadcastChannel) {\n broadcastChannel.onmessage = (event: MessageEvent) => {\n const data = event.data;\n if (data?.source?.toString().startsWith('angular')) return;\n\n if (data?.type === 'oauth-response') {\n cleanup(true);\n processOAuthResponse(data);\n } else if (data?.type === 'oauth-error') {\n cleanup(true);\n const errorMessage = (data.error as string) || 'User cancelled the OAuth flow';\n reject(inferUserCancelledError(errorMessage));\n }\n };\n }\n\n window.addEventListener('message', handleMessage);\n\n // Timeout after 5 minutes\n timeoutHandle = setTimeout(() => {\n cleanup(true);\n reject(new Error('OAuth timeout'));\n }, 300000);\n\n popupClosedInterval = setInterval(() => {\n try {\n // Check if popup is closed - this may throw cross-origin errors for some providers\n if (popup.closed) {\n cleanup();\n reject(createUserCancelledError('Popup closed'));\n }\n } catch {\n // Cross-origin error when checking popup.closed - this happens when the popup\n // navigates to a third-party OAuth provider with strict security settings.\n // We can't detect if the window was closed, so we rely on timeout and message handlers.\n clearInterval(popupClosedInterval);\n }\n }, 1000);\n });\n }\n}\n"]}
1
+ {"version":3,"file":"google-provider.js","sourceRoot":"","sources":["../../src/google-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE5E,MAAM,8BAA8B,GAClC,0PAA0P,CAAC;AAE7P,MAAM,OAAO,iBAAkB,SAAQ,eAAe;IAAtD;;QACU,aAAQ,GAAkB,IAAI,CAAC;QAE/B,cAAS,GAAyB,QAAQ,CAAC;QAE3C,6BAAwB,GAAG,gDAAgD,CAAC;QACnE,qBAAgB,GAAG,iCAAiC,CAAC;IAiexE,CAAC;IA/dC,KAAK,CAAC,UAAU,CACd,QAAuB,EACvB,IAA2B,EAC3B,YAA4B,EAC5B,WAAoB;QAEpB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,YAAY,GAAG,YAAkC,CAAC;QACvD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,KAAK,CACT,OAA2B;QAE3B,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;QACxE,CAAC;QAED,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAA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C,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseSocialLogin } from './base';\nimport type { AuthorizationCode, GoogleLoginOptions, LoginResult, ProviderResponseMap } from './definitions';\nimport { createUserCancelledError, inferUserCancelledError } from './errors';\nimport { listenForOAuthResult, markOAuthPopup } from './oauth-popup-bridge';\n\nconst GOOGLE_OFFLINE_REFRESH_MESSAGE =\n \"Google refresh() is not available when using offline mode. Offline mode only returns serverAuthCode for backend token exchange. Send serverAuthCode to your backend and refresh tokens there, or switch google.mode to 'online' for client-side refresh.\";\n\nexport class GoogleSocialLogin extends BaseSocialLogin {\n private clientId: string | null = null;\n private hostedDomain?: string;\n private loginType: 'online' | 'offline' = 'online';\n private redirectUrl?: string;\n private GOOGLE_TOKEN_REQUEST_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';\n private readonly GOOGLE_STATE_KEY = 'capgo_social_login_google_state';\n\n async initialize(\n clientId: string | null,\n mode?: 'online' | 'offline',\n hostedDomain?: string | null,\n redirectUrl?: string,\n ): Promise<void> {\n this.clientId = clientId;\n if (mode) {\n this.loginType = mode;\n }\n this.hostedDomain = hostedDomain as string | undefined;\n this.redirectUrl = redirectUrl;\n }\n\n async login<T extends 'google'>(\n options: GoogleLoginOptions,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }> {\n if (!this.clientId) {\n throw new Error('Google Client ID not set. Call initialize() first.');\n }\n\n let scopes = options.scopes || [];\n\n if (scopes.length > 0) {\n // If scopes are provided, directly use the traditional OAuth flow\n if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {\n scopes.push('https://www.googleapis.com/auth/userinfo.email');\n }\n if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {\n scopes.push('https://www.googleapis.com/auth/userinfo.profile');\n }\n if (!scopes.includes('openid')) {\n scopes.push('openid');\n }\n } else {\n scopes = [\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'openid',\n ];\n }\n\n const nonce = options.nonce || Math.random().toString(36).substring(2);\n\n // If scopes are provided, directly use the traditional OAuth flow\n return this.traditionalOAuth({\n scopes,\n nonce,\n hostedDomain: this.hostedDomain,\n prompt: options.prompt,\n });\n }\n\n async logout(): Promise<void> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. logout is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) return;\n await this.rawLogoutGoogle(state.accessToken);\n }\n\n async isLoggedIn(): Promise<{ isLoggedIn: boolean }> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. isLoggedIn is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) return { isLoggedIn: false };\n\n try {\n const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);\n const isValidIdToken = this.idTokenValid(state.idToken);\n if (isValidAccessToken && isValidIdToken) {\n return { isLoggedIn: true };\n } else {\n try {\n await this.rawLogoutGoogle(state.accessToken, false);\n } catch (e) {\n console.error('Access token is not valid, but cannot logout', e);\n }\n return { isLoggedIn: false };\n }\n } catch (e) {\n return Promise.reject(e);\n }\n }\n\n async getAuthorizationCode(): Promise<AuthorizationCode> {\n if (this.loginType === 'offline') {\n return Promise.reject(\"Offline login doesn't store tokens. getAuthorizationCode is not available\");\n }\n // eslint-disable-next-line\n const state = this.getGoogleState();\n if (!state) throw new Error('No Google authorization code available');\n\n try {\n const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);\n const isValidIdToken = this.idTokenValid(state.idToken);\n if (isValidAccessToken && isValidIdToken) {\n return { accessToken: state.accessToken, jwt: state.idToken };\n } else {\n try {\n await this.rawLogoutGoogle(state.accessToken, false);\n } catch (e) {\n console.error('Access token is not valid, but cannot logout', e);\n }\n throw new Error('No Google authorization code available');\n }\n } catch (e) {\n return Promise.reject(e);\n }\n }\n\n async refresh(): Promise<void> {\n if (this.loginType === 'offline') {\n console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);\n return Promise.reject(new Error(GOOGLE_OFFLINE_REFRESH_MESSAGE));\n }\n return Promise.reject(\n new Error('Google refresh is not implemented on web. Use login() again to obtain a new token.'),\n );\n }\n\n handleOAuthRedirect(url: URL): LoginResult | { error: string } | null {\n const paramsRaw = url.searchParams;\n\n // Check for errors in search params first (for offline mode)\n const errorInParams = paramsRaw.get('error');\n if (errorInParams) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const errorDescription = paramsRaw.get('error_description') || errorInParams;\n return { error: errorDescription };\n }\n\n const code = paramsRaw.get('code');\n\n if (code && paramsRaw.has('scope')) {\n return {\n provider: 'google',\n result: {\n serverAuthCode: code,\n responseType: 'offline',\n },\n };\n }\n\n const hash = url.hash.substring(1);\n\n if (!hash) return null;\n\n const params = new URLSearchParams(hash);\n\n // Check for error cases in hash (e.g., user cancelled)\n const error = params.get('error');\n if (error) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const errorDescription = params.get('error_description') || error;\n return { error: errorDescription };\n }\n\n const accessToken = params.get('access_token');\n const idToken = params.get('id_token');\n\n if (accessToken && idToken) {\n localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);\n const profile = this.parseJwt(idToken);\n return {\n provider: 'google',\n result: {\n accessToken: {\n token: accessToken,\n },\n idToken,\n profile: {\n email: profile.email || null,\n familyName: profile.family_name || null,\n givenName: profile.given_name || null,\n id: profile.sub || null,\n name: profile.name || null,\n imageUrl: profile.picture || null,\n },\n responseType: 'online',\n },\n };\n }\n return null;\n }\n\n private async accessTokenIsValid(accessToken: string): Promise<boolean> {\n const url = `${this.GOOGLE_TOKEN_REQUEST_URL}?access_token=${encodeURIComponent(accessToken)}`;\n\n try {\n // Make the GET request using fetch\n const response = await fetch(url);\n\n // Check if the response is successful\n if (!response.ok) {\n console.log(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response not successful. Status code: ${response.status}. Assuming that the token is not valid`,\n );\n return false;\n }\n\n // Get the response body as text\n const responseBody = await response.text();\n\n if (!responseBody) {\n console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);\n throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);\n }\n\n // Parse the response body as JSON\n let jsonObject: any;\n try {\n jsonObject = JSON.parse(responseBody);\n } catch (e) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`,\n );\n }\n\n // Extract the 'expires_in' field\n const expiresInStr = jsonObject['expires_in'];\n\n if (expiresInStr === undefined || expiresInStr === null) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`,\n );\n }\n\n // Parse 'expires_in' as an integer\n let expiresInInt: number;\n try {\n expiresInInt = parseInt(expiresInStr, 10);\n if (isNaN(expiresInInt)) {\n throw new Error(`'expires_in' is not a valid integer`);\n }\n } catch (e) {\n console.error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`,\n );\n throw new Error(\n `Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`,\n );\n }\n\n // Determine if the access token is valid based on 'expires_in'\n return expiresInInt > 5;\n } catch (error) {\n console.error(error);\n throw error;\n }\n }\n\n private idTokenValid(idToken: string): boolean {\n try {\n const parsed = this.parseJwt(idToken);\n const currentTime = Math.ceil(Date.now() / 1000) + 5; // Convert current time to seconds since epoch\n return parsed.exp && currentTime < parsed.exp;\n } catch (e) {\n return false;\n }\n }\n\n private async rawLogoutGoogle(accessToken: string, tokenValid: boolean | null = null) {\n if (tokenValid === null) {\n tokenValid = await this.accessTokenIsValid(accessToken);\n }\n\n if (tokenValid === true) {\n try {\n await fetch(`https://accounts.google.com/o/oauth2/revoke?token=${encodeURIComponent(accessToken)}`);\n this.clearStateGoogle();\n } catch (e) {\n // ignore\n }\n return;\n } else {\n this.clearStateGoogle();\n return;\n }\n }\n\n private persistStateGoogle(accessToken: string, idToken: string) {\n try {\n window.localStorage.setItem(this.GOOGLE_STATE_KEY, JSON.stringify({ accessToken, idToken }));\n } catch (e) {\n console.error('Cannot persist state google', e);\n }\n }\n\n private clearStateGoogle() {\n try {\n window.localStorage.removeItem(this.GOOGLE_STATE_KEY);\n } catch (e) {\n console.error('Cannot clear state google', e);\n }\n }\n\n private getGoogleState(): { accessToken: string; idToken: string } | null {\n try {\n const state = window.localStorage.getItem(this.GOOGLE_STATE_KEY);\n if (!state) return null;\n const { accessToken, idToken } = JSON.parse(state);\n return { accessToken, idToken };\n } catch (e) {\n console.error('Cannot get state google', e);\n return null;\n }\n }\n\n private async traditionalOAuth<T extends 'google'>({\n scopes,\n hostedDomain,\n nonce,\n prompt,\n }: GoogleLoginOptions & { hostedDomain?: string; nonce: string }): Promise<{\n provider: T;\n result: ProviderResponseMap[T];\n }> {\n const uniqueScopes = [...new Set([...(scopes || []), 'openid'])];\n\n const params = new URLSearchParams({\n client_id: this.clientId ?? '',\n redirect_uri: this.redirectUrl || window.location.origin + window.location.pathname,\n response_type: this.loginType === 'offline' ? 'code' : 'token id_token',\n scope: uniqueScopes.join(' '),\n ...(nonce && { nonce }),\n include_granted_scopes: 'true',\n state: 'popup',\n });\n if (hostedDomain !== undefined) {\n params.append('hd', hostedDomain);\n }\n if (prompt !== undefined) {\n params.append('prompt', prompt);\n }\n\n const url = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;\n const width = 500;\n const height = 600;\n const left = window.screenX + (window.outerWidth - width) / 2;\n const top = window.screenY + (window.outerHeight - height) / 2;\n localStorage.setItem(\n BaseSocialLogin.OAUTH_STATE_KEY,\n JSON.stringify({ provider: 'google', loginType: this.loginType, nonce }),\n );\n markOAuthPopup(nonce);\n const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);\n\n let popupClosedInterval: number;\n let timeoutHandle: number;\n let removeOAuthListener: (() => void) | null = null;\n\n // This may never return...\n return new Promise((resolve, reject) => {\n if (!popup) {\n reject(new Error('Failed to open popup'));\n return;\n }\n\n let settled = false;\n let coopErrorDetected = false;\n\n const cleanup = (shouldClose = false) => {\n clearInterval(popupClosedInterval);\n clearTimeout(timeoutHandle);\n if (removeOAuthListener) {\n removeOAuthListener();\n removeOAuthListener = null;\n }\n if (shouldClose) {\n try {\n popup.close();\n } catch {\n // Ignore cross-origin errors when closing the popup\n }\n }\n };\n\n const settle = (shouldClose: boolean, action: () => void) => {\n if (settled) return;\n settled = true;\n cleanup(shouldClose);\n action();\n };\n\n const processOAuthResponse = (data: Record<string, unknown>) => {\n if (this.loginType === 'online') {\n const { accessToken, idToken } = data as { accessToken?: { token: string }; idToken?: string };\n if (accessToken && idToken) {\n const profile = this.parseJwt(idToken);\n this.persistStateGoogle(accessToken.token, idToken);\n settle(true, () => {\n resolve({\n provider: 'google' as T,\n result: {\n accessToken: {\n token: accessToken.token,\n },\n idToken,\n profile: {\n email: profile.email || null,\n familyName: profile.family_name || null,\n givenName: profile.given_name || null,\n id: profile.sub || null,\n name: profile.name || null,\n imageUrl: profile.picture || null,\n },\n responseType: 'online',\n },\n });\n });\n } else {\n settle(true, () => {\n reject(new Error('Invalid OAuth response: missing accessToken or idToken'));\n });\n }\n } else {\n const { serverAuthCode } = data as { serverAuthCode: string };\n if (!serverAuthCode) {\n settle(true, () => {\n reject(new Error('Invalid OAuth response: missing serverAuthCode'));\n });\n return;\n }\n settle(true, () => {\n resolve({\n provider: 'google' as T,\n result: {\n responseType: 'offline',\n serverAuthCode,\n },\n });\n });\n }\n };\n\n // COOP-safe listener: postMessage + BroadcastChannel + localStorage storage events\n removeOAuthListener = listenForOAuthResult('google', nonce, {\n onResponse: processOAuthResponse,\n onError: (errorMessage) => {\n settle(true, () => {\n reject(inferUserCancelledError(errorMessage));\n });\n },\n });\n\n // Timeout after 5 minutes\n timeoutHandle = setTimeout(() => {\n settle(true, () => {\n reject(new Error('OAuth timeout'));\n });\n }, 300000);\n\n popupClosedInterval = setInterval(() => {\n if (coopErrorDetected) return;\n\n try {\n if (popup.closed) {\n settle(false, () => {\n reject(createUserCancelledError('Popup closed'));\n });\n }\n } catch {\n // COOP blocks popup.closed while on third-party origin — stop polling, rely on bridge\n coopErrorDetected = true;\n }\n }, 1000);\n });\n }\n}\n"]}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * COOP-safe OAuth popup communication bridge.
3
+ *
4
+ * When Cross-Origin-Opener-Policy severs window.opener, postMessage and popup.closed
5
+ * checks fail. This module uses localStorage + storage events and BroadcastChannel
6
+ * as reliable fallbacks that work across same-origin popup windows.
7
+ */
8
+ export declare const OAUTH_STATE_KEY = "social_login_oauth_pending";
9
+ export declare const OAUTH_POPUP_SESSION_KEY = "social_login_oauth_popup";
10
+ export declare const OAUTH_RESULT_KEY_PREFIX = "social_login_oauth_result_";
11
+ export declare const OAUTH_DELIVERED_KEY = "social_login_oauth_delivered";
12
+ export declare const POPUP_WINDOW_NAMES: Set<string>;
13
+ export type OAuthBridgeMessage = Record<string, unknown> & {
14
+ type: 'oauth-response' | 'oauth-error';
15
+ };
16
+ export declare function getOAuthResultKey(nonce: string): string;
17
+ export declare function getBroadcastChannelName(provider: string, nonceOrState: string): string;
18
+ export declare function markOAuthPopup(nonce: string): void;
19
+ export declare function clearOAuthPopupMarker(): void;
20
+ export declare function hasOAuthRedirectParams(): boolean;
21
+ export declare function isOAuthPopupContext(): boolean;
22
+ export declare function shouldAutoFinishOAuthRedirect(): boolean;
23
+ /**
24
+ * Deliver OAuth result from popup to opener via all available channels.
25
+ */
26
+ export declare function deliverOAuthResult(provider: string, nonceOrState: string | undefined, message: OAuthBridgeMessage): void;
27
+ export interface OAuthResultListener {
28
+ onResponse: (data: Record<string, unknown>) => void;
29
+ onError: (error: string, code?: string) => void;
30
+ }
31
+ /**
32
+ * Listen for OAuth results from popup via postMessage, BroadcastChannel, and localStorage.
33
+ * Returns a cleanup function.
34
+ */
35
+ export declare function listenForOAuthResult(provider: string, nonceOrState: string, handlers: OAuthResultListener): () => void;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * COOP-safe OAuth popup communication bridge.
3
+ *
4
+ * When Cross-Origin-Opener-Policy severs window.opener, postMessage and popup.closed
5
+ * checks fail. This module uses localStorage + storage events and BroadcastChannel
6
+ * as reliable fallbacks that work across same-origin popup windows.
7
+ */
8
+ export const OAUTH_STATE_KEY = 'social_login_oauth_pending';
9
+ export const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';
10
+ export const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';
11
+ export const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';
12
+ export const POPUP_WINDOW_NAMES = new Set(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);
13
+ export function getOAuthResultKey(nonce) {
14
+ return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;
15
+ }
16
+ export function getBroadcastChannelName(provider, nonceOrState) {
17
+ if (provider === 'oauth2')
18
+ return `oauth2_${nonceOrState}`;
19
+ if (provider === 'twitter')
20
+ return `twitter_oauth_${nonceOrState}`;
21
+ return `google_oauth_${nonceOrState}`;
22
+ }
23
+ export function markOAuthPopup(nonce) {
24
+ try {
25
+ sessionStorage.removeItem(OAUTH_DELIVERED_KEY);
26
+ sessionStorage.setItem(OAUTH_POPUP_SESSION_KEY, nonce);
27
+ }
28
+ catch (_a) {
29
+ // sessionStorage may be unavailable in some contexts
30
+ }
31
+ }
32
+ export function clearOAuthPopupMarker() {
33
+ try {
34
+ sessionStorage.removeItem(OAUTH_POPUP_SESSION_KEY);
35
+ }
36
+ catch (_a) {
37
+ // ignore
38
+ }
39
+ }
40
+ export function hasOAuthRedirectParams() {
41
+ const { search, hash } = window.location;
42
+ return (search.includes('code=') ||
43
+ search.includes('error=') ||
44
+ hash.includes('access_token=') ||
45
+ hash.includes('id_token=') ||
46
+ hash.includes('error='));
47
+ }
48
+ export function isOAuthPopupContext() {
49
+ if (typeof window === 'undefined')
50
+ return false;
51
+ return !!window.opener || POPUP_WINDOW_NAMES.has(window.name) || !!sessionStorage.getItem(OAUTH_POPUP_SESSION_KEY);
52
+ }
53
+ export function shouldAutoFinishOAuthRedirect() {
54
+ if (!localStorage.getItem(OAUTH_STATE_KEY))
55
+ return false;
56
+ return isOAuthPopupContext() || hasOAuthRedirectParams();
57
+ }
58
+ /**
59
+ * Deliver OAuth result from popup to opener via all available channels.
60
+ */
61
+ export function deliverOAuthResult(provider, nonceOrState, message) {
62
+ // Prevent duplicate delivery when both eager handler and plugin constructor run
63
+ try {
64
+ if (sessionStorage.getItem(OAUTH_DELIVERED_KEY))
65
+ return;
66
+ sessionStorage.setItem(OAUTH_DELIVERED_KEY, '1');
67
+ }
68
+ catch (_a) {
69
+ // sessionStorage unavailable
70
+ }
71
+ // postMessage when opener reference is still available
72
+ try {
73
+ if (window.opener) {
74
+ window.opener.postMessage(message, window.location.origin);
75
+ }
76
+ }
77
+ catch (_b) {
78
+ // COOP may block opener access
79
+ }
80
+ // BroadcastChannel works across same-origin windows without opener
81
+ if (nonceOrState) {
82
+ try {
83
+ const channel = new BroadcastChannel(getBroadcastChannelName(provider, nonceOrState));
84
+ channel.postMessage(message);
85
+ channel.close();
86
+ }
87
+ catch (_c) {
88
+ // BroadcastChannel not supported
89
+ }
90
+ }
91
+ // localStorage + storage event is the most COOP-resilient fallback
92
+ if (nonceOrState) {
93
+ try {
94
+ localStorage.setItem(getOAuthResultKey(nonceOrState), JSON.stringify(Object.assign(Object.assign({}, message), { _ts: Date.now() })));
95
+ }
96
+ catch (_d) {
97
+ // localStorage may be full or unavailable
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Listen for OAuth results from popup via postMessage, BroadcastChannel, and localStorage.
103
+ * Returns a cleanup function.
104
+ */
105
+ export function listenForOAuthResult(provider, nonceOrState, handlers) {
106
+ const resultKey = getOAuthResultKey(nonceOrState);
107
+ const channelName = getBroadcastChannelName(provider, nonceOrState);
108
+ let broadcastChannel = null;
109
+ try {
110
+ broadcastChannel = new BroadcastChannel(channelName);
111
+ }
112
+ catch (_a) {
113
+ // BroadcastChannel not supported
114
+ }
115
+ const processData = (data) => {
116
+ if ((data === null || data === void 0 ? void 0 : data.source) && String(data.source).startsWith('angular'))
117
+ return false;
118
+ if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
119
+ handlers.onResponse(data);
120
+ return true;
121
+ }
122
+ if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
123
+ handlers.onError(data.error || 'User cancelled the OAuth flow', data.code);
124
+ return true;
125
+ }
126
+ return false;
127
+ };
128
+ const handleMessage = (event) => {
129
+ if (event.origin !== window.location.origin)
130
+ return;
131
+ processData(event.data);
132
+ };
133
+ const handleStorage = (event) => {
134
+ if (event.key !== resultKey || !event.newValue)
135
+ return;
136
+ try {
137
+ const data = JSON.parse(event.newValue);
138
+ localStorage.removeItem(resultKey);
139
+ processData(data);
140
+ }
141
+ catch (_a) {
142
+ // ignore parse errors
143
+ }
144
+ };
145
+ const handleBroadcast = (event) => {
146
+ processData(event.data);
147
+ };
148
+ window.addEventListener('message', handleMessage);
149
+ window.addEventListener('storage', handleStorage);
150
+ if (broadcastChannel) {
151
+ broadcastChannel.onmessage = handleBroadcast;
152
+ }
153
+ // Poll localStorage as fallback when storage event is missed (e.g. same-window writes)
154
+ const pollInterval = window.setInterval(() => {
155
+ try {
156
+ const raw = localStorage.getItem(resultKey);
157
+ if (!raw)
158
+ return;
159
+ localStorage.removeItem(resultKey);
160
+ const data = JSON.parse(raw);
161
+ processData(data);
162
+ }
163
+ catch (_a) {
164
+ // ignore
165
+ }
166
+ }, 300);
167
+ return () => {
168
+ window.removeEventListener('message', handleMessage);
169
+ window.removeEventListener('storage', handleStorage);
170
+ clearInterval(pollInterval);
171
+ if (broadcastChannel) {
172
+ broadcastChannel.close();
173
+ }
174
+ try {
175
+ localStorage.removeItem(resultKey);
176
+ }
177
+ catch (_a) {
178
+ // ignore
179
+ }
180
+ };
181
+ }
182
+ //# sourceMappingURL=oauth-popup-bridge.js.map
@@ -0,0 +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;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,CAAC,aAAa,EAAE,QAAQ,EAAE,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC;AAMxG,MAAM,UAAU,iBAAiB,CAAC,KAAa;IAC7C,OAAO,GAAG,uBAAuB,GAAG,KAAK,EAAE,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,QAAgB,EAAE,YAAoB;IAC5E,IAAI,QAAQ,KAAK,QAAQ;QAAE,OAAO,UAAU,YAAY,EAAE,CAAC;IAC3D,IAAI,QAAQ,KAAK,SAAS;QAAE,OAAO,iBAAiB,YAAY,EAAE,CAAC;IACnE,OAAO,gBAAgB,YAAY,EAAE,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,IAAI,CAAC;QACH,cAAc,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC;QAC/C,cAAc,CAAC,OAAO,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC;IACzD,CAAC;I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**\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(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);\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 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, hash } = window.location;\n return (\n search.includes('code=') ||\n search.includes('error=') ||\n hash.includes('access_token=') ||\n hash.includes('id_token=') ||\n hash.includes('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"]}
@@ -0,0 +1 @@
1
+ export declare function initOAuthPopupRedirectHandler(): void;