@capgo/capacitor-social-login 8.5.1 → 8.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +78 -18
  2. package/android/src/main/java/ee/forgr/capacitor/social/login/OAuth2LoginActivity.java +7 -0
  3. package/android/src/main/java/ee/forgr/capacitor/social/login/SocialLoginPlugin.java +31 -1
  4. package/android/src/main/java/ee/forgr/capacitor/social/login/TelegramProvider.java +352 -0
  5. package/android/src/main/java/ee/forgr/capacitor/social/login/helpers/DependencyAvailabilityChecker.java +21 -1
  6. package/dist/docs.json +150 -8
  7. package/dist/esm/definitions.d.ts +87 -3
  8. package/dist/esm/definitions.js.map +1 -1
  9. package/dist/esm/facebook-provider.d.ts +3 -1
  10. package/dist/esm/facebook-provider.js +33 -0
  11. package/dist/esm/facebook-provider.js.map +1 -1
  12. package/dist/esm/oauth-popup-bridge.js +17 -7
  13. package/dist/esm/oauth-popup-bridge.js.map +1 -1
  14. package/dist/esm/oauth-popup-redirect.js +5 -0
  15. package/dist/esm/oauth-popup-redirect.js.map +1 -1
  16. package/dist/esm/social-login.d.ts +1 -1
  17. package/dist/esm/social-login.js.map +1 -1
  18. package/dist/esm/telegram-provider.d.ts +37 -0
  19. package/dist/esm/telegram-provider.js +292 -0
  20. package/dist/esm/telegram-provider.js.map +1 -0
  21. package/dist/esm/web.d.ts +2 -1
  22. package/dist/esm/web.js +23 -3
  23. package/dist/esm/web.js.map +1 -1
  24. package/dist/plugin.cjs.js +364 -10
  25. package/dist/plugin.cjs.js.map +1 -1
  26. package/dist/plugin.js +364 -10
  27. package/dist/plugin.js.map +1 -1
  28. package/ios/Sources/SocialLoginPlugin/SocialLoginPlugin.swift +67 -1
  29. package/ios/Sources/SocialLoginPlugin/TelegramProvider.swift +260 -0
  30. package/package.json +1 -1
@@ -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 * 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\n/**\n * Options for `providerSpecificCall` with `google#createRestoreCredential`.\n *\n * Android-only. Creates a Restore Credential (restore key) via Credential Manager after the user\n * signs in. Your backend must supply WebAuthn PublicKeyCredentialCreationOptionsJSON (the same\n * FIDO2/passkey registration flow used for passkeys).\n *\n * @see https://developer.android.com/identity/sign-in/restore-credentials\n * @since 8.5.0\n */\nexport interface GoogleCreateRestoreCredentialOptions {\n /**\n * Credential creation options from your server in WebAuthn PublicKeyCredentialCreationOptionsJSON format.\n */\n requestJson: string;\n /**\n * When `true` (default), the restore key is backed up to the cloud when the user has backup and\n * end-to-end encryption (e.g. screen lock) enabled. If cloud backup creation fails with\n * `E2eeUnavailableException` on Android, the plugin automatically retries with local-only storage.\n * @default true\n */\n isCloudBackupEnabled?: boolean;\n}\n\n/**\n * Response from `google#createRestoreCredential`.\n *\n * Send `responseJson` to your server to complete restore key registration (same as passkey creation).\n */\nexport interface GoogleCreateRestoreCredentialResponse {\n /** Public key credential registration response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/**\n * Options for `providerSpecificCall` with `google#getRestoreCredential`.\n *\n * Android-only. Retrieves a Restore Credential silently (e.g. on first launch on a new device or from\n * BackupAgent `onRestoreFinished`). Your backend must supply WebAuthn authentication request JSON.\n */\nexport interface GoogleGetRestoreCredentialOptions {\n /**\n * Credential request options from your server (WebAuthn authentication request JSON).\n */\n requestJson: string;\n}\n\n/**\n * Response from `google#getRestoreCredential`.\n *\n * Send `responseJson` to your server to sign the user in (same server path as passkey authentication).\n */\nexport interface GoogleGetRestoreCredentialResponse {\n /** Restore credential authentication response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/** Options for `google#clearRestoreCredential` (no fields). */\nexport type GoogleClearRestoreCredentialOptions = Record<string, never>;\n\n/** Response from `google#clearRestoreCredential`. */\nexport interface GoogleClearRestoreCredentialResponse {\n /** Whether the restore credential clear request completed successfully. */\n cleared: boolean;\n}\n\nexport type ProviderSpecificCall =\n | 'facebook#getProfile'\n | 'facebook#requestTracking'\n | 'google#createRestoreCredential'\n | 'google#getRestoreCredential'\n | 'google#clearRestoreCredential';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile\n * @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 'google#createRestoreCredential': GoogleCreateRestoreCredentialOptions;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialOptions;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialOptions;\n};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialResponse;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialResponse;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialResponse;\n};\n\n// Add a helper type to map providers to their response types\nexport type ProviderResponseMap = {\n facebook: FacebookLoginResponse;\n google: GoogleLoginResponse;\n apple: AppleProviderResponse;\n twitter: TwitterLoginResponse;\n oauth2: OAuth2LoginResponse;\n};\n\n/**\n * Error codes returned by the plugin.\n * @since 8.3.x\n */\nexport type SocialLoginErrorCode = 'USER_CANCELLED';\n\n/**\n * Errors thrown by SocialLogin methods.\n *\n * When a user dismisses or cancels the provider UI (popup closed, system dialog cancelled, access denied, etc.),\n * the plugin rejects with `code === 'USER_CANCELLED'` so the caller can distinguish user intent from real failures.\n * Other errors may omit the code or use provider-specific values.\n */\nexport interface SocialLoginError extends Error {\n code?: SocialLoginErrorCode | string;\n}\n\nexport interface SocialLoginPlugin {\n /**\n * Initialize the plugin\n * @description initialize the plugin with the required options\n */\n initialize(options: InitializeOptions): Promise<void>;\n /**\n * Login with the selected provider\n * @description login with the selected provider\n *\n * On user dismissal/cancellation, the Promise is rejected with `code === 'USER_CANCELLED'` (see `SocialLoginError`).\n */\n login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }>;\n /**\n * Logout\n * @description Logout the user from the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"logout is not implemented when using offline mode\"\n *\n * **Google Restore Credentials (Android):**\n * When logging out from Google, the plugin also clears any stored Restore Credential\n * (`google#clearRestoreCredential`) in addition to Credential Manager sign-in state.\n *\n * @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 /**\n * Telegram Login Widget configuration.\n * Uses Telegram's OAuth widget (`oauth.telegram.org`), not standard OAuth2.\n */\n telegram?: {\n /**\n * Telegram bot ID (numeric, not the bot token).\n * @example '123456789'\n */\n botId: string;\n /**\n * Default redirect URL that will receive Telegram auth data.\n * For mobile apps, prefer a custom scheme (e.g. `myapp://telegram-auth`).\n * On iOS/Android this must be set here or per login; native login rejects if it is missing.\n */\n redirectUrl?: string;\n /**\n * Origin/domain registered for the Telegram login widget.\n * Required when `redirectUrl` is not `http`/`https` (for example a custom scheme like `myapp://telegram-auth`).\n * Defaults to the origin of `redirectUrl` only when that URL is already http(s).\n * @example 'https://example.com'\n */\n origin?: string;\n /**\n * Requested access level.\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n /**\n * Optional language code passed to Telegram (e.g. 'en', 'fr').\n */\n languageCode?: string;\n };\n twitter?: {\n /**\n * The OAuth 2.0 client identifier issued by X (Twitter) Developer Portal\n * @example 'Y2xpZW50SWQ'\n */\n clientId: string;\n /**\n * Redirect URL that is registered inside the X Developer Portal.\n * The plugin uses this URL on every platform to receive the authorization code.\n * @example 'myapp://auth/x'\n */\n redirectUrl: string;\n /**\n * Default scopes appended to every login request when no custom scopes are provided.\n * @description Defaults to the minimum required scopes for Log in with X.\n * @default ['tweet.read','users.read']\n */\n defaultScopes?: string[];\n /**\n * Force the consent screen to show on every login attempt.\n * Mirrors X's `force_login=true` flag.\n * @default false\n */\n forceLogin?: boolean;\n /**\n * Optional audience value when your application has been approved for multi-tenant access.\n */\n audience?: string;\n };\n facebook?: {\n /**\n * Facebook App ID, provided by Facebook for web, in mobile it's set in the native files\n * @description For business integrations, use your Business App ID from Facebook Developer Console.\n * Business apps can access additional permissions like Instagram API, Pages API, and business management features.\n * @see docs/facebook_business_login.md for business app setup guide\n */\n appId: string;\n /**\n * Facebook Client Token, provided by Facebook for web, in mobile it's set in the native files\n */\n clientToken?: string;\n /**\n * Locale\n * @description The locale to use for the Facebook SDK (e.g., 'en_US', 'fr_FR', 'es_ES')\n * @default 'en_US'\n * @example 'fr_FR'\n */\n locale?: string;\n };\n\n google?: {\n /**\n * The app's client ID, found and created in the Google Developers Console.\n * Required for iOS platform.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSClientId?: string;\n /**\n * The app's server client ID, required for offline mode on iOS.\n * Should be the same value as webClientId.\n * Found and created in the Google Developers Console.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n iOSServerClientId?: string;\n /**\n * The app's web client ID, found and created in the Google Developers Console.\n * Required for Android and Web platforms.\n * @example xxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\n * @since 3.1.0\n */\n webClientId?: string;\n /**\n * The login mode, can be online or offline.\n *\n * **Online mode (default):**\n * - Returns user profile data and access tokens\n * - Supports all methods: login, logout, isLoggedIn, getAuthorizationCode\n *\n * **Offline mode:**\n * - Returns only serverAuthCode for backend authentication\n * - No user profile data available\n * - **Limitations:** The following methods are NOT supported in offline mode:\n * - `logout()` - Will reject with \"not implemented when using offline mode\"\n * - `isLoggedIn()` - Will reject with \"not implemented when using offline mode\"\n * - `getAuthorizationCode()` - Will reject with \"not implemented when using offline mode\"\n * - `refresh()` - Will reject because offline mode only returns `serverAuthCode`; token refresh must happen on your backend\n * - Only `login()` method works in offline mode, returning serverAuthCode only\n * - `serverAuthCode` must be exchanged on your backend for access/refresh tokens\n * - Requires `iOSServerClientId` to be set on iOS\n *\n * @example 'offline'\n * @default 'online'\n * @since 3.1.0\n */\n mode?: 'online' | 'offline';\n /**\n * Filter visible accounts by hosted domain\n * @description filter visible accounts by hosted domain\n */\n hostedDomain?: string;\n /**\n * Google Redirect URL, should be your backend url that is configured in your google app\n */\n redirectUrl?: string;\n };\n apple?: {\n /**\n * Apple Client ID, provided by Apple for web and Android\n */\n clientId?: string;\n /**\n * Apple Redirect URL, should be your backend url that is configured in your apple app\n *\n * **Note**: Use empty string `''` for iOS to prevent redirect.\n * **Note**: Not required when using Broadcast Channel mode on Android.\n */\n redirectUrl?: string;\n /**\n * Use proper token exchange for Apple Sign-In\n * @description Controls how Apple Sign-In tokens are handled and what gets returned:\n *\n * **When `true` (Recommended for new implementations):**\n * - Exchanges authorization code for proper access tokens via Apple's token endpoint\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: Proper access token from Apple (short-lived, ~1 hour)\n * - `authorizationCode`: Raw authorization code for backend token exchange\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses authorization code directly as access token for backward compatibility\n * - `idToken`: JWT containing user identity information (email, name, user ID)\n * - `accessToken.token`: The authorization code itself (not a real access token)\n * - `authorizationCode`: undefined\n *\n * @default false\n * @example\n * // Enable proper token exchange (recommended)\n * useProperTokenExchange: true\n * // Result: idToken=JWT, accessToken=real_token, authorizationCode=present\n *\n * // Legacy mode (backward compatibility)\n * useProperTokenExchange: false\n * // Result: idToken=JWT, accessToken=auth_code, authorizationCode=undefined\n */\n useProperTokenExchange?: boolean;\n /**\n * Use Broadcast Channel for Android Apple Sign-In (Recommended)\n * @description When enabled, Android uses Broadcast Channel API instead of URL redirects.\n * This eliminates the need for redirect URL configuration and server-side setup.\n *\n * **Benefits:**\n * - No redirect URL configuration required\n * - No backend server needed for Android\n * - Simpler setup and more reliable communication\n * - Direct client-server communication via Broadcast Channel\n *\n * **When `true`:**\n * - Uses Broadcast Channel for authentication flow\n * - `redirectUrl` is ignored\n * - Requires Broadcast Channel compatible backend or direct token handling\n *\n * **When `false` (Default - Legacy mode):**\n * - Uses traditional URL redirect flow\n * - Requires `redirectUrl` configuration\n * - Requires backend server for token exchange\n *\n * @default false\n * @since 7.10.0\n * @example\n * // Enable Broadcast Channel mode (recommended for new Android implementations)\n * useBroadcastChannel: true\n * // Result: Simplified setup, no redirect URL needed\n *\n * // Legacy mode (backward compatibility)\n * useBroadcastChannel: false\n * // Result: Traditional URL redirect flow with server-side setup\n */\n useBroadcastChannel?: boolean;\n };\n}\n\nexport interface FacebookLoginOptions {\n /**\n * Permissions\n * @description Select permissions to login with. Supports both consumer and business permissions.\n *\n * **Consumer Permissions:**\n * - `email` - User's email address\n * - `public_profile` - User's public profile info\n * - `user_friends` - List of friends who also use your app\n *\n * **Business Permissions** (require business app configuration and may need App Review):\n * - `instagram_basic` - Instagram Basic Display API access\n * - `instagram_manage_insights` - Instagram Insights data\n * - `instagram_manage_comments` - Manage Instagram comments\n * - `instagram_content_publish` - Publish to Instagram\n * - `pages_show_list` - List of Pages managed by user\n * - `pages_read_engagement` - Read Page engagement metrics\n * - `pages_manage_posts` - Manage Page posts\n * - `pages_messaging` - Page messaging features\n * - `business_management` - Manage business assets\n * - `catalog_management` - Manage product catalogs\n * - `ads_management` - Manage advertising accounts\n *\n * @example ['email', 'public_profile'] // Consumer permissions\n * @example ['email', 'instagram_basic', 'pages_show_list'] // Business permissions\n * @see https://developers.facebook.com/docs/permissions/reference\n * @see docs/facebook_business_login.md for complete business integration guide\n */\n permissions: string[];\n /**\n * Is Limited Login\n * @description use limited login for Facebook iOS only. Important: This is iOS-only and doesn't affect Android.\n * Even if set to false, Facebook will automatically force it to true if App Tracking Transparency (ATT) permission is not granted.\n * Developers should always be prepared to handle both limited and full login scenarios.\n * @default false\n */\n limitedLogin?: boolean;\n /**\n * Nonce\n * @description A custom nonce to use for the login request\n */\n nonce?: string;\n}\n\nexport interface TwitterLoginOptions {\n /**\n * Additional scopes to request during login.\n * If omitted the plugin falls back to the default scopes configured during initialization.\n * @example ['tweet.read','users.read','offline.access']\n */\n scopes?: string[];\n /**\n * Provide a custom OAuth state value.\n * When not provided the plugin generates a cryptographically random value.\n */\n state?: string;\n /**\n * Provide a pre-computed PKCE code verifier (mostly used for testing).\n * When omitted the plugin generates a secure verifier automatically.\n */\n codeVerifier?: string;\n /**\n * Override the redirect URI for a single login call.\n * Useful when the same app supports multiple callback URLs per platform.\n */\n redirectUrl?: string;\n /**\n * Force the consent screen on every attempt, maps to `force_login=true`.\n */\n forceLogin?: boolean;\n}\n\nexport interface TelegramLoginOptions {\n /**\n * Override the redirect URL for this login attempt.\n * Defaults to the redirect configured during initialize().\n * Required on iOS/Android when initialize() did not set `redirectUrl`.\n */\n redirectUrl?: string;\n /**\n * Optional state parameter for CSRF protection.\n * If omitted, a secure random value is generated automatically.\n */\n state?: string;\n /**\n * Override requested access level for this login.\n * Defaults to the value configured during initialize().\n * @default 'write'\n */\n requestAccess?: 'read' | 'write';\n}\n\nexport interface OAuth2LoginOptions {\n /**\n * The provider ID as configured in initialize()\n * This is required to identify which OAuth2 provider to use\n * @example 'github', 'azure', 'keycloak'\n */\n providerId: string;\n /**\n * Override the scopes for this login request\n * If not provided, uses the scopes from initialization\n */\n scope?: string | string[];\n /**\n * Alias for `scope` using common naming (`scopes`).\n * If both are provided, `scope` takes precedence.\n */\n scopes?: string[];\n /**\n * Custom state parameter for CSRF protection\n * If not provided, a random value is generated\n */\n state?: string;\n /**\n * Override PKCE code verifier (for testing purposes)\n * If not provided, a secure random verifier is generated\n */\n codeVerifier?: string;\n /**\n * Override redirect URL for this login request\n */\n redirectUrl?: string;\n /**\n * Additional parameters to add to the authorization URL\n */\n additionalParameters?: Record<string, string>;\n /**\n * Convenience option for OIDC `login_hint`.\n * Equivalent to passing `additionalParameters.login_hint`.\n */\n loginHint?: string;\n /**\n * Convenience option for OAuth/OIDC `prompt`.\n * Equivalent to passing `additionalParameters.prompt`.\n */\n prompt?: string;\n /**\n * Web-only (`oauth2` provider only): Use a full-page redirect instead of a popup window.\n *\n * When using `redirect`, the promise returned by `login()` will not resolve because the page navigates away.\n * After the redirect lands back in your app, call `SocialLogin.handleRedirectCallback()` on that page to\n * parse the result.\n *\n * @default 'popup'\n */\n flow?: 'popup' | 'redirect';\n}\n\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: 'telegram';\n options: TelegramLoginOptions;\n }\n | {\n provider: 'oauth2';\n options: OAuth2LoginOptions;\n };\n\nexport type LoginResult =\n | {\n provider: 'facebook';\n result: FacebookLoginResponse;\n }\n | {\n provider: 'google';\n result: GoogleLoginResponse;\n }\n | {\n provider: 'apple';\n result: AppleProviderResponse;\n }\n | {\n provider: 'twitter';\n result: TwitterLoginResponse;\n }\n | {\n provider: 'telegram';\n result: TelegramLoginResponse;\n }\n | {\n provider: 'oauth2';\n result: OAuth2LoginResponse;\n };\n\nexport interface AccessToken {\n applicationId?: string;\n declinedPermissions?: string[];\n expires?: string;\n isExpired?: boolean;\n lastRefresh?: string;\n permissions?: string[];\n token: string;\n tokenType?: string;\n refreshToken?: string;\n userId?: string;\n}\n\nexport interface FacebookLoginResponse {\n accessToken: AccessToken | null;\n /**\n * Whether Facebook Limited Login was used for this session.\n * When `true`, `accessToken` is not valid for Graph API calls (Facebook error 190).\n * Validate `idToken` on your backend instead, or call `facebook#requestTracking` and log in again after ATT is granted.\n * @since 8.4.0\n */\n isLimitedLogin?: boolean;\n /**\n * OpenID Connect ID token (JWT) from Meta Limited Login (iOS native, when available).\n *\n * **Not equivalent to Google/Apple `email_verified`:** Meta's OIDC token may include\n * an `email` claim (when the `email` permission is granted) but does **not** publish an\n * `email_verified` claim like Google or Apple. Meta documents the value as the user's\n * primary account email, not as an OIDC-verified email assertion.\n *\n * On Android and Web this is usually `null` (Graph API access token flow instead).\n * Validate signature, `iss` (`https://www.facebook.com` or `https://limited.facebook.com`),\n * `aud`, `exp`, and nonce on your backend. Do not infer `email_verified: true` from the\n * presence of `email` alone when linking accounts across providers.\n *\n * @see https://developers.facebook.com/docs/facebook-login/limited-login/token/validating/\n */\n idToken: string | null;\n profile: {\n userID: string;\n /**\n * Primary email from the Meta profile / Graph API (`/me?fields=email`).\n *\n * **Not equivalent to Google/Apple `email_verified`:** this field has no verification\n * flag. Meta returns the account's primary email when the `email` permission is\n * granted; it does not expose an `email_verified` boolean comparable to Google or\n * Apple ID tokens. Treat this as an identifier hint only—verify ownership yourself\n * (e.g. magic link) before linking Meta sign-in to Google/Apple accounts by email.\n */\n email: string | null;\n friendIDs: string[];\n birthday: string | null;\n ageRange: { min?: number; max?: number } | null;\n gender: string | null;\n location: { id: string; name: string } | null;\n hometown: { id: string; name: string } | null;\n profileURL: string | null;\n name: string | null;\n imageURL: string | null;\n };\n}\n\nexport interface TwitterProfile {\n id: string;\n username: string;\n name: string | null;\n profileImageUrl: string | null;\n verified: boolean;\n email?: string | null;\n}\n\nexport interface TwitterLoginResponse {\n accessToken: AccessToken | null;\n refreshToken?: string | null;\n scope: string[];\n tokenType: 'bearer';\n expiresIn?: number | null;\n profile: TwitterProfile;\n}\n\nexport interface TelegramProfile {\n id: string;\n firstName: string;\n lastName?: string | null;\n username?: string | null;\n photoUrl?: string | null;\n}\n\nexport interface TelegramLoginResponse {\n profile: TelegramProfile;\n /**\n * Unix timestamp (seconds) when the user authorized the login.\n */\n authDate: number;\n /**\n * Telegram-provided hash for server-side verification.\n */\n hash: string;\n /**\n * Requested access level that was used for this login.\n */\n requestAccess: 'read' | 'write';\n}\n\nexport interface AuthorizationCode {\n /**\n * Jwt\n * @description A JSON web token\n */\n jwt?: string;\n /**\n * Access Token\n * @description An access token\n */\n accessToken?: string;\n}\n\nexport interface AuthorizationCodeOptions {\n /**\n * Provider\n * @description Provider for the authorization code\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\nexport interface isLoggedInOptions {\n /**\n * Provider\n * @description Provider for the isLoggedIn\n */\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'oauth2';\n /**\n * Provider ID for OAuth2 providers (required when provider is 'oauth2')\n * @description The ID used when configuring the OAuth2 provider in initialize()\n */\n providerId?: string;\n}\n\n// Define the provider-specific call types\n/**\n * Options for `providerSpecificCall` with `google#createRestoreCredential`.\n *\n * Android-only. Creates a Restore Credential (restore key) via Credential Manager after the user\n * signs in. Your backend must supply WebAuthn PublicKeyCredentialCreationOptionsJSON (the same\n * FIDO2/passkey registration flow used for passkeys).\n *\n * @see https://developer.android.com/identity/sign-in/restore-credentials\n * @since 8.5.0\n */\nexport interface GoogleCreateRestoreCredentialOptions {\n /**\n * Credential creation options from your server in WebAuthn PublicKeyCredentialCreationOptionsJSON format.\n */\n requestJson: string;\n /**\n * When `true` (default), the restore key is backed up to the cloud when the user has backup and\n * end-to-end encryption (e.g. screen lock) enabled. If cloud backup creation fails with\n * `E2eeUnavailableException` on Android, the plugin automatically retries with local-only storage.\n * @default true\n */\n isCloudBackupEnabled?: boolean;\n}\n\n/**\n * Response from `google#createRestoreCredential`.\n *\n * Send `responseJson` to your server to complete restore key registration (same as passkey creation).\n */\nexport interface GoogleCreateRestoreCredentialResponse {\n /** Public key credential registration response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/**\n * Options for `providerSpecificCall` with `google#getRestoreCredential`.\n *\n * Android-only. Retrieves a Restore Credential silently (e.g. on first launch on a new device or from\n * BackupAgent `onRestoreFinished`). Your backend must supply WebAuthn authentication request JSON.\n */\nexport interface GoogleGetRestoreCredentialOptions {\n /**\n * Credential request options from your server (WebAuthn authentication request JSON).\n */\n requestJson: string;\n}\n\n/**\n * Response from `google#getRestoreCredential`.\n *\n * Send `responseJson` to your server to sign the user in (same server path as passkey authentication).\n */\nexport interface GoogleGetRestoreCredentialResponse {\n /** Restore credential authentication response JSON from Credential Manager. */\n responseJson: string;\n}\n\n/** Options for `google#clearRestoreCredential` (no fields). */\nexport type GoogleClearRestoreCredentialOptions = Record<string, never>;\n\n/** Response from `google#clearRestoreCredential`. */\nexport interface GoogleClearRestoreCredentialResponse {\n /** Whether the restore credential clear request completed successfully. */\n cleared: boolean;\n}\n\nexport type ProviderSpecificCall =\n | 'facebook#getProfile'\n | 'facebook#requestTracking'\n | 'google#createRestoreCredential'\n | 'google#getRestoreCredential'\n | 'google#clearRestoreCredential';\n\n// Define the options and response types for each specific call\nexport interface FacebookGetProfileOptions {\n /**\n * Fields to retrieve from Facebook profile.\n * @default ['id', 'name', 'email', 'picture']\n * @example [\"id\", \"name\", \"email\", \"picture\"]\n */\n fields?: string[];\n}\n\nexport interface FacebookGetProfileResponse {\n /**\n * Facebook profile data\n */\n profile: {\n id: string | null;\n name: string | null;\n email: string | null;\n first_name: string | null;\n last_name: string | null;\n picture?: {\n data: {\n height: number | null;\n is_silhouette: boolean | null;\n url: string | null;\n width: number | null;\n };\n } | null;\n [key: string]: any; // For additional fields that might be requested\n };\n}\n\nexport interface OpenSecureWindowOptions {\n /**\n * The endpoint to open\n */\n authEndpoint: string;\n /**\n * The redirect URI to use for the openSecureWindow call.\n * This will be checked to make sure it matches the redirect URI after the window finishes the redirection.\n */\n redirectUri: string;\n /**\n * The name of the broadcast channel to listen to, relevant only for web\n */\n broadcastChannelName?: string;\n}\n\nexport interface OpenSecureWindowResponse {\n /**\n * The result of the openSecureWindow call\n */\n redirectedUri: string;\n}\n\nexport type FacebookRequestTrackingOptions = Record<string, never>;\n\nexport interface FacebookRequestTrackingResponse {\n /**\n * App tracking authorization status\n */\n status: 'authorized' | 'denied' | 'notDetermined' | 'restricted';\n}\n\n// Map call strings to their options and response types\nexport type ProviderSpecificCallOptionsMap = {\n 'facebook#getProfile': FacebookGetProfileOptions;\n 'facebook#requestTracking': FacebookRequestTrackingOptions;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialOptions;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialOptions;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialOptions;\n};\n\nexport type ProviderSpecificCallResponseMap = {\n 'facebook#getProfile': FacebookGetProfileResponse;\n 'facebook#requestTracking': FacebookRequestTrackingResponse;\n 'google#createRestoreCredential': GoogleCreateRestoreCredentialResponse;\n 'google#getRestoreCredential': GoogleGetRestoreCredentialResponse;\n 'google#clearRestoreCredential': GoogleClearRestoreCredentialResponse;\n};\n\n// Add a helper type to map providers to their response types\nexport type ProviderResponseMap = {\n facebook: FacebookLoginResponse;\n google: GoogleLoginResponse;\n apple: AppleProviderResponse;\n twitter: TwitterLoginResponse;\n telegram: TelegramLoginResponse;\n oauth2: OAuth2LoginResponse;\n};\n\n/**\n * Error codes returned by the plugin.\n * @since 8.3.x\n */\nexport type SocialLoginErrorCode = 'USER_CANCELLED';\n\n/**\n * Errors thrown by SocialLogin methods.\n *\n * When a user dismisses or cancels the provider UI (popup closed, system dialog cancelled, access denied, etc.),\n * the plugin rejects with `code === 'USER_CANCELLED'` so the caller can distinguish user intent from real failures.\n * Other errors may omit the code or use provider-specific values.\n */\nexport interface SocialLoginError extends Error {\n code?: SocialLoginErrorCode | string;\n}\n\nexport interface SocialLoginPlugin {\n /**\n * Initialize the plugin\n * @description initialize the plugin with the required options\n */\n initialize(options: InitializeOptions): Promise<void>;\n /**\n * Login with the selected provider\n * @description login with the selected provider\n *\n * On user dismissal/cancellation, the Promise is rejected with `code === 'USER_CANCELLED'` (see `SocialLoginError`).\n */\n login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }>;\n /**\n * Logout\n * @description Logout the user from the specified provider\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * It will reject with error: \"logout is not implemented when using offline mode\"\n *\n * **Google Restore Credentials (Android):**\n * When logging out from Google, the plugin also clears any stored Restore Credential\n * (`google#clearRestoreCredential`) in addition to Credential Manager sign-in state.\n *\n * @throws Error if Google provider is in offline mode\n */\n logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | '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 * Telegram login does not produce an authorization code; use the `hash` from `login()` and verify it on your backend.\n *\n * @throws Error if Google provider is in offline mode\n */\n getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode>;\n /**\n * Refresh the access token\n * @description refresh the access token\n *\n * **Google Offline Mode Limitation:**\n * This method is NOT supported when Google is initialized with `mode: 'offline'`.\n * Offline mode only returns `serverAuthCode` for backend token exchange, so token refresh must happen on your backend.\n * The plugin logs and rejects with a message explaining that you should send `serverAuthCode` to your backend,\n * refresh the Google tokens there, or switch to `mode: 'online'` for client-side refresh.\n *\n * **Google Web Limitation:**\n * On Web, Google `refresh()` is not implemented, even when using `mode: 'online'`.\n * Call `login()` again on Web to obtain a fresh token instead.\n *\n * @throws Error if Google provider is in offline mode, or on Web where Google `refresh()` is not implemented\n */\n refresh(options: LoginOptions): Promise<void>;\n\n /**\n * OAuth2 refresh-token helper (feature parity with Capawesome OAuth).\n *\n * Scope:\n * - 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,5 +1,5 @@
1
1
  import { BaseSocialLogin } from './base';
2
- import type { AuthorizationCode, FacebookLoginOptions, LoginResult } from './definitions';
2
+ import type { AuthorizationCode, FacebookGetProfileResponse, FacebookLoginOptions, FacebookRequestTrackingResponse, LoginResult } from './definitions';
3
3
  export declare class FacebookSocialLogin extends BaseSocialLogin {
4
4
  private appId;
5
5
  private scriptLoaded;
@@ -12,6 +12,8 @@ export declare class FacebookSocialLogin extends BaseSocialLogin {
12
12
  }>;
13
13
  getAuthorizationCode(): Promise<AuthorizationCode>;
14
14
  refresh(options: FacebookLoginOptions): Promise<void>;
15
+ getProfile(fields?: string[]): Promise<FacebookGetProfileResponse>;
16
+ requestTracking(): Promise<FacebookRequestTrackingResponse>;
15
17
  private waitForConnection;
16
18
  private loadFacebookScript;
17
19
  }
@@ -121,6 +121,39 @@ export class FacebookSocialLogin extends BaseSocialLogin {
121
121
  async refresh(options) {
122
122
  await this.login(options);
123
123
  }
124
+ async getProfile(fields) {
125
+ if (!this.appId) {
126
+ throw new Error('Facebook App ID not set. Call initialize() first.');
127
+ }
128
+ const requestedFields = Array.isArray(fields) && fields.length > 0 ? fields : ['id', 'name', 'email', 'picture'];
129
+ return new Promise((resolve, reject) => {
130
+ FB.getLoginStatus((statusResponse) => {
131
+ if (statusResponse.status !== 'connected') {
132
+ reject(new Error('User is not logged in. Call login() before fetching profile.'));
133
+ return;
134
+ }
135
+ FB.api('/me', { fields: requestedFields.join(',') }, (profile) => {
136
+ var _a, _b, _c, _d, _e, _f, _g;
137
+ if (profile && !profile.error) {
138
+ resolve({
139
+ profile: Object.assign(Object.assign({}, profile), { id: (_a = profile.id) !== null && _a !== void 0 ? _a : null, name: (_b = profile.name) !== null && _b !== void 0 ? _b : null, email: (_c = profile.email) !== null && _c !== void 0 ? _c : null, first_name: (_d = profile.first_name) !== null && _d !== void 0 ? _d : null, last_name: (_e = profile.last_name) !== null && _e !== void 0 ? _e : null }),
140
+ });
141
+ }
142
+ else {
143
+ const errorMessage = (_g = (_f = profile === null || profile === void 0 ? void 0 : profile.error) === null || _f === void 0 ? void 0 : _f.message) !== null && _g !== void 0 ? _g : 'Failed to fetch Facebook profile';
144
+ reject(new Error(errorMessage));
145
+ }
146
+ });
147
+ });
148
+ });
149
+ }
150
+ async requestTracking() {
151
+ if (!this.appId) {
152
+ throw new Error('Facebook App ID not set. Call initialize() first.');
153
+ }
154
+ // App Tracking Transparency is not applicable on web.
155
+ return { status: 'authorized' };
156
+ }
124
157
  waitForConnection(timeoutMs = 120000, pollIntervalMs = 500) {
125
158
  const start = Date.now();
126
159
  return new Promise((resolve, reject) => {
@@ -1 +1 @@
1
- {"version":3,"file":"facebook-provider.js","sourceRoot":"","sources":["../../src/facebook-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAepD,MAAM,OAAO,mBAAoB,SAAQ,eAAe;IAAxD;;QACU,UAAK,GAAkB,IAAI,CAAC;QAC5B,iBAAY,GAAG,KAAK,CAAC;QACrB,WAAM,GAAG,OAAO,CAAC;IAgL3B,CAAC;IA9KC,KAAK,CAAC,UAAU,CAAC,KAAoB,EAAE,MAAe;QACpD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACvB,CAAC;QAED,IAAI,KAAK,EAAE,CAAC;YACV,4CAA4C;YAC5C,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3C,EAAE,CAAC,IAAI,CAAC;gBACN,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,OAAO,EAAE,OAAO;gBAChB,KAAK,EAAE,IAAI;gBACX,MAAM,EAAE,IAAI;aACb,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,OAA6B;QACvC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;;YACrC,IAAI,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AC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseSocialLogin } from './base';\nimport type { AuthorizationCode, FacebookLoginOptions, FacebookLoginResponse, LoginResult } from './definitions';\nimport { createUserCancelledError } from './errors';\n\ndeclare const FB: {\n init(options: any): void;\n login(\n callback: (response: { status: string; authResponse: { accessToken: string; userID: string } }) => void,\n options?: { scope: string },\n ): void;\n logout(callback: () => void): void;\n api(path: string, params: { fields: string }, callback: (response: any) => void): void;\n getLoginStatus(\n callback: (response: { status: string; authResponse?: { accessToken: string; userID?: string } }) => void,\n ): void;\n};\n\nexport class FacebookSocialLogin extends BaseSocialLogin {\n private appId: string | null = null;\n private scriptLoaded = false;\n private locale = 'en_US';\n\n async initialize(appId: string | null, locale?: string): Promise<void> {\n this.appId = appId;\n if (locale) {\n this.locale = locale;\n }\n\n if (appId) {\n // Load with the specified locale or default\n await this.loadFacebookScript(this.locale);\n FB.init({\n appId: this.appId,\n version: 'v17.0',\n xfbml: true,\n cookie: true,\n });\n }\n }\n\n async login(options: FacebookLoginOptions): Promise<LoginResult> {\n if (!this.appId) {\n throw new Error('Facebook App ID not set. Call initialize() first.');\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let waitingForStatus = false;\n\n const resolveWithProfile = (authResponse: { accessToken?: string; userID?: string } | undefined) => {\n if (settled) return;\n if (!authResponse?.accessToken || !authResponse.userID) {\n settled = true;\n reject(new Error('Facebook login failed'));\n return;\n }\n\n const accessToken = authResponse.accessToken;\n const userId = authResponse.userID;\n\n FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo: any) => {\n settled = true;\n const result: FacebookLoginResponse = {\n accessToken: {\n token: accessToken,\n userId,\n },\n profile: {\n userID: userInfo.id,\n name: userInfo.name,\n email: userInfo.email || null,\n imageURL: userInfo.picture?.data?.url || null,\n friendIDs: [],\n birthday: null,\n ageRange: null,\n gender: null,\n location: null,\n hometown: null,\n profileURL: null,\n },\n idToken: null,\n };\n resolve({ provider: 'facebook', result });\n });\n };\n\n const waitForConnected = () => {\n if (settled || waitingForStatus) return;\n waitingForStatus = true;\n this.waitForConnection()\n .then((statusResponse) => resolveWithProfile(statusResponse.authResponse))\n .catch((error) => {\n if (settled) return;\n settled = true;\n reject(error);\n });\n };\n\n FB.login(\n (response) => {\n if (response.status === 'connected') {\n resolveWithProfile(response.authResponse);\n } else if (response.status === 'not_authorized' || response.status === 'unknown') {\n reject(createUserCancelledError('Facebook login was cancelled.'));\n } else {\n waitForConnected();\n }\n },\n options.permissions?.length ? { scope: options.permissions.join(',') } : undefined,\n );\n });\n }\n\n async logout(): Promise<void> {\n return new Promise<void>((resolve) => {\n FB.logout(() => resolve());\n });\n }\n\n async isLoggedIn(): Promise<{ isLoggedIn: boolean }> {\n return new Promise((resolve) => {\n FB.getLoginStatus((response) => {\n resolve({ isLoggedIn: response.status === 'connected' });\n });\n });\n }\n\n async getAuthorizationCode(): Promise<AuthorizationCode> {\n return new Promise((resolve, reject) => {\n FB.getLoginStatus((response) => {\n if (response.status === 'connected') {\n resolve({ accessToken: response.authResponse?.accessToken || '' });\n } else {\n reject(new Error('No Facebook authorization code available'));\n }\n });\n });\n }\n\n async refresh(options: FacebookLoginOptions): Promise<void> {\n await this.login(options);\n }\n\n private waitForConnection(\n timeoutMs = 120000,\n pollIntervalMs = 500,\n ): Promise<{ status: string; authResponse?: { accessToken: string; userID?: string } }> {\n const start = Date.now();\n return new Promise((resolve, reject) => {\n let finished = false;\n\n const pollStatus = () => {\n if (finished) return;\n\n FB.getLoginStatus((response) => {\n if (finished) return;\n\n if (response.status === 'connected' && response.authResponse?.accessToken) {\n finished = true;\n resolve(response);\n return;\n }\n\n if (response.status === 'not_authorized' || response.status === 'unknown') {\n finished = true;\n reject(createUserCancelledError('Facebook login was cancelled.'));\n return;\n }\n\n if (Date.now() - start >= timeoutMs) {\n finished = true;\n reject(new Error('Facebook login failed or timed out'));\n return;\n }\n\n setTimeout(pollStatus, pollIntervalMs);\n });\n };\n\n pollStatus();\n });\n }\n\n private async loadFacebookScript(locale: string): Promise<void> {\n if (this.scriptLoaded) return;\n\n // Remove any existing Facebook SDK script\n const existingScript = document.querySelector('script[src*=\"connect.facebook.net\"]');\n if (existingScript) {\n existingScript.remove();\n }\n\n return this.loadScript(`https://connect.facebook.net/${locale}/sdk.js`).then(() => {\n this.scriptLoaded = true;\n });\n }\n}\n"]}
1
+ {"version":3,"file":"facebook-provider.js","sourceRoot":"","sources":["../../src/facebook-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AASzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAepD,MAAM,OAAO,mBAAoB,SAAQ,eAAe;IAAxD;;QACU,UAAK,GAAkB,IAAI,CAAC;QAC5B,iBAAY,GAAG,KAAK,CAAC;QACrB,WAAM,GAAG,OAAO,CAAC;IA2N3B,CAAC;IAzNC,KAAK,CAAC,UAAU,CAAC,KAAoB,EAAE,MAAe;QACpD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACvB,CAAC;QAED,IAAI,KAAK,EAAE,CAAC;YACV,4CAA4C;YAC5C,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3C,EAAE,CAAC,IAAI,CAAC;gBACN,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,OAAO,EAAE,OAAO;gBAChB,KAAK,EAAE,IAAI;gBACX,MAAM,EAAE,IAAI;aACb,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,OAA6B;QACvC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;;YACrC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ACf,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,KAAK,CAAC,kBAAkB,CAAC,MAAc;QAC7C,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO;QAE9B,0CAA0C;QAC1C,MAAM,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC,qCAAqC,CAAC,CAAC;QACrF,IAAI,cAAc,EAAE,CAAC;YACnB,cAAc,CAAC,MAAM,EAAE,CAAC;QAC1B,CAAC;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,gCAAgC,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;YAChF,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseSocialLogin } from './base';\nimport type {\n AuthorizationCode,\n FacebookGetProfileResponse,\n FacebookLoginOptions,\n FacebookLoginResponse,\n FacebookRequestTrackingResponse,\n LoginResult,\n} from './definitions';\nimport { createUserCancelledError } from './errors';\n\ndeclare const FB: {\n init(options: any): void;\n login(\n callback: (response: { status: string; authResponse: { accessToken: string; userID: string } }) => void,\n options?: { scope: string },\n ): void;\n logout(callback: () => void): void;\n api(path: string, params: { fields: string }, callback: (response: any) => void): void;\n getLoginStatus(\n callback: (response: { status: string; authResponse?: { accessToken: string; userID?: string } }) => void,\n ): void;\n};\n\nexport class FacebookSocialLogin extends BaseSocialLogin {\n private appId: string | null = null;\n private scriptLoaded = false;\n private locale = 'en_US';\n\n async initialize(appId: string | null, locale?: string): Promise<void> {\n this.appId = appId;\n if (locale) {\n this.locale = locale;\n }\n\n if (appId) {\n // Load with the specified locale or default\n await this.loadFacebookScript(this.locale);\n FB.init({\n appId: this.appId,\n version: 'v17.0',\n xfbml: true,\n cookie: true,\n });\n }\n }\n\n async login(options: FacebookLoginOptions): Promise<LoginResult> {\n if (!this.appId) {\n throw new Error('Facebook App ID not set. Call initialize() first.');\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let waitingForStatus = false;\n\n const resolveWithProfile = (authResponse: { accessToken?: string; userID?: string } | undefined) => {\n if (settled) return;\n if (!authResponse?.accessToken || !authResponse.userID) {\n settled = true;\n reject(new Error('Facebook login failed'));\n return;\n }\n\n const accessToken = authResponse.accessToken;\n const userId = authResponse.userID;\n\n FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo: any) => {\n settled = true;\n const result: FacebookLoginResponse = {\n accessToken: {\n token: accessToken,\n userId,\n },\n profile: {\n userID: userInfo.id,\n name: userInfo.name,\n email: userInfo.email || null,\n imageURL: userInfo.picture?.data?.url || null,\n friendIDs: [],\n birthday: null,\n ageRange: null,\n gender: null,\n location: null,\n hometown: null,\n profileURL: null,\n },\n idToken: null,\n };\n resolve({ provider: 'facebook', result });\n });\n };\n\n const waitForConnected = () => {\n if (settled || waitingForStatus) return;\n waitingForStatus = true;\n this.waitForConnection()\n .then((statusResponse) => resolveWithProfile(statusResponse.authResponse))\n .catch((error) => {\n if (settled) return;\n settled = true;\n reject(error);\n });\n };\n\n FB.login(\n (response) => {\n if (response.status === 'connected') {\n resolveWithProfile(response.authResponse);\n } else if (response.status === 'not_authorized' || response.status === 'unknown') {\n reject(createUserCancelledError('Facebook login was cancelled.'));\n } else {\n waitForConnected();\n }\n },\n options.permissions?.length ? { scope: options.permissions.join(',') } : undefined,\n );\n });\n }\n\n async logout(): Promise<void> {\n return new Promise<void>((resolve) => {\n FB.logout(() => resolve());\n });\n }\n\n async isLoggedIn(): Promise<{ isLoggedIn: boolean }> {\n return new Promise((resolve) => {\n FB.getLoginStatus((response) => {\n resolve({ isLoggedIn: response.status === 'connected' });\n });\n });\n }\n\n async getAuthorizationCode(): Promise<AuthorizationCode> {\n return new Promise((resolve, reject) => {\n FB.getLoginStatus((response) => {\n if (response.status === 'connected') {\n resolve({ accessToken: response.authResponse?.accessToken || '' });\n } else {\n reject(new Error('No Facebook authorization code available'));\n }\n });\n });\n }\n\n async refresh(options: FacebookLoginOptions): Promise<void> {\n await this.login(options);\n }\n\n async getProfile(fields?: string[]): Promise<FacebookGetProfileResponse> {\n if (!this.appId) {\n throw new Error('Facebook App ID not set. Call initialize() first.');\n }\n\n const requestedFields = Array.isArray(fields) && fields.length > 0 ? fields : ['id', 'name', 'email', 'picture'];\n\n return new Promise((resolve, reject) => {\n FB.getLoginStatus((statusResponse) => {\n if (statusResponse.status !== 'connected') {\n reject(new Error('User is not logged in. Call login() before fetching profile.'));\n return;\n }\n\n FB.api('/me', { fields: requestedFields.join(',') }, (profile: any) => {\n if (profile && !profile.error) {\n resolve({\n profile: {\n ...profile,\n id: profile.id ?? null,\n name: profile.name ?? null,\n email: profile.email ?? null,\n first_name: profile.first_name ?? null,\n last_name: profile.last_name ?? null,\n },\n });\n } else {\n const errorMessage = profile?.error?.message ?? 'Failed to fetch Facebook profile';\n reject(new Error(errorMessage));\n }\n });\n });\n });\n }\n\n async requestTracking(): Promise<FacebookRequestTrackingResponse> {\n if (!this.appId) {\n throw new Error('Facebook App ID not set. Call initialize() first.');\n }\n // App Tracking Transparency is not applicable on web.\n return { status: 'authorized' };\n }\n\n private waitForConnection(\n timeoutMs = 120000,\n pollIntervalMs = 500,\n ): Promise<{ status: string; authResponse?: { accessToken: string; userID?: string } }> {\n const start = Date.now();\n return new Promise((resolve, reject) => {\n let finished = false;\n\n const pollStatus = () => {\n if (finished) return;\n\n FB.getLoginStatus((response) => {\n if (finished) return;\n\n if (response.status === 'connected' && response.authResponse?.accessToken) {\n finished = true;\n resolve(response);\n return;\n }\n\n if (response.status === 'not_authorized' || response.status === 'unknown') {\n finished = true;\n reject(createUserCancelledError('Facebook login was cancelled.'));\n return;\n }\n\n if (Date.now() - start >= timeoutMs) {\n finished = true;\n reject(new Error('Facebook login failed or timed out'));\n return;\n }\n\n setTimeout(pollStatus, pollIntervalMs);\n });\n };\n\n pollStatus();\n });\n }\n\n private async loadFacebookScript(locale: string): Promise<void> {\n if (this.scriptLoaded) return;\n\n // Remove any existing Facebook SDK script\n const existingScript = document.querySelector('script[src*=\"connect.facebook.net\"]');\n if (existingScript) {\n existingScript.remove();\n }\n\n return this.loadScript(`https://connect.facebook.net/${locale}/sdk.js`).then(() => {\n this.scriptLoaded = true;\n });\n }\n}\n"]}
@@ -9,7 +9,13 @@ export const OAUTH_STATE_KEY = 'social_login_oauth_pending';
9
9
  export const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';
10
10
  export const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';
11
11
  export const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';
12
- export const POPUP_WINDOW_NAMES = new Set(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);
12
+ export const POPUP_WINDOW_NAMES = new Set([
13
+ 'OAuth2Login',
14
+ 'XLogin',
15
+ 'Google Sign In',
16
+ 'Authorization',
17
+ 'TelegramLogin',
18
+ ]);
13
19
  export function getOAuthResultKey(nonce) {
14
20
  return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;
15
21
  }
@@ -18,6 +24,8 @@ export function getBroadcastChannelName(provider, nonceOrState) {
18
24
  return `oauth2_${nonceOrState}`;
19
25
  if (provider === 'twitter')
20
26
  return `twitter_oauth_${nonceOrState}`;
27
+ if (provider === 'telegram')
28
+ return `telegram_oauth_${nonceOrState}`;
21
29
  return `google_oauth_${nonceOrState}`;
22
30
  }
23
31
  export function markOAuthPopup(nonce) {
@@ -38,12 +46,14 @@ export function clearOAuthPopupMarker() {
38
46
  }
39
47
  }
40
48
  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='));
49
+ const search = new URLSearchParams(window.location.search);
50
+ const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));
51
+ return (search.has('code') ||
52
+ search.has('error') ||
53
+ (search.has('hash') && search.has('auth_date')) ||
54
+ hash.has('access_token') ||
55
+ hash.has('id_token') ||
56
+ hash.has('error'));
47
57
  }
48
58
  export function isOAuthPopupContext() {
49
59
  if (typeof window === 'undefined')
@@ -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;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;IAAC,WAAM,CAAC;QACP,qDAAqD;IACvD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qBAAqB;IACnC,IAAI,CAAC;QACH,cAAc,CAAC,UAAU,CAAC,uBAAuB,CAAC,CAAC;IACrD,CAAC;IAAC,WAAM,CAAC;QACP,SAAS;IACX,C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AAS,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(['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"]}
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,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,QAA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AAC,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"]}
@@ -2,6 +2,7 @@ import { inferUserCancelledError } from './errors';
2
2
  import { GoogleSocialLogin } from './google-provider';
3
3
  import { clearOAuthPopupMarker, deliverOAuthResult, OAUTH_STATE_KEY, shouldAutoFinishOAuthRedirect, } from './oauth-popup-bridge';
4
4
  import { OAuth2SocialLogin } from './oauth2-provider';
5
+ import { TelegramSocialLogin } from './telegram-provider';
5
6
  import { TwitterSocialLogin } from './twitter-provider';
6
7
  async function parseRedirectResult() {
7
8
  var _a;
@@ -24,11 +25,15 @@ async function parseRedirectResult() {
24
25
  const googleProvider = new GoogleSocialLogin();
25
26
  const oauth2Provider = new OAuth2SocialLogin();
26
27
  const twitterProvider = new TwitterSocialLogin();
28
+ const telegramProvider = new TelegramSocialLogin();
27
29
  let result = null;
28
30
  switch (provider) {
29
31
  case 'twitter':
30
32
  result = await twitterProvider.handleOAuthRedirect(url, state);
31
33
  break;
34
+ case 'telegram':
35
+ result = await telegramProvider.handleOAuthRedirect(url, state);
36
+ break;
32
37
  case 'oauth2':
33
38
  result = await oauth2Provider.handleOAuthRedirect(url, state);
34
39
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-popup-redirect.js","sourceRoot":"","sources":["../../src/oauth-popup-redirect.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,6BAA6B,GAE9B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB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Y,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,YAAY,EAAE,CAAC;gBACjB,kBAAkB,CAAC,MAAA,WAAW,CAAC,QAAQ,mCAAI,QAAQ,EAAE,MAAA,WAAW,CAAC,KAAK,mCAAI,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAC7G,CAAC;iBAAM,CAAC;gBACN,kBAAkB,CAAC,MAAA,MAAM,CAAC,QAAQ,mCAAI,QAAQ,EAAE,YAAY,EAAE;oBAC5D,IAAI,EAAE,aAAa;oBACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;oBACzB,KAAK,EAAE,qDAAqD;iBAC7D,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;SAAM,CAAC;QACN,kBAAkB,CAAC,MAAA,MAAM,CAAC,QAAQ,mCAAI,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACzE,CAAC;IAED,qBAAqB,EAAE,CAAC;IAExB,IAAI,CAAC;QACH,MAAM,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,4DAA4D;IAC9D,CAAC;AACH,CAAC;AAED,SAAS,YAAY;IACnB,IAAI,CAAC,6BAA6B,EAAE;QAAE,OAAO;IAC7C,KAAK,0BAA0B,EAAE,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,6BAA6B;IAC3C,IAAI,OAAO,MAAM,KAAK,WAAW;QAAE,OAAO;IAE1C,IAAI,6BAA6B,EAAE,EAAE,CAAC;QACpC,KAAK,0BAA0B,EAAE,CAAC;IACpC,CAAC;IAED,0DAA0D;IAC1D,MAAM,CAAC,gBAAgB,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;AACtD,CAAC;AAED,gFAAgF;AAChF,6BAA6B,EAAE,CAAC","sourcesContent":["/**\n * Eager OAuth popup redirect handler.\n *\n * Capacitor lazily loads the web plugin implementation, so the popup window may\n * never instantiate SocialLoginWeb after Google redirects back. This module runs\n * immediately when the package is imported and finishes the OAuth redirect in popup\n * windows without waiting for plugin initialization.\n */\nimport type { LoginResult } from './definitions';\nimport { inferUserCancelledError } from './errors';\nimport { GoogleSocialLogin } from './google-provider';\nimport {\n clearOAuthPopupMarker,\n deliverOAuthResult,\n OAUTH_STATE_KEY,\n shouldAutoFinishOAuthRedirect,\n type OAuthBridgeMessage,\n} from './oauth-popup-bridge';\nimport { OAuth2SocialLogin } from './oauth2-provider';\nimport { TwitterSocialLogin } from './twitter-provider';\n\nasync function parseRedirectResult(): Promise<{\n provider: string | null;\n state?: string;\n nonce?: string;\n result: LoginResult | { error: string } | null;\n}> {\n const url = new URL(window.location.href);\n const stateRaw = localStorage.getItem(OAUTH_STATE_KEY);\n let provider: string | null = null;\n let state: string | undefined;\n let nonce: string | undefined;\n\n if (stateRaw) {\n try {\n const parsed = JSON.parse(stateRaw);\n provider = parsed.provider ?? null;\n state = parsed.state;\n nonce = parsed.nonce;\n } catch {\n provider = stateRaw === 'true' ? 'google' : null;\n }\n }\n\n const googleProvider = new GoogleSocialLogin();\n const oauth2Provider = new OAuth2SocialLogin();\n const twitterProvider = new TwitterSocialLogin();\n\n let result: LoginResult | { error: string } | null = null;\n\n switch (provider) {\n case 'twitter':\n result = await twitterProvider.handleOAuthRedirect(url, state);\n break;\n case 'oauth2':\n result = await oauth2Provider.handleOAuthRedirect(url, state);\n break;\n case 'google':\n default:\n result = googleProvider.handleOAuthRedirect(url);\n break;\n }\n\n return { provider, state, nonce, result };\n}\n\nfunction buildOAuthMessage(parsed: Awaited<ReturnType<typeof parseRedirectResult>>): OAuthBridgeMessage | null {\n const { result } = parsed;\n if (!result) return null;\n\n if ('error' in result) {\n const error = inferUserCancelledError(result.error);\n return {\n type: 'oauth-error',\n provider: parsed.provider,\n error: error.message,\n ...(error.code ? { code: error.code } : null),\n };\n }\n\n return {\n type: 'oauth-response',\n provider: result.provider,\n ...result.result,\n };\n}\n\nasync function finishOAuthRedirectInPopup(): Promise<void> {\n const parsed = await parseRedirectResult();\n const nonceOrState = parsed.nonce ?? parsed.state;\n const message = buildOAuthMessage(parsed);\n\n if (!message) {\n // OAuth params may not be ready yet (SPA router). Retry briefly.\n if (shouldAutoFinishOAuthRedirect()) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n const retryParsed = await parseRedirectResult();\n const retryMessage = buildOAuthMessage(retryParsed);\n if (retryMessage) {\n deliverOAuthResult(retryParsed.provider ?? 'google', retryParsed.nonce ?? retryParsed.state, retryMessage);\n } else {\n deliverOAuthResult(parsed.provider ?? 'google', nonceOrState, {\n type: 'oauth-error',\n provider: parsed.provider,\n error: 'OAuth redirect did not contain expected parameters.',\n });\n }\n }\n } else {\n deliverOAuthResult(parsed.provider ?? 'google', nonceOrState, message);\n }\n\n clearOAuthPopupMarker();\n\n try {\n window.close();\n } catch {\n // Popup may not be allowed to close itself in some contexts\n }\n}\n\nfunction onHashChange(): void {\n if (!shouldAutoFinishOAuthRedirect()) return;\n void finishOAuthRedirectInPopup();\n}\n\nexport function initOAuthPopupRedirectHandler(): void {\n if (typeof window === 'undefined') return;\n\n if (shouldAutoFinishOAuthRedirect()) {\n void finishOAuthRedirectInPopup();\n }\n\n // SPA routers may apply the OAuth hash after initial load\n window.addEventListener('hashchange', onHashChange);\n}\n\n// Auto-run on import so popup windows finish OAuth even before plugin lazy-load\ninitOAuthPopupRedirectHandler();\n"]}
1
+ {"version":3,"file":"oauth-popup-redirect.js","sourceRoot":"","sources":["../../src/oauth-popup-redirect.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,6BAA6B,GAE9B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,C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;AACtD,CAAC;AAED,gFAAgF;AAChF,6BAA6B,EAAE,CAAC","sourcesContent":["/**\n * Eager OAuth popup redirect handler.\n *\n * Capacitor lazily loads the web plugin implementation, so the popup window may\n * never instantiate SocialLoginWeb after Google redirects back. This module runs\n * immediately when the package is imported and finishes the OAuth redirect in popup\n * windows without waiting for plugin initialization.\n */\nimport type { LoginResult } from './definitions';\nimport { inferUserCancelledError } from './errors';\nimport { GoogleSocialLogin } from './google-provider';\nimport {\n clearOAuthPopupMarker,\n deliverOAuthResult,\n OAUTH_STATE_KEY,\n shouldAutoFinishOAuthRedirect,\n type OAuthBridgeMessage,\n} from './oauth-popup-bridge';\nimport { OAuth2SocialLogin } from './oauth2-provider';\nimport { TelegramSocialLogin } from './telegram-provider';\nimport { TwitterSocialLogin } from './twitter-provider';\n\nasync function parseRedirectResult(): Promise<{\n provider: string | null;\n state?: string;\n nonce?: string;\n result: LoginResult | { error: string } | null;\n}> {\n const url = new URL(window.location.href);\n const stateRaw = localStorage.getItem(OAUTH_STATE_KEY);\n let provider: string | null = null;\n let state: string | undefined;\n let nonce: string | undefined;\n\n if (stateRaw) {\n try {\n const parsed = JSON.parse(stateRaw);\n provider = parsed.provider ?? null;\n state = parsed.state;\n nonce = parsed.nonce;\n } catch {\n provider = stateRaw === 'true' ? 'google' : null;\n }\n }\n\n const googleProvider = new GoogleSocialLogin();\n const oauth2Provider = new OAuth2SocialLogin();\n const twitterProvider = new TwitterSocialLogin();\n const telegramProvider = new TelegramSocialLogin();\n\n let result: LoginResult | { error: string } | null = null;\n\n switch (provider) {\n case 'twitter':\n result = await twitterProvider.handleOAuthRedirect(url, state);\n break;\n case 'telegram':\n result = await telegramProvider.handleOAuthRedirect(url, state);\n break;\n case 'oauth2':\n result = await oauth2Provider.handleOAuthRedirect(url, state);\n break;\n case 'google':\n default:\n result = googleProvider.handleOAuthRedirect(url);\n break;\n }\n\n return { provider, state, nonce, result };\n}\n\nfunction buildOAuthMessage(parsed: Awaited<ReturnType<typeof parseRedirectResult>>): OAuthBridgeMessage | null {\n const { result } = parsed;\n if (!result) return null;\n\n if ('error' in result) {\n const error = inferUserCancelledError(result.error);\n return {\n type: 'oauth-error',\n provider: parsed.provider,\n error: error.message,\n ...(error.code ? { code: error.code } : null),\n };\n }\n\n return {\n type: 'oauth-response',\n provider: result.provider,\n ...result.result,\n };\n}\n\nasync function finishOAuthRedirectInPopup(): Promise<void> {\n const parsed = await parseRedirectResult();\n const nonceOrState = parsed.nonce ?? parsed.state;\n const message = buildOAuthMessage(parsed);\n\n if (!message) {\n // OAuth params may not be ready yet (SPA router). Retry briefly.\n if (shouldAutoFinishOAuthRedirect()) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n const retryParsed = await parseRedirectResult();\n const retryMessage = buildOAuthMessage(retryParsed);\n if (retryMessage) {\n deliverOAuthResult(retryParsed.provider ?? 'google', retryParsed.nonce ?? retryParsed.state, retryMessage);\n } else {\n deliverOAuthResult(parsed.provider ?? 'google', nonceOrState, {\n type: 'oauth-error',\n provider: parsed.provider,\n error: 'OAuth redirect did not contain expected parameters.',\n });\n }\n }\n } else {\n deliverOAuthResult(parsed.provider ?? 'google', nonceOrState, message);\n }\n\n clearOAuthPopupMarker();\n\n try {\n window.close();\n } catch {\n // Popup may not be allowed to close itself in some contexts\n }\n}\n\nfunction onHashChange(): void {\n if (!shouldAutoFinishOAuthRedirect()) return;\n void finishOAuthRedirectInPopup();\n}\n\nexport function initOAuthPopupRedirectHandler(): void {\n if (typeof window === 'undefined') return;\n\n if (shouldAutoFinishOAuthRedirect()) {\n void finishOAuthRedirectInPopup();\n }\n\n // SPA routers may apply the OAuth hash after initial load\n window.addEventListener('hashchange', onHashChange);\n}\n\n// Auto-run on import so popup windows finish OAuth even before plugin lazy-load\ninitOAuthPopupRedirectHandler();\n"]}
@@ -11,7 +11,7 @@ declare class SocialLoginClient implements SocialLoginPlugin {
11
11
  result: ProviderResponseMap[T];
12
12
  }>;
13
13
  logout(options: {
14
- provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2';
14
+ provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'oauth2';
15
15
  providerId?: string;
16
16
  }): Promise<void>;
17
17
  isLoggedIn(options: isLoggedInOptions): Promise<{
@@ -1 +1 @@
1
- {"version":3,"file":"social-login.js","sourceRoot":"","sources":["../../src/social-login.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,2EAA2E;AAC3E,OAAO,wBAAwB,CAAC;AAkBhC,MAAM,8BAA8B,GAClC,0PAA0P,CAAC;AAE7P,MAAM,cAAc,GAAG,cAAc,CAAoB,aAAa,EAAE;IACtE,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,CAAC;CAC/D,CAAC,CAAC;AAEH,MAAM,iBAAiB;IAGrB;QACE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAA0B;QACzC,MAAM,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,KAAK,CACT,OAA+C;QAE/C,OAAO,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAGZ;QACC,OAAO,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAA0B;QACzC,OAAO,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC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BAAoB,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,OAAO,cAAc,CAAC,gBAAgB,EAAE,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,OAAgC;QACrD,OAAO,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;CACF;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,cAAc,CAAC;AAC9C,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\n\n// Eagerly finish OAuth popup redirects before plugin lazy-load (COOP-safe)\nimport './oauth-popup-redirect';\n\nimport type {\n AuthorizationCode,\n AuthorizationCodeOptions,\n InitializeOptions,\n LoginOptions,\n OpenSecureWindowOptions,\n OpenSecureWindowResponse,\n OAuth2LoginResponse,\n ProviderResponseMap,\n ProviderSpecificCall,\n ProviderSpecificCallOptionsMap,\n ProviderSpecificCallResponseMap,\n SocialLoginPlugin,\n isLoggedInOptions,\n} from './definitions';\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\nconst rawSocialLogin = registerPlugin<SocialLoginPlugin>('SocialLogin', {\n web: () => import('./web').then((m) => new m.SocialLoginWeb()),\n});\n\nclass SocialLoginClient implements SocialLoginPlugin {\n private initializeOptions?: InitializeOptions;\n\n constructor() {\n this.initialize = this.initialize.bind(this);\n this.refresh = this.refresh.bind(this);\n }\n\n async initialize(options: InitializeOptions): Promise<void> {\n await rawSocialLogin.initialize(options);\n this.initializeOptions = options;\n }\n\n async login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }> {\n return rawSocialLogin.login(options);\n }\n\n async logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2';\n providerId?: string;\n }): Promise<void> {\n return rawSocialLogin.logout(options);\n }\n\n async isLoggedIn(options: isLoggedInOptions): Promise<{ isLoggedIn: boolean }> {\n return rawSocialLogin.isLoggedIn(options);\n }\n\n async getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode> {\n return rawSocialLogin.getAuthorizationCode(options);\n }\n\n async refresh(options: LoginOptions): Promise<void> {\n if (options.provider === 'google' && this.initializeOptions?.google?.mode === 'offline') {\n console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);\n }\n return rawSocialLogin.refresh(options);\n }\n\n async refreshToken(options: {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }): Promise<OAuth2LoginResponse> {\n return rawSocialLogin.refreshToken(options);\n }\n\n async handleRedirectCallback() {\n return rawSocialLogin.handleRedirectCallback();\n }\n\n async decodeIdToken(options: { idToken?: string; token?: string }): Promise<{ claims: Record<string, any> }> {\n return rawSocialLogin.decodeIdToken(options);\n }\n\n async getAccessTokenExpirationDate(options: { accessTokenExpirationDate: number }): Promise<{ date: string }> {\n return rawSocialLogin.getAccessTokenExpirationDate(options);\n }\n\n async isAccessTokenAvailable(options: { accessToken: string | null }): Promise<{ isAvailable: boolean }> {\n return rawSocialLogin.isAccessTokenAvailable(options);\n }\n\n async isAccessTokenExpired(options: { accessTokenExpirationDate: number }): Promise<{ isExpired: boolean }> {\n return rawSocialLogin.isAccessTokenExpired(options);\n }\n\n async isRefreshTokenAvailable(options: { refreshToken: string | null }): Promise<{ isAvailable: boolean }> {\n return rawSocialLogin.isRefreshTokenAvailable(options);\n }\n\n async providerSpecificCall<T extends ProviderSpecificCall>(options: {\n call: T;\n options: ProviderSpecificCallOptionsMap[T];\n }): Promise<ProviderSpecificCallResponseMap[T]> {\n return rawSocialLogin.providerSpecificCall(options);\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return rawSocialLogin.getPluginVersion();\n }\n\n async openSecureWindow(options: OpenSecureWindowOptions): Promise<OpenSecureWindowResponse> {\n return rawSocialLogin.openSecureWindow(options);\n }\n}\n\nexport const SocialLoginBase = rawSocialLogin;\nexport const SocialLogin = new SocialLoginClient();\n"]}
1
+ {"version":3,"file":"social-login.js","sourceRoot":"","sources":["../../src/social-login.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,2EAA2E;AAC3E,OAAO,wBAAwB,CAAC;AAkBhC,MAAM,8BAA8B,GAClC,0PAA0P,CAAC;AAE7P,MAAM,cAAc,GAAG,cAAc,CAAoB,aAAa,EAAE;IACtE,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,CAAC;CAC/D,CAAC,CAAC;AAEH,MAAM,iBAAiB;IAGrB;QACE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAA0B;QACzC,MAAM,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,KAAK,CACT,OAA+C;QAE/C,OAAO,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAGZ;QACC,OAAO,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAA0B;QACzC,OAAO,cAAc,CAAC,UAAU,CAAC,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Ac,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,OAAO,cAAc,CAAC,gBAAgB,EAAE,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,OAAgC;QACrD,OAAO,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;CACF;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,cAAc,CAAC;AAC9C,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,iBAAiB,EAAE,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\n\n// Eagerly finish OAuth popup redirects before plugin lazy-load (COOP-safe)\nimport './oauth-popup-redirect';\n\nimport type {\n AuthorizationCode,\n AuthorizationCodeOptions,\n InitializeOptions,\n LoginOptions,\n OpenSecureWindowOptions,\n OpenSecureWindowResponse,\n OAuth2LoginResponse,\n ProviderResponseMap,\n ProviderSpecificCall,\n ProviderSpecificCallOptionsMap,\n ProviderSpecificCallResponseMap,\n SocialLoginPlugin,\n isLoggedInOptions,\n} from './definitions';\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\nconst rawSocialLogin = registerPlugin<SocialLoginPlugin>('SocialLogin', {\n web: () => import('./web').then((m) => new m.SocialLoginWeb()),\n});\n\nclass SocialLoginClient implements SocialLoginPlugin {\n private initializeOptions?: InitializeOptions;\n\n constructor() {\n this.initialize = this.initialize.bind(this);\n this.refresh = this.refresh.bind(this);\n }\n\n async initialize(options: InitializeOptions): Promise<void> {\n await rawSocialLogin.initialize(options);\n this.initializeOptions = options;\n }\n\n async login<T extends LoginOptions['provider']>(\n options: Extract<LoginOptions, { provider: T }>,\n ): Promise<{ provider: T; result: ProviderResponseMap[T] }> {\n return rawSocialLogin.login(options);\n }\n\n async logout(options: {\n provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'oauth2';\n providerId?: string;\n }): Promise<void> {\n return rawSocialLogin.logout(options);\n }\n\n async isLoggedIn(options: isLoggedInOptions): Promise<{ isLoggedIn: boolean }> {\n return rawSocialLogin.isLoggedIn(options);\n }\n\n async getAuthorizationCode(options: AuthorizationCodeOptions): Promise<AuthorizationCode> {\n return rawSocialLogin.getAuthorizationCode(options);\n }\n\n async refresh(options: LoginOptions): Promise<void> {\n if (options.provider === 'google' && this.initializeOptions?.google?.mode === 'offline') {\n console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);\n }\n return rawSocialLogin.refresh(options);\n }\n\n async refreshToken(options: {\n provider: 'oauth2';\n providerId: string;\n refreshToken?: string;\n additionalParameters?: Record<string, string>;\n }): Promise<OAuth2LoginResponse> {\n return rawSocialLogin.refreshToken(options);\n }\n\n async handleRedirectCallback() {\n return rawSocialLogin.handleRedirectCallback();\n }\n\n async decodeIdToken(options: { idToken?: string; token?: string }): Promise<{ claims: Record<string, any> }> {\n return rawSocialLogin.decodeIdToken(options);\n }\n\n async getAccessTokenExpirationDate(options: { accessTokenExpirationDate: number }): Promise<{ date: string }> {\n return rawSocialLogin.getAccessTokenExpirationDate(options);\n }\n\n async isAccessTokenAvailable(options: { accessToken: string | null }): Promise<{ isAvailable: boolean }> {\n return rawSocialLogin.isAccessTokenAvailable(options);\n }\n\n async isAccessTokenExpired(options: { accessTokenExpirationDate: number }): Promise<{ isExpired: boolean }> {\n return rawSocialLogin.isAccessTokenExpired(options);\n }\n\n async isRefreshTokenAvailable(options: { refreshToken: string | null }): Promise<{ isAvailable: boolean }> {\n return rawSocialLogin.isRefreshTokenAvailable(options);\n }\n\n async providerSpecificCall<T extends ProviderSpecificCall>(options: {\n call: T;\n options: ProviderSpecificCallOptionsMap[T];\n }): Promise<ProviderSpecificCallResponseMap[T]> {\n return rawSocialLogin.providerSpecificCall(options);\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return rawSocialLogin.getPluginVersion();\n }\n\n async openSecureWindow(options: OpenSecureWindowOptions): Promise<OpenSecureWindowResponse> {\n return rawSocialLogin.openSecureWindow(options);\n }\n}\n\nexport const SocialLoginBase = rawSocialLogin;\nexport const SocialLogin = new SocialLoginClient();\n"]}