@capgo/capacitor-social-login 8.4.4 → 8.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -1,1319 +1,1485 @@
1
1
  var capacitorCapacitorUpdater = (function (exports, core) {
2
2
  'use strict';
3
3
 
4
- const GOOGLE_OFFLINE_REFRESH_MESSAGE$1 = "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.";
5
- const rawSocialLogin = core.registerPlugin('SocialLogin', {
6
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.SocialLoginWeb()),
7
- });
8
- class SocialLoginClient {
9
- constructor() {
10
- this.initialize = this.initialize.bind(this);
11
- this.refresh = this.refresh.bind(this);
12
- }
13
- async initialize(options) {
14
- await rawSocialLogin.initialize(options);
15
- this.initializeOptions = options;
16
- }
17
- async login(options) {
18
- return rawSocialLogin.login(options);
19
- }
20
- async logout(options) {
21
- return rawSocialLogin.logout(options);
4
+ const USER_CANCELLED_CODE = 'USER_CANCELLED';
5
+ const CANCELLED_PATTERNS = [
6
+ 'access_denied',
7
+ 'access denied',
8
+ 'user_cancelled_authorize',
9
+ 'user_cancelled',
10
+ 'user cancelled',
11
+ 'user canceled',
12
+ 'login cancelled',
13
+ 'login canceled',
14
+ 'popup closed',
15
+ 'window was closed',
16
+ ];
17
+ function createUserCancelledError(message) {
18
+ const error = new Error(message);
19
+ error.code = USER_CANCELLED_CODE;
20
+ return error;
21
+ }
22
+ /**
23
+ * Detects cancellation-like messages and marks them with USER_CANCELLED.
24
+ * Falls back to a regular Error when the message doesn't look like a user cancellation.
25
+ */
26
+ function inferUserCancelledError(message) {
27
+ const normalized = message.toLowerCase();
28
+ if (CANCELLED_PATTERNS.some((pattern) => normalized.includes(pattern))) {
29
+ return createUserCancelledError(message);
22
30
  }
23
- async isLoggedIn(options) {
24
- return rawSocialLogin.isLoggedIn(options);
31
+ return new Error(message);
32
+ }
33
+
34
+ class BaseSocialLogin extends core.WebPlugin {
35
+ constructor() {
36
+ super();
25
37
  }
26
- async getAuthorizationCode(options) {
27
- return rawSocialLogin.getAuthorizationCode(options);
38
+ parseJwt(token) {
39
+ const base64Url = token.split('.')[1];
40
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
41
+ const jsonPayload = decodeURIComponent(atob(base64)
42
+ .split('')
43
+ .map((c) => {
44
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
45
+ })
46
+ .join(''));
47
+ return JSON.parse(jsonPayload);
28
48
  }
29
- async refresh(options) {
30
- var _a, _b;
31
- if (options.provider === 'google' && ((_b = (_a = this.initializeOptions) === null || _a === void 0 ? void 0 : _a.google) === null || _b === void 0 ? void 0 : _b.mode) === 'offline') {
32
- console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE$1}`);
33
- }
34
- return rawSocialLogin.refresh(options);
49
+ async loadScript(src) {
50
+ return new Promise((resolve, reject) => {
51
+ const script = document.createElement('script');
52
+ script.src = src;
53
+ script.async = true;
54
+ script.onload = () => {
55
+ resolve();
56
+ };
57
+ script.onerror = reject;
58
+ document.body.appendChild(script);
59
+ });
35
60
  }
36
- async refreshToken(options) {
37
- return rawSocialLogin.refreshToken(options);
61
+ }
62
+ BaseSocialLogin.OAUTH_STATE_KEY = 'social_login_oauth_pending';
63
+
64
+ /**
65
+ * COOP-safe OAuth popup communication bridge.
66
+ *
67
+ * When Cross-Origin-Opener-Policy severs window.opener, postMessage and popup.closed
68
+ * checks fail. This module uses localStorage + storage events and BroadcastChannel
69
+ * as reliable fallbacks that work across same-origin popup windows.
70
+ */
71
+ const OAUTH_STATE_KEY = 'social_login_oauth_pending';
72
+ const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';
73
+ const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';
74
+ const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';
75
+ const POPUP_WINDOW_NAMES = new Set(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);
76
+ function getOAuthResultKey(nonce) {
77
+ return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;
78
+ }
79
+ function getBroadcastChannelName(provider, nonceOrState) {
80
+ if (provider === 'oauth2')
81
+ return `oauth2_${nonceOrState}`;
82
+ if (provider === 'twitter')
83
+ return `twitter_oauth_${nonceOrState}`;
84
+ return `google_oauth_${nonceOrState}`;
85
+ }
86
+ function markOAuthPopup(nonce) {
87
+ try {
88
+ sessionStorage.removeItem(OAUTH_DELIVERED_KEY);
89
+ sessionStorage.setItem(OAUTH_POPUP_SESSION_KEY, nonce);
38
90
  }
39
- async handleRedirectCallback() {
40
- return rawSocialLogin.handleRedirectCallback();
91
+ catch (_a) {
92
+ // sessionStorage may be unavailable in some contexts
41
93
  }
42
- async decodeIdToken(options) {
43
- return rawSocialLogin.decodeIdToken(options);
94
+ }
95
+ function clearOAuthPopupMarker() {
96
+ try {
97
+ sessionStorage.removeItem(OAUTH_POPUP_SESSION_KEY);
44
98
  }
45
- async getAccessTokenExpirationDate(options) {
46
- return rawSocialLogin.getAccessTokenExpirationDate(options);
99
+ catch (_a) {
100
+ // ignore
47
101
  }
48
- async isAccessTokenAvailable(options) {
49
- return rawSocialLogin.isAccessTokenAvailable(options);
102
+ }
103
+ function hasOAuthRedirectParams() {
104
+ const { search, hash } = window.location;
105
+ return (search.includes('code=') ||
106
+ search.includes('error=') ||
107
+ hash.includes('access_token=') ||
108
+ hash.includes('id_token=') ||
109
+ hash.includes('error='));
110
+ }
111
+ function isOAuthPopupContext() {
112
+ if (typeof window === 'undefined')
113
+ return false;
114
+ return !!window.opener || POPUP_WINDOW_NAMES.has(window.name) || !!sessionStorage.getItem(OAUTH_POPUP_SESSION_KEY);
115
+ }
116
+ function shouldAutoFinishOAuthRedirect() {
117
+ if (!localStorage.getItem(OAUTH_STATE_KEY))
118
+ return false;
119
+ return isOAuthPopupContext() || hasOAuthRedirectParams();
120
+ }
121
+ /**
122
+ * Deliver OAuth result from popup to opener via all available channels.
123
+ */
124
+ function deliverOAuthResult(provider, nonceOrState, message) {
125
+ // Prevent duplicate delivery when both eager handler and plugin constructor run
126
+ try {
127
+ if (sessionStorage.getItem(OAUTH_DELIVERED_KEY))
128
+ return;
129
+ sessionStorage.setItem(OAUTH_DELIVERED_KEY, '1');
50
130
  }
51
- async isAccessTokenExpired(options) {
52
- return rawSocialLogin.isAccessTokenExpired(options);
131
+ catch (_a) {
132
+ // sessionStorage unavailable
53
133
  }
54
- async isRefreshTokenAvailable(options) {
55
- return rawSocialLogin.isRefreshTokenAvailable(options);
134
+ // postMessage when opener reference is still available
135
+ try {
136
+ if (window.opener) {
137
+ window.opener.postMessage(message, window.location.origin);
138
+ }
56
139
  }
57
- async providerSpecificCall(options) {
58
- return rawSocialLogin.providerSpecificCall(options);
140
+ catch (_b) {
141
+ // COOP may block opener access
59
142
  }
60
- async getPluginVersion() {
61
- return rawSocialLogin.getPluginVersion();
143
+ // BroadcastChannel works across same-origin windows without opener
144
+ if (nonceOrState) {
145
+ try {
146
+ const channel = new BroadcastChannel(getBroadcastChannelName(provider, nonceOrState));
147
+ channel.postMessage(message);
148
+ channel.close();
149
+ }
150
+ catch (_c) {
151
+ // BroadcastChannel not supported
152
+ }
62
153
  }
63
- async openSecureWindow(options) {
64
- return rawSocialLogin.openSecureWindow(options);
154
+ // localStorage + storage event is the most COOP-resilient fallback
155
+ if (nonceOrState) {
156
+ try {
157
+ localStorage.setItem(getOAuthResultKey(nonceOrState), JSON.stringify(Object.assign(Object.assign({}, message), { _ts: Date.now() })));
158
+ }
159
+ catch (_d) {
160
+ // localStorage may be full or unavailable
161
+ }
65
162
  }
66
163
  }
67
- const SocialLoginBase = rawSocialLogin;
68
- const SocialLogin = new SocialLoginClient();
69
-
70
- /******************************************************************************
71
- Copyright (c) Microsoft Corporation.
72
-
73
- Permission to use, copy, modify, and/or distribute this software for any
74
- purpose with or without fee is hereby granted.
75
-
76
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
77
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
78
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
79
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
80
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
81
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
82
- PERFORMANCE OF THIS SOFTWARE.
83
- ***************************************************************************** */
84
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
85
-
86
-
87
- function __rest(s, e) {
88
- var t = {};
89
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
90
- t[p] = s[p];
91
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
92
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
93
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
94
- t[p[i]] = s[p[i]];
95
- }
96
- return t;
164
+ /**
165
+ * Listen for OAuth results from popup via postMessage, BroadcastChannel, and localStorage.
166
+ * Returns a cleanup function.
167
+ */
168
+ function listenForOAuthResult(provider, nonceOrState, handlers) {
169
+ const resultKey = getOAuthResultKey(nonceOrState);
170
+ const channelName = getBroadcastChannelName(provider, nonceOrState);
171
+ let broadcastChannel = null;
172
+ try {
173
+ broadcastChannel = new BroadcastChannel(channelName);
174
+ }
175
+ catch (_a) {
176
+ // BroadcastChannel not supported
177
+ }
178
+ const processData = (data) => {
179
+ if ((data === null || data === void 0 ? void 0 : data.source) && String(data.source).startsWith('angular'))
180
+ return false;
181
+ if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
182
+ handlers.onResponse(data);
183
+ return true;
184
+ }
185
+ if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
186
+ handlers.onError(data.error || 'User cancelled the OAuth flow', data.code);
187
+ return true;
188
+ }
189
+ return false;
190
+ };
191
+ const handleMessage = (event) => {
192
+ if (event.origin !== window.location.origin)
193
+ return;
194
+ processData(event.data);
195
+ };
196
+ const handleStorage = (event) => {
197
+ if (event.key !== resultKey || !event.newValue)
198
+ return;
199
+ try {
200
+ const data = JSON.parse(event.newValue);
201
+ localStorage.removeItem(resultKey);
202
+ processData(data);
203
+ }
204
+ catch (_a) {
205
+ // ignore parse errors
206
+ }
207
+ };
208
+ const handleBroadcast = (event) => {
209
+ processData(event.data);
210
+ };
211
+ window.addEventListener('message', handleMessage);
212
+ window.addEventListener('storage', handleStorage);
213
+ if (broadcastChannel) {
214
+ broadcastChannel.onmessage = handleBroadcast;
215
+ }
216
+ // Poll localStorage as fallback when storage event is missed (e.g. same-window writes)
217
+ const pollInterval = window.setInterval(() => {
218
+ try {
219
+ const raw = localStorage.getItem(resultKey);
220
+ if (!raw)
221
+ return;
222
+ localStorage.removeItem(resultKey);
223
+ const data = JSON.parse(raw);
224
+ processData(data);
225
+ }
226
+ catch (_a) {
227
+ // ignore
228
+ }
229
+ }, 300);
230
+ return () => {
231
+ window.removeEventListener('message', handleMessage);
232
+ window.removeEventListener('storage', handleStorage);
233
+ clearInterval(pollInterval);
234
+ if (broadcastChannel) {
235
+ broadcastChannel.close();
236
+ }
237
+ try {
238
+ localStorage.removeItem(resultKey);
239
+ }
240
+ catch (_a) {
241
+ // ignore
242
+ }
243
+ };
97
244
  }
98
245
 
99
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
100
- var e = new Error(message);
101
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
102
- };
103
-
104
- const AUTH_CONNECT_PROVIDERS = ['auth0', 'azure', 'cognito', 'okta', 'onelogin'];
105
- const DEFAULT_SCOPES = {
106
- auth0: 'openid profile email offline_access',
107
- azure: 'openid profile email',
108
- cognito: 'openid profile email',
109
- okta: 'openid profile email offline_access',
110
- onelogin: 'openid profile email',
111
- };
112
- const DEFAULT_RESOURCE_URLS = {
113
- azure: 'https://graph.microsoft.com/v1.0/me',
114
- };
115
- const DEFAULT_AUTHORITY_HOST = 'https://login.microsoftonline.com';
116
- const ensureProtocol = (value) => {
117
- if (value.startsWith('http://') || value.startsWith('https://')) {
118
- return value;
119
- }
120
- return `https://${value}`;
121
- };
122
- const trimTrailingSlash = (value) => value.replace(/\/+$/, '');
123
- const joinUrl = (base, path) => {
124
- const sanitizedBase = trimTrailingSlash(base);
125
- const sanitizedPath = path.replace(/^\/+/, '');
126
- return `${sanitizedBase}/${sanitizedPath}`;
127
- };
128
- const mergeRecords = (base, overrides) => {
129
- if (!base && !overrides) {
130
- return undefined;
131
- }
132
- return Object.assign(Object.assign({}, (base !== null && base !== void 0 ? base : {})), (overrides !== null && overrides !== void 0 ? overrides : {}));
133
- };
134
- const validatePreset = (providerId, preset) => {
135
- if (!preset.clientId) {
136
- throw new Error(`[authConnect] ${providerId} requires clientId.`);
137
- }
138
- if (!preset.redirectUrl) {
139
- throw new Error(`[authConnect] ${providerId} requires redirectUrl.`);
246
+ const GOOGLE_OFFLINE_REFRESH_MESSAGE$1 = "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.";
247
+ class GoogleSocialLogin extends BaseSocialLogin {
248
+ constructor() {
249
+ super(...arguments);
250
+ this.clientId = null;
251
+ this.loginType = 'online';
252
+ this.GOOGLE_TOKEN_REQUEST_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
253
+ this.GOOGLE_STATE_KEY = 'capgo_social_login_google_state';
140
254
  }
141
- };
142
- const buildAuth0Config = (preset) => {
143
- validatePreset('auth0', preset);
144
- if (!preset.domain) {
145
- throw new Error('[authConnect] auth0 requires domain.');
255
+ async initialize(clientId, mode, hostedDomain, redirectUrl) {
256
+ this.clientId = clientId;
257
+ if (mode) {
258
+ this.loginType = mode;
259
+ }
260
+ this.hostedDomain = hostedDomain;
261
+ this.redirectUrl = redirectUrl;
146
262
  }
147
- const base = trimTrailingSlash(ensureProtocol(preset.domain));
148
- return buildConfigFromPreset('auth0', preset, {
149
- authorizationBaseUrl: joinUrl(base, 'authorize'),
150
- accessTokenEndpoint: joinUrl(base, 'oauth/token'),
151
- resourceUrl: joinUrl(base, 'userinfo'),
152
- logoutUrl: joinUrl(base, 'v2/logout'),
153
- additionalParameters: preset.audience ? { audience: preset.audience } : undefined,
154
- });
155
- };
156
- const buildAzureConfig = (preset) => {
157
- var _a, _b;
158
- validatePreset('azure', preset);
159
- const tenantId = (_a = preset.tenantId) !== null && _a !== void 0 ? _a : 'common';
160
- const authorityHost = trimTrailingSlash(ensureProtocol((_b = preset.authorityHost) !== null && _b !== void 0 ? _b : DEFAULT_AUTHORITY_HOST));
161
- const base = joinUrl(authorityHost, `${tenantId}/oauth2/v2.0`);
162
- return buildConfigFromPreset('azure', preset, {
163
- authorizationBaseUrl: joinUrl(base, 'authorize'),
164
- accessTokenEndpoint: joinUrl(base, 'token'),
165
- resourceUrl: DEFAULT_RESOURCE_URLS.azure,
166
- });
167
- };
168
- const buildCognitoConfig = (preset) => {
169
- validatePreset('cognito', preset);
170
- if (!preset.domain) {
171
- throw new Error('[authConnect] cognito requires domain.');
172
- }
173
- const base = trimTrailingSlash(ensureProtocol(preset.domain));
174
- return buildConfigFromPreset('cognito', preset, {
175
- authorizationBaseUrl: joinUrl(base, 'oauth2/authorize'),
176
- accessTokenEndpoint: joinUrl(base, 'oauth2/token'),
177
- resourceUrl: joinUrl(base, 'oauth2/userInfo'),
178
- logoutUrl: joinUrl(base, 'logout'),
179
- });
180
- };
181
- const buildOktaConfig = (preset) => {
182
- validatePreset('okta', preset);
183
- if (!preset.issuer) {
184
- throw new Error('[authConnect] okta requires issuer.');
185
- }
186
- const base = trimTrailingSlash(ensureProtocol(preset.issuer));
187
- return buildConfigFromPreset('okta', preset, {
188
- authorizationBaseUrl: joinUrl(base, 'v1/authorize'),
189
- accessTokenEndpoint: joinUrl(base, 'v1/token'),
190
- resourceUrl: joinUrl(base, 'v1/userinfo'),
191
- logoutUrl: joinUrl(base, 'v1/logout'),
192
- });
193
- };
194
- const buildOneLoginConfig = (preset) => {
195
- validatePreset('onelogin', preset);
196
- if (!preset.issuer) {
197
- throw new Error('[authConnect] onelogin requires issuer.');
198
- }
199
- const base = trimTrailingSlash(ensureProtocol(preset.issuer));
200
- return buildConfigFromPreset('onelogin', preset, {
201
- authorizationBaseUrl: joinUrl(base, 'auth'),
202
- accessTokenEndpoint: joinUrl(base, 'token'),
203
- resourceUrl: joinUrl(base, 'me'),
204
- logoutUrl: joinUrl(base, 'logout'),
205
- });
206
- };
207
- const buildConfigFromPreset = (providerId, preset, defaults) => {
208
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
209
- const additionalParameters = mergeRecords(defaults.additionalParameters, preset.additionalParameters);
210
- const additionalResourceHeaders = mergeRecords(defaults.additionalResourceHeaders, preset.additionalResourceHeaders);
211
- const config = {
212
- appId: preset.clientId,
213
- authorizationBaseUrl: (_b = (_a = preset.authorizationBaseUrl) !== null && _a !== void 0 ? _a : defaults.authorizationBaseUrl) !== null && _b !== void 0 ? _b : '',
214
- accessTokenEndpoint: (_c = preset.accessTokenEndpoint) !== null && _c !== void 0 ? _c : defaults.accessTokenEndpoint,
215
- redirectUrl: preset.redirectUrl,
216
- resourceUrl: (_d = preset.resourceUrl) !== null && _d !== void 0 ? _d : defaults.resourceUrl,
217
- responseType: (_f = (_e = preset.responseType) !== null && _e !== void 0 ? _e : defaults.responseType) !== null && _f !== void 0 ? _f : 'code',
218
- pkceEnabled: (_h = (_g = preset.pkceEnabled) !== null && _g !== void 0 ? _g : defaults.pkceEnabled) !== null && _h !== void 0 ? _h : true,
219
- scope: (_k = (_j = preset.scope) !== null && _j !== void 0 ? _j : defaults.scope) !== null && _k !== void 0 ? _k : DEFAULT_SCOPES[providerId],
220
- additionalParameters,
221
- additionalResourceHeaders,
222
- logoutUrl: (_l = preset.logoutUrl) !== null && _l !== void 0 ? _l : defaults.logoutUrl,
223
- logsEnabled: (_m = preset.logsEnabled) !== null && _m !== void 0 ? _m : defaults.logsEnabled,
224
- };
225
- if (!config.authorizationBaseUrl) {
226
- throw new Error(`[authConnect] ${providerId} authorizationBaseUrl is required.`);
227
- }
228
- return config;
229
- };
230
- const buildAuthConnectProviders = (presets) => {
231
- if (!presets) {
232
- return {};
233
- }
234
- const providers = {};
235
- if (presets.auth0) {
236
- providers.auth0 = buildAuth0Config(presets.auth0);
237
- }
238
- if (presets.azure) {
239
- providers.azure = buildAzureConfig(presets.azure);
240
- }
241
- if (presets.cognito) {
242
- providers.cognito = buildCognitoConfig(presets.cognito);
243
- }
244
- if (presets.okta) {
245
- providers.okta = buildOktaConfig(presets.okta);
246
- }
247
- if (presets.onelogin) {
248
- providers.onelogin = buildOneLoginConfig(presets.onelogin);
249
- }
250
- return providers;
251
- };
252
- const isAuthConnectProvider = (provider) => AUTH_CONNECT_PROVIDERS.includes(provider);
253
- const isAuthConnectProviderOptions = (options) => isAuthConnectProvider(options.provider);
254
- const isAuthConnectLoginOptions = (options) => isAuthConnectProvider(options.provider);
255
- const mapLoginOptions = (options) => {
256
- var _a;
257
- if (isAuthConnectLoginOptions(options)) {
258
- return {
259
- provider: 'oauth2',
260
- options: Object.assign({ providerId: options.provider }, ((_a = options.options) !== null && _a !== void 0 ? _a : {})),
261
- };
262
- }
263
- return options;
264
- };
265
- const mapProviderOptions = (options) => {
266
- if (isAuthConnectProviderOptions(options)) {
267
- return {
268
- provider: 'oauth2',
269
- providerId: options.provider,
270
- };
271
- }
272
- return options;
273
- };
274
- const mapRefreshOptions = (options) => mapLoginOptions(options);
275
- const mergeOAuth2Configs = (presets, oauth2) => {
276
- if (!Object.keys(presets).length && !oauth2) {
277
- return oauth2;
278
- }
279
- return Object.assign(Object.assign({}, presets), (oauth2 !== null && oauth2 !== void 0 ? oauth2 : {}));
280
- };
281
- const createAuthConnectClient = (client) => ({
282
- initialize: async (options) => {
283
- const { authConnect, oauth2 } = options, rest = __rest(options, ["authConnect", "oauth2"]);
284
- const presetProviders = buildAuthConnectProviders(authConnect);
285
- const mergedOauth2 = mergeOAuth2Configs(presetProviders, oauth2);
286
- const payload = Object.assign(Object.assign({}, rest), (mergedOauth2 ? { oauth2: mergedOauth2 } : {}));
287
- return client.initialize(payload);
288
- },
289
- login: async (options) => {
290
- if (isAuthConnectProvider(options.provider)) {
291
- const mapped = mapLoginOptions(options);
292
- const response = await client.login(mapped);
293
- return {
294
- provider: options.provider,
295
- result: response.result,
296
- };
297
- }
298
- return client.login(options);
299
- },
300
- logout: async (options) => client.logout(mapProviderOptions(options)),
301
- isLoggedIn: async (options) => client.isLoggedIn(mapProviderOptions(options)),
302
- getAuthorizationCode: async (options) => client.getAuthorizationCode(mapProviderOptions(options)),
303
- refresh: async (options) => client.refresh(mapRefreshOptions(options)),
304
- providerSpecificCall: async (options) => client.providerSpecificCall(options),
305
- getPluginVersion: async () => client.getPluginVersion(),
306
- });
307
- const SocialLoginAuthConnect = createAuthConnectClient(SocialLoginBase);
308
-
309
- class BaseSocialLogin extends core.WebPlugin {
310
- constructor() {
311
- super();
312
- }
313
- parseJwt(token) {
314
- const base64Url = token.split('.')[1];
315
- const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
316
- const jsonPayload = decodeURIComponent(atob(base64)
317
- .split('')
318
- .map((c) => {
319
- return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
320
- })
321
- .join(''));
322
- return JSON.parse(jsonPayload);
323
- }
324
- async loadScript(src) {
325
- return new Promise((resolve, reject) => {
326
- const script = document.createElement('script');
327
- script.src = src;
328
- script.async = true;
329
- script.onload = () => {
330
- resolve();
331
- };
332
- script.onerror = reject;
333
- document.body.appendChild(script);
334
- });
335
- }
336
- }
337
- BaseSocialLogin.OAUTH_STATE_KEY = 'social_login_oauth_pending';
338
-
339
- const USER_CANCELLED_CODE = 'USER_CANCELLED';
340
- const CANCELLED_PATTERNS = [
341
- 'access_denied',
342
- 'access denied',
343
- 'user_cancelled_authorize',
344
- 'user_cancelled',
345
- 'user cancelled',
346
- 'user canceled',
347
- 'login cancelled',
348
- 'login canceled',
349
- 'popup closed',
350
- 'window was closed',
351
- ];
352
- function createUserCancelledError(message) {
353
- const error = new Error(message);
354
- error.code = USER_CANCELLED_CODE;
355
- return error;
356
- }
357
- /**
358
- * Detects cancellation-like messages and marks them with USER_CANCELLED.
359
- * Falls back to a regular Error when the message doesn't look like a user cancellation.
360
- */
361
- function inferUserCancelledError(message) {
362
- const normalized = message.toLowerCase();
363
- if (CANCELLED_PATTERNS.some((pattern) => normalized.includes(pattern))) {
364
- return createUserCancelledError(message);
365
- }
366
- return new Error(message);
367
- }
368
-
369
- class AppleSocialLogin extends BaseSocialLogin {
370
- constructor() {
371
- super(...arguments);
372
- this.clientId = null;
373
- this.redirectUrl = null;
374
- this.scriptLoaded = false;
375
- this.scriptUrl = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
376
- this.useProperTokenExchange = false;
377
- }
378
- async initialize(clientId, redirectUrl, useProperTokenExchange = false) {
379
- this.clientId = clientId;
380
- this.redirectUrl = redirectUrl || null;
381
- this.useProperTokenExchange = useProperTokenExchange;
382
- if (clientId) {
383
- await this.loadAppleScript();
384
- }
385
- }
386
- async login(options) {
387
- if (!this.clientId) {
388
- throw new Error('Apple Client ID not set. Call initialize() first.');
389
- }
390
- if (!this.scriptLoaded) {
391
- throw new Error('Apple Sign-In script not loaded.');
392
- }
393
- return new Promise((resolve, reject) => {
394
- var _a, _b;
395
- AppleID.auth.init({
396
- clientId: (_a = this.clientId) !== null && _a !== void 0 ? _a : '',
397
- scope: ((_b = options.scopes) === null || _b === void 0 ? void 0 : _b.join(' ')) || 'name email',
398
- redirectURI: this.redirectUrl || window.location.href,
399
- state: options.state,
400
- nonce: options.nonce,
401
- usePopup: true,
402
- });
403
- AppleID.auth
404
- .signIn()
405
- .then((res) => {
406
- var _a, _b, _c, _d, _e;
407
- let accessToken = null;
408
- if (this.useProperTokenExchange) {
409
- // When using proper token exchange, the authorization code should be exchanged
410
- // for a proper access token on the backend. For now, we set accessToken to null
411
- // and provide the authorization code in a separate field for backend processing.
412
- accessToken = null;
413
- }
414
- else {
415
- // Legacy behavior: use authorization code as access token for backward compatibility
416
- accessToken = {
417
- token: res.authorization.code || '',
418
- };
419
- }
420
- const result = Object.assign({ profile: {
421
- user: res.user || '',
422
- email: ((_a = res.user) === null || _a === void 0 ? void 0 : _a.email) || null,
423
- givenName: ((_c = (_b = res.user) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.firstName) || null,
424
- familyName: ((_e = (_d = res.user) === null || _d === void 0 ? void 0 : _d.name) === null || _e === void 0 ? void 0 : _e.lastName) || null,
425
- }, accessToken: accessToken, idToken: res.authorization.id_token || null }, (this.useProperTokenExchange && { authorizationCode: res.authorization.code }));
426
- resolve({ provider: 'apple', result });
427
- })
428
- .catch((error) => {
429
- var _a, _b, _c;
430
- const message = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.localizedDescription) !== null && _b !== void 0 ? _b : error === null || error === void 0 ? void 0 : error.error) !== null && _c !== void 0 ? _c : 'Apple login failed';
431
- reject(inferUserCancelledError(message));
432
- });
433
- });
434
- }
435
- async logout() {
436
- // Apple doesn't provide a logout method for web
437
- console.log('Apple logout: Session should be managed on the client side');
438
- }
439
- async isLoggedIn() {
440
- // Apple doesn't provide a method to check login status on web
441
- console.log('Apple login status should be managed on the client side');
442
- return { isLoggedIn: false };
443
- }
444
- async getAuthorizationCode() {
445
- // Apple authorization code should be obtained during login
446
- console.log('Apple authorization code should be stored during login');
447
- throw new Error('Apple authorization code not available');
448
- }
449
- async refresh() {
450
- // Apple doesn't provide a refresh method for web
451
- console.log('Apple refresh not available on web');
452
- }
453
- async loadAppleScript() {
454
- if (this.scriptLoaded)
455
- return;
456
- return this.loadScript(this.scriptUrl).then(() => {
457
- this.scriptLoaded = true;
458
- });
459
- }
460
- }
461
-
462
- class FacebookSocialLogin extends BaseSocialLogin {
463
- constructor() {
464
- super(...arguments);
465
- this.appId = null;
466
- this.scriptLoaded = false;
467
- this.locale = 'en_US';
468
- }
469
- async initialize(appId, locale) {
470
- this.appId = appId;
471
- if (locale) {
472
- this.locale = locale;
473
- }
474
- if (appId) {
475
- // Load with the specified locale or default
476
- await this.loadFacebookScript(this.locale);
477
- FB.init({
478
- appId: this.appId,
479
- version: 'v17.0',
480
- xfbml: true,
481
- cookie: true,
482
- });
483
- }
484
- }
485
- async login(options) {
486
- if (!this.appId) {
487
- throw new Error('Facebook App ID not set. Call initialize() first.');
488
- }
489
- return new Promise((resolve, reject) => {
490
- var _a;
491
- let settled = false;
492
- let waitingForStatus = false;
493
- const resolveWithProfile = (authResponse) => {
494
- if (settled)
495
- return;
496
- if (!(authResponse === null || authResponse === void 0 ? void 0 : authResponse.accessToken) || !authResponse.userID) {
497
- settled = true;
498
- reject(new Error('Facebook login failed'));
499
- return;
500
- }
501
- const accessToken = authResponse.accessToken;
502
- const userId = authResponse.userID;
503
- FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo) => {
504
- var _a, _b;
505
- settled = true;
506
- const result = {
507
- accessToken: {
508
- token: accessToken,
509
- userId,
510
- },
511
- profile: {
512
- userID: userInfo.id,
513
- name: userInfo.name,
514
- email: userInfo.email || null,
515
- imageURL: ((_b = (_a = userInfo.picture) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.url) || null,
516
- friendIDs: [],
517
- birthday: null,
518
- ageRange: null,
519
- gender: null,
520
- location: null,
521
- hometown: null,
522
- profileURL: null,
523
- },
524
- idToken: null,
525
- };
526
- resolve({ provider: 'facebook', result });
527
- });
528
- };
529
- const waitForConnected = () => {
530
- if (settled || waitingForStatus)
531
- return;
532
- waitingForStatus = true;
533
- this.waitForConnection()
534
- .then((statusResponse) => resolveWithProfile(statusResponse.authResponse))
535
- .catch((error) => {
536
- if (settled)
537
- return;
538
- settled = true;
539
- reject(error);
540
- });
541
- };
542
- FB.login((response) => {
543
- if (response.status === 'connected') {
544
- resolveWithProfile(response.authResponse);
545
- }
546
- else if (response.status === 'not_authorized' || response.status === 'unknown') {
547
- reject(createUserCancelledError('Facebook login was cancelled.'));
548
- }
549
- else {
550
- waitForConnected();
551
- }
552
- }, ((_a = options.permissions) === null || _a === void 0 ? void 0 : _a.length) ? { scope: options.permissions.join(',') } : undefined);
263
+ async login(options) {
264
+ if (!this.clientId) {
265
+ throw new Error('Google Client ID not set. Call initialize() first.');
266
+ }
267
+ let scopes = options.scopes || [];
268
+ if (scopes.length > 0) {
269
+ // If scopes are provided, directly use the traditional OAuth flow
270
+ if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {
271
+ scopes.push('https://www.googleapis.com/auth/userinfo.email');
272
+ }
273
+ if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {
274
+ scopes.push('https://www.googleapis.com/auth/userinfo.profile');
275
+ }
276
+ if (!scopes.includes('openid')) {
277
+ scopes.push('openid');
278
+ }
279
+ }
280
+ else {
281
+ scopes = [
282
+ 'https://www.googleapis.com/auth/userinfo.email',
283
+ 'https://www.googleapis.com/auth/userinfo.profile',
284
+ 'openid',
285
+ ];
286
+ }
287
+ const nonce = options.nonce || Math.random().toString(36).substring(2);
288
+ // If scopes are provided, directly use the traditional OAuth flow
289
+ return this.traditionalOAuth({
290
+ scopes,
291
+ nonce,
292
+ hostedDomain: this.hostedDomain,
293
+ prompt: options.prompt,
553
294
  });
554
295
  }
555
296
  async logout() {
556
- return new Promise((resolve) => {
557
- FB.logout(() => resolve());
558
- });
297
+ if (this.loginType === 'offline') {
298
+ return Promise.reject("Offline login doesn't store tokens. logout is not available");
299
+ }
300
+ // eslint-disable-next-line
301
+ const state = this.getGoogleState();
302
+ if (!state)
303
+ return;
304
+ await this.rawLogoutGoogle(state.accessToken);
559
305
  }
560
306
  async isLoggedIn() {
561
- return new Promise((resolve) => {
562
- FB.getLoginStatus((response) => {
563
- resolve({ isLoggedIn: response.status === 'connected' });
564
- });
565
- });
307
+ if (this.loginType === 'offline') {
308
+ return Promise.reject("Offline login doesn't store tokens. isLoggedIn is not available");
309
+ }
310
+ // eslint-disable-next-line
311
+ const state = this.getGoogleState();
312
+ if (!state)
313
+ return { isLoggedIn: false };
314
+ try {
315
+ const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
316
+ const isValidIdToken = this.idTokenValid(state.idToken);
317
+ if (isValidAccessToken && isValidIdToken) {
318
+ return { isLoggedIn: true };
319
+ }
320
+ else {
321
+ try {
322
+ await this.rawLogoutGoogle(state.accessToken, false);
323
+ }
324
+ catch (e) {
325
+ console.error('Access token is not valid, but cannot logout', e);
326
+ }
327
+ return { isLoggedIn: false };
328
+ }
329
+ }
330
+ catch (e) {
331
+ return Promise.reject(e);
332
+ }
566
333
  }
567
334
  async getAuthorizationCode() {
568
- return new Promise((resolve, reject) => {
569
- FB.getLoginStatus((response) => {
570
- var _a;
571
- if (response.status === 'connected') {
572
- resolve({ accessToken: ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken) || '' });
335
+ if (this.loginType === 'offline') {
336
+ return Promise.reject("Offline login doesn't store tokens. getAuthorizationCode is not available");
337
+ }
338
+ // eslint-disable-next-line
339
+ const state = this.getGoogleState();
340
+ if (!state)
341
+ throw new Error('No Google authorization code available');
342
+ try {
343
+ const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
344
+ const isValidIdToken = this.idTokenValid(state.idToken);
345
+ if (isValidAccessToken && isValidIdToken) {
346
+ return { accessToken: state.accessToken, jwt: state.idToken };
347
+ }
348
+ else {
349
+ try {
350
+ await this.rawLogoutGoogle(state.accessToken, false);
573
351
  }
574
- else {
575
- reject(new Error('No Facebook authorization code available'));
352
+ catch (e) {
353
+ console.error('Access token is not valid, but cannot logout', e);
576
354
  }
577
- });
578
- });
355
+ throw new Error('No Google authorization code available');
356
+ }
357
+ }
358
+ catch (e) {
359
+ return Promise.reject(e);
360
+ }
579
361
  }
580
- async refresh(options) {
581
- await this.login(options);
362
+ async refresh() {
363
+ if (this.loginType === 'offline') {
364
+ console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE$1}`);
365
+ return Promise.reject(new Error(GOOGLE_OFFLINE_REFRESH_MESSAGE$1));
366
+ }
367
+ return Promise.reject(new Error('Google refresh is not implemented on web. Use login() again to obtain a new token.'));
582
368
  }
583
- waitForConnection(timeoutMs = 120000, pollIntervalMs = 500) {
584
- const start = Date.now();
585
- return new Promise((resolve, reject) => {
586
- let finished = false;
587
- const pollStatus = () => {
588
- if (finished)
589
- return;
590
- FB.getLoginStatus((response) => {
591
- var _a;
592
- if (finished)
593
- return;
594
- if (response.status === 'connected' && ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken)) {
595
- finished = true;
596
- resolve(response);
597
- return;
598
- }
599
- if (response.status === 'not_authorized' || response.status === 'unknown') {
600
- finished = true;
601
- reject(createUserCancelledError('Facebook login was cancelled.'));
602
- return;
603
- }
604
- if (Date.now() - start >= timeoutMs) {
605
- finished = true;
606
- reject(new Error('Facebook login failed or timed out'));
607
- return;
608
- }
609
- setTimeout(pollStatus, pollIntervalMs);
610
- });
369
+ handleOAuthRedirect(url) {
370
+ const paramsRaw = url.searchParams;
371
+ // Check for errors in search params first (for offline mode)
372
+ const errorInParams = paramsRaw.get('error');
373
+ if (errorInParams) {
374
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
375
+ const errorDescription = paramsRaw.get('error_description') || errorInParams;
376
+ return { error: errorDescription };
377
+ }
378
+ const code = paramsRaw.get('code');
379
+ if (code && paramsRaw.has('scope')) {
380
+ return {
381
+ provider: 'google',
382
+ result: {
383
+ serverAuthCode: code,
384
+ responseType: 'offline',
385
+ },
611
386
  };
612
- pollStatus();
613
- });
387
+ }
388
+ const hash = url.hash.substring(1);
389
+ if (!hash)
390
+ return null;
391
+ const params = new URLSearchParams(hash);
392
+ // Check for error cases in hash (e.g., user cancelled)
393
+ const error = params.get('error');
394
+ if (error) {
395
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
396
+ const errorDescription = params.get('error_description') || error;
397
+ return { error: errorDescription };
398
+ }
399
+ const accessToken = params.get('access_token');
400
+ const idToken = params.get('id_token');
401
+ if (accessToken && idToken) {
402
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
403
+ const profile = this.parseJwt(idToken);
404
+ return {
405
+ provider: 'google',
406
+ result: {
407
+ accessToken: {
408
+ token: accessToken,
409
+ },
410
+ idToken,
411
+ profile: {
412
+ email: profile.email || null,
413
+ familyName: profile.family_name || null,
414
+ givenName: profile.given_name || null,
415
+ id: profile.sub || null,
416
+ name: profile.name || null,
417
+ imageUrl: profile.picture || null,
418
+ },
419
+ responseType: 'online',
420
+ },
421
+ };
422
+ }
423
+ return null;
614
424
  }
615
- async loadFacebookScript(locale) {
616
- if (this.scriptLoaded)
617
- return;
618
- // Remove any existing Facebook SDK script
619
- const existingScript = document.querySelector('script[src*="connect.facebook.net"]');
620
- if (existingScript) {
621
- existingScript.remove();
425
+ async accessTokenIsValid(accessToken) {
426
+ const url = `${this.GOOGLE_TOKEN_REQUEST_URL}?access_token=${encodeURIComponent(accessToken)}`;
427
+ try {
428
+ // Make the GET request using fetch
429
+ const response = await fetch(url);
430
+ // Check if the response is successful
431
+ if (!response.ok) {
432
+ console.log(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response not successful. Status code: ${response.status}. Assuming that the token is not valid`);
433
+ return false;
434
+ }
435
+ // Get the response body as text
436
+ const responseBody = await response.text();
437
+ if (!responseBody) {
438
+ console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);
439
+ throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);
440
+ }
441
+ // Parse the response body as JSON
442
+ let jsonObject;
443
+ try {
444
+ jsonObject = JSON.parse(responseBody);
445
+ }
446
+ catch (e) {
447
+ console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`);
448
+ throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`);
449
+ }
450
+ // Extract the 'expires_in' field
451
+ const expiresInStr = jsonObject['expires_in'];
452
+ if (expiresInStr === undefined || expiresInStr === null) {
453
+ console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`);
454
+ throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`);
455
+ }
456
+ // Parse 'expires_in' as an integer
457
+ let expiresInInt;
458
+ try {
459
+ expiresInInt = parseInt(expiresInStr, 10);
460
+ if (isNaN(expiresInInt)) {
461
+ throw new Error(`'expires_in' is not a valid integer`);
462
+ }
463
+ }
464
+ catch (e) {
465
+ console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`);
466
+ throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`);
467
+ }
468
+ // Determine if the access token is valid based on 'expires_in'
469
+ return expiresInInt > 5;
470
+ }
471
+ catch (error) {
472
+ console.error(error);
473
+ throw error;
622
474
  }
623
- return this.loadScript(`https://connect.facebook.net/${locale}/sdk.js`).then(() => {
624
- this.scriptLoaded = true;
625
- });
626
- }
627
- }
628
-
629
- const GOOGLE_OFFLINE_REFRESH_MESSAGE = "Google refresh() is not available when using offline mode. Offline mode only returns serverAuthCode for backend token exchange. Send serverAuthCode to your backend and refresh tokens there, or switch google.mode to 'online' for client-side refresh.";
630
- class GoogleSocialLogin extends BaseSocialLogin {
631
- constructor() {
632
- super(...arguments);
633
- this.clientId = null;
634
- this.loginType = 'online';
635
- this.GOOGLE_TOKEN_REQUEST_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
636
- this.GOOGLE_STATE_KEY = 'capgo_social_login_google_state';
637
475
  }
638
- async initialize(clientId, mode, hostedDomain, redirectUrl) {
639
- this.clientId = clientId;
640
- if (mode) {
641
- this.loginType = mode;
476
+ idTokenValid(idToken) {
477
+ try {
478
+ const parsed = this.parseJwt(idToken);
479
+ const currentTime = Math.ceil(Date.now() / 1000) + 5; // Convert current time to seconds since epoch
480
+ return parsed.exp && currentTime < parsed.exp;
481
+ }
482
+ catch (e) {
483
+ return false;
642
484
  }
643
- this.hostedDomain = hostedDomain;
644
- this.redirectUrl = redirectUrl;
645
485
  }
646
- async login(options) {
647
- if (!this.clientId) {
648
- throw new Error('Google Client ID not set. Call initialize() first.');
486
+ async rawLogoutGoogle(accessToken, tokenValid = null) {
487
+ if (tokenValid === null) {
488
+ tokenValid = await this.accessTokenIsValid(accessToken);
649
489
  }
650
- let scopes = options.scopes || [];
651
- if (scopes.length > 0) {
652
- // If scopes are provided, directly use the traditional OAuth flow
653
- if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {
654
- scopes.push('https://www.googleapis.com/auth/userinfo.email');
655
- }
656
- if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {
657
- scopes.push('https://www.googleapis.com/auth/userinfo.profile');
490
+ if (tokenValid === true) {
491
+ try {
492
+ await fetch(`https://accounts.google.com/o/oauth2/revoke?token=${encodeURIComponent(accessToken)}`);
493
+ this.clearStateGoogle();
658
494
  }
659
- if (!scopes.includes('openid')) {
660
- scopes.push('openid');
495
+ catch (e) {
496
+ // ignore
661
497
  }
498
+ return;
662
499
  }
663
500
  else {
664
- scopes = [
665
- 'https://www.googleapis.com/auth/userinfo.email',
666
- 'https://www.googleapis.com/auth/userinfo.profile',
667
- 'openid',
668
- ];
501
+ this.clearStateGoogle();
502
+ return;
669
503
  }
670
- const nonce = options.nonce || Math.random().toString(36).substring(2);
671
- // If scopes are provided, directly use the traditional OAuth flow
672
- return this.traditionalOAuth({
673
- scopes,
674
- nonce,
675
- hostedDomain: this.hostedDomain,
676
- prompt: options.prompt,
677
- });
678
504
  }
679
- async logout() {
680
- if (this.loginType === 'offline') {
681
- return Promise.reject("Offline login doesn't store tokens. logout is not available");
505
+ persistStateGoogle(accessToken, idToken) {
506
+ try {
507
+ window.localStorage.setItem(this.GOOGLE_STATE_KEY, JSON.stringify({ accessToken, idToken }));
508
+ }
509
+ catch (e) {
510
+ console.error('Cannot persist state google', e);
682
511
  }
683
- // eslint-disable-next-line
684
- const state = this.getGoogleState();
685
- if (!state)
686
- return;
687
- await this.rawLogoutGoogle(state.accessToken);
688
512
  }
689
- async isLoggedIn() {
690
- if (this.loginType === 'offline') {
691
- return Promise.reject("Offline login doesn't store tokens. isLoggedIn is not available");
513
+ clearStateGoogle() {
514
+ try {
515
+ window.localStorage.removeItem(this.GOOGLE_STATE_KEY);
692
516
  }
693
- // eslint-disable-next-line
694
- const state = this.getGoogleState();
695
- if (!state)
696
- return { isLoggedIn: false };
517
+ catch (e) {
518
+ console.error('Cannot clear state google', e);
519
+ }
520
+ }
521
+ getGoogleState() {
697
522
  try {
698
- const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
699
- const isValidIdToken = this.idTokenValid(state.idToken);
700
- if (isValidAccessToken && isValidIdToken) {
701
- return { isLoggedIn: true };
523
+ const state = window.localStorage.getItem(this.GOOGLE_STATE_KEY);
524
+ if (!state)
525
+ return null;
526
+ const { accessToken, idToken } = JSON.parse(state);
527
+ return { accessToken, idToken };
528
+ }
529
+ catch (e) {
530
+ console.error('Cannot get state google', e);
531
+ return null;
532
+ }
533
+ }
534
+ async traditionalOAuth({ scopes, hostedDomain, nonce, prompt, }) {
535
+ var _a;
536
+ const uniqueScopes = [...new Set([...(scopes || []), 'openid'])];
537
+ const params = new URLSearchParams(Object.assign(Object.assign({ client_id: (_a = this.clientId) !== null && _a !== void 0 ? _a : '', redirect_uri: this.redirectUrl || window.location.origin + window.location.pathname, response_type: this.loginType === 'offline' ? 'code' : 'token id_token', scope: uniqueScopes.join(' ') }, (nonce && { nonce })), { include_granted_scopes: 'true', state: 'popup' }));
538
+ if (hostedDomain !== undefined) {
539
+ params.append('hd', hostedDomain);
540
+ }
541
+ if (prompt !== undefined) {
542
+ params.append('prompt', prompt);
543
+ }
544
+ const url = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
545
+ const width = 500;
546
+ const height = 600;
547
+ const left = window.screenX + (window.outerWidth - width) / 2;
548
+ const top = window.screenY + (window.outerHeight - height) / 2;
549
+ localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'google', loginType: this.loginType, nonce }));
550
+ markOAuthPopup(nonce);
551
+ const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);
552
+ let popupClosedInterval;
553
+ let timeoutHandle;
554
+ let removeOAuthListener = null;
555
+ // This may never return...
556
+ return new Promise((resolve, reject) => {
557
+ if (!popup) {
558
+ reject(new Error('Failed to open popup'));
559
+ return;
702
560
  }
703
- else {
561
+ let settled = false;
562
+ let coopErrorDetected = false;
563
+ const cleanup = (shouldClose = false) => {
564
+ clearInterval(popupClosedInterval);
565
+ clearTimeout(timeoutHandle);
566
+ if (removeOAuthListener) {
567
+ removeOAuthListener();
568
+ removeOAuthListener = null;
569
+ }
570
+ if (shouldClose) {
571
+ try {
572
+ popup.close();
573
+ }
574
+ catch (_a) {
575
+ // Ignore cross-origin errors when closing the popup
576
+ }
577
+ }
578
+ };
579
+ const settle = (shouldClose, action) => {
580
+ if (settled)
581
+ return;
582
+ settled = true;
583
+ cleanup(shouldClose);
584
+ action();
585
+ };
586
+ const processOAuthResponse = (data) => {
587
+ if (this.loginType === 'online') {
588
+ const { accessToken, idToken } = data;
589
+ if (accessToken && idToken) {
590
+ const profile = this.parseJwt(idToken);
591
+ this.persistStateGoogle(accessToken.token, idToken);
592
+ settle(true, () => {
593
+ resolve({
594
+ provider: 'google',
595
+ result: {
596
+ accessToken: {
597
+ token: accessToken.token,
598
+ },
599
+ idToken,
600
+ profile: {
601
+ email: profile.email || null,
602
+ familyName: profile.family_name || null,
603
+ givenName: profile.given_name || null,
604
+ id: profile.sub || null,
605
+ name: profile.name || null,
606
+ imageUrl: profile.picture || null,
607
+ },
608
+ responseType: 'online',
609
+ },
610
+ });
611
+ });
612
+ }
613
+ else {
614
+ settle(true, () => {
615
+ reject(new Error('Invalid OAuth response: missing accessToken or idToken'));
616
+ });
617
+ }
618
+ }
619
+ else {
620
+ const { serverAuthCode } = data;
621
+ if (!serverAuthCode) {
622
+ settle(true, () => {
623
+ reject(new Error('Invalid OAuth response: missing serverAuthCode'));
624
+ });
625
+ return;
626
+ }
627
+ settle(true, () => {
628
+ resolve({
629
+ provider: 'google',
630
+ result: {
631
+ responseType: 'offline',
632
+ serverAuthCode,
633
+ },
634
+ });
635
+ });
636
+ }
637
+ };
638
+ // COOP-safe listener: postMessage + BroadcastChannel + localStorage storage events
639
+ removeOAuthListener = listenForOAuthResult('google', nonce, {
640
+ onResponse: processOAuthResponse,
641
+ onError: (errorMessage) => {
642
+ settle(true, () => {
643
+ reject(inferUserCancelledError(errorMessage));
644
+ });
645
+ },
646
+ });
647
+ // Timeout after 5 minutes
648
+ timeoutHandle = setTimeout(() => {
649
+ settle(true, () => {
650
+ reject(new Error('OAuth timeout'));
651
+ });
652
+ }, 300000);
653
+ popupClosedInterval = setInterval(() => {
654
+ if (coopErrorDetected)
655
+ return;
704
656
  try {
705
- await this.rawLogoutGoogle(state.accessToken, false);
657
+ if (popup.closed) {
658
+ settle(false, () => {
659
+ reject(createUserCancelledError('Popup closed'));
660
+ });
661
+ }
706
662
  }
707
- catch (e) {
708
- console.error('Access token is not valid, but cannot logout', e);
663
+ catch (_a) {
664
+ // COOP blocks popup.closed while on third-party origin — stop polling, rely on bridge
665
+ coopErrorDetected = true;
709
666
  }
710
- return { isLoggedIn: false };
711
- }
712
- }
713
- catch (e) {
714
- return Promise.reject(e);
715
- }
667
+ }, 1000);
668
+ });
669
+ }
670
+ }
671
+
672
+ /******************************************************************************
673
+ Copyright (c) Microsoft Corporation.
674
+
675
+ Permission to use, copy, modify, and/or distribute this software for any
676
+ purpose with or without fee is hereby granted.
677
+
678
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
679
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
680
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
681
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
682
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
683
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
684
+ PERFORMANCE OF THIS SOFTWARE.
685
+ ***************************************************************************** */
686
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
687
+
688
+
689
+ function __rest(s, e) {
690
+ var t = {};
691
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
692
+ t[p] = s[p];
693
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
694
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
695
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
696
+ t[p[i]] = s[p[i]];
697
+ }
698
+ return t;
699
+ }
700
+
701
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
702
+ var e = new Error(message);
703
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
704
+ };
705
+
706
+ /**
707
+ * OAuth2 Social Login Manager
708
+ * Supports multiple OAuth2 provider configurations
709
+ */
710
+ class OAuth2SocialLogin extends BaseSocialLogin {
711
+ constructor() {
712
+ super();
713
+ this.providers = new Map();
714
+ this.TOKENS_KEY_PREFIX = 'capgo_social_login_oauth2_tokens_';
715
+ this.STATE_PREFIX = 'capgo_social_login_oauth2_state_';
716
+ this.CONFIG_KEY_PREFIX = 'capgo_social_login_oauth2_config_';
717
+ // Restore configurations from localStorage for popup window context
718
+ this.restoreConfigurationsFromStorage();
716
719
  }
717
- async getAuthorizationCode() {
718
- if (this.loginType === 'offline') {
719
- return Promise.reject("Offline login doesn't store tokens. getAuthorizationCode is not available");
720
+ normalizeScopeValue(scope) {
721
+ if (!scope)
722
+ return '';
723
+ if (typeof scope === 'string')
724
+ return scope;
725
+ if (Array.isArray(scope))
726
+ return scope.filter(Boolean).join(' ');
727
+ return '';
728
+ }
729
+ normalizeConfig(providerId, config) {
730
+ var _a, _b, _c, _d, _e, _f, _g, _h;
731
+ const appId = (_a = config.appId) !== null && _a !== void 0 ? _a : config.clientId;
732
+ const authorizationBaseUrl = (_b = config.authorizationBaseUrl) !== null && _b !== void 0 ? _b : config.authorizationEndpoint;
733
+ const accessTokenEndpoint = (_c = config.accessTokenEndpoint) !== null && _c !== void 0 ? _c : config.tokenEndpoint;
734
+ const logoutUrl = (_d = config.logoutUrl) !== null && _d !== void 0 ? _d : config.endSessionEndpoint;
735
+ const scopeSource = (_e = config.scope) !== null && _e !== void 0 ? _e : config.scopes;
736
+ if (!appId) {
737
+ throw new Error(`OAuth2 provider '${providerId}' requires appId (or clientId).`);
720
738
  }
721
- // eslint-disable-next-line
722
- const state = this.getGoogleState();
723
- if (!state)
724
- throw new Error('No Google authorization code available');
725
- try {
726
- const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
727
- const isValidIdToken = this.idTokenValid(state.idToken);
728
- if (isValidAccessToken && isValidIdToken) {
729
- return { accessToken: state.accessToken, jwt: state.idToken };
730
- }
731
- else {
732
- try {
733
- await this.rawLogoutGoogle(state.accessToken, false);
734
- }
735
- catch (e) {
736
- console.error('Access token is not valid, but cannot logout', e);
737
- }
738
- throw new Error('No Google authorization code available');
739
- }
739
+ if (!config.redirectUrl) {
740
+ throw new Error(`OAuth2 provider '${providerId}' requires redirectUrl.`);
740
741
  }
741
- catch (e) {
742
- return Promise.reject(e);
742
+ if (!authorizationBaseUrl && !config.issuerUrl) {
743
+ throw new Error(`OAuth2 provider '${providerId}' requires authorizationBaseUrl (or authorizationEndpoint) or issuerUrl.`);
743
744
  }
745
+ return {
746
+ appId,
747
+ clientSecret: config.clientSecret,
748
+ issuerUrl: config.issuerUrl,
749
+ authorizationBaseUrl,
750
+ accessTokenEndpoint,
751
+ redirectUrl: config.redirectUrl,
752
+ resourceUrl: config.resourceUrl,
753
+ responseType: ((_f = config.responseType) !== null && _f !== void 0 ? _f : 'code'),
754
+ pkceEnabled: (_g = config.pkceEnabled) !== null && _g !== void 0 ? _g : true,
755
+ scope: this.normalizeScopeValue(scopeSource),
756
+ additionalParameters: config.additionalParameters,
757
+ loginHint: config.loginHint,
758
+ prompt: config.prompt,
759
+ additionalTokenParameters: config.additionalTokenParameters,
760
+ additionalResourceHeaders: config.additionalResourceHeaders,
761
+ logoutUrl,
762
+ postLogoutRedirectUrl: config.postLogoutRedirectUrl,
763
+ additionalLogoutParameters: config.additionalLogoutParameters,
764
+ logsEnabled: (_h = config.logsEnabled) !== null && _h !== void 0 ? _h : false,
765
+ };
744
766
  }
745
- async refresh() {
746
- if (this.loginType === 'offline') {
747
- console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);
748
- return Promise.reject(new Error(GOOGLE_OFFLINE_REFRESH_MESSAGE));
767
+ async ensureDiscovered(providerId) {
768
+ const config = this.providers.get(providerId);
769
+ if (!(config === null || config === void 0 ? void 0 : config.issuerUrl))
770
+ return;
771
+ // Resolve endpoints lazily.
772
+ if (config.authorizationBaseUrl && config.accessTokenEndpoint)
773
+ return;
774
+ const issuer = config.issuerUrl.replace(/\/+$/, '');
775
+ const discoveryUrl = `${issuer}/.well-known/openid-configuration`;
776
+ const resp = await fetch(discoveryUrl);
777
+ if (!resp.ok) {
778
+ const text = await resp.text().catch(() => '');
779
+ throw new Error(`OAuth2 discovery failed (${resp.status}): ${text || discoveryUrl}`);
749
780
  }
750
- return Promise.reject(new Error('Google refresh is not implemented on web. Use login() again to obtain a new token.'));
751
- }
752
- handleOAuthRedirect(url) {
753
- const paramsRaw = url.searchParams;
754
- // Check for errors in search params first (for offline mode)
755
- const errorInParams = paramsRaw.get('error');
756
- if (errorInParams) {
757
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
758
- const errorDescription = paramsRaw.get('error_description') || errorInParams;
759
- return { error: errorDescription };
781
+ const payload = (await resp.json());
782
+ const authorizationEndpoint = payload['authorization_endpoint'];
783
+ const tokenEndpoint = payload['token_endpoint'];
784
+ const endSessionEndpoint = payload['end_session_endpoint'];
785
+ if (!config.authorizationBaseUrl && typeof authorizationEndpoint === 'string') {
786
+ config.authorizationBaseUrl = authorizationEndpoint;
760
787
  }
761
- const code = paramsRaw.get('code');
762
- if (code && paramsRaw.has('scope')) {
763
- return {
764
- provider: 'google',
765
- result: {
766
- serverAuthCode: code,
767
- responseType: 'offline',
768
- },
769
- };
788
+ if (!config.accessTokenEndpoint && typeof tokenEndpoint === 'string') {
789
+ config.accessTokenEndpoint = tokenEndpoint;
770
790
  }
771
- const hash = url.hash.substring(1);
772
- console.log('handleOAuthRedirect', url.hash);
773
- if (!hash)
774
- return null;
775
- const params = new URLSearchParams(hash);
776
- // Check for error cases in hash (e.g., user cancelled)
777
- const error = params.get('error');
778
- if (error) {
779
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
780
- const errorDescription = params.get('error_description') || error;
781
- return { error: errorDescription };
791
+ if (!config.logoutUrl && typeof endSessionEndpoint === 'string') {
792
+ config.logoutUrl = endSessionEndpoint;
782
793
  }
783
- console.log('handleOAuthRedirect ok');
784
- const accessToken = params.get('access_token');
785
- const idToken = params.get('id_token');
786
- if (accessToken && idToken) {
787
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
788
- const profile = this.parseJwt(idToken);
789
- return {
790
- provider: 'google',
791
- result: {
792
- accessToken: {
793
- token: accessToken,
794
- },
795
- idToken,
796
- profile: {
797
- email: profile.email || null,
798
- familyName: profile.family_name || null,
799
- givenName: profile.given_name || null,
800
- id: profile.sub || null,
801
- name: profile.name || null,
802
- imageUrl: profile.picture || null,
803
- },
804
- responseType: 'online',
805
- },
806
- };
794
+ if (config.logsEnabled) {
795
+ console.log(`[OAuth2:${providerId}] Discovery resolved`, {
796
+ authorizationBaseUrl: config.authorizationBaseUrl,
797
+ accessTokenEndpoint: config.accessTokenEndpoint,
798
+ logoutUrl: config.logoutUrl,
799
+ });
807
800
  }
808
- return null;
801
+ // Persist updated configuration after discovery
802
+ this.persistConfiguration(providerId, config);
809
803
  }
810
- async accessTokenIsValid(accessToken) {
811
- const url = `${this.GOOGLE_TOKEN_REQUEST_URL}?access_token=${encodeURIComponent(accessToken)}`;
812
- try {
813
- // Make the GET request using fetch
814
- const response = await fetch(url);
815
- // Check if the response is successful
816
- if (!response.ok) {
817
- console.log(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response not successful. Status code: ${response.status}. Assuming that the token is not valid`);
818
- return false;
819
- }
820
- // Get the response body as text
821
- const responseBody = await response.text();
822
- if (!responseBody) {
823
- console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);
824
- throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is null`);
825
- }
826
- // Parse the response body as JSON
827
- let jsonObject;
828
- try {
829
- jsonObject = JSON.parse(responseBody);
830
- }
831
- catch (e) {
832
- console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`);
833
- throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response body is not valid JSON. Error: ${e}`);
834
- }
835
- // Extract the 'expires_in' field
836
- const expiresInStr = jsonObject['expires_in'];
837
- if (expiresInStr === undefined || expiresInStr === null) {
838
- console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`);
839
- throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. Response JSON does not include 'expires_in'.`);
840
- }
841
- // Parse 'expires_in' as an integer
842
- let expiresInInt;
843
- try {
844
- expiresInInt = parseInt(expiresInStr, 10);
845
- if (isNaN(expiresInInt)) {
846
- throw new Error(`'expires_in' is not a valid integer`);
847
- }
848
- }
849
- catch (e) {
850
- console.error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`);
851
- throw new Error(`Invalid response from ${this.GOOGLE_TOKEN_REQUEST_URL}. 'expires_in': ${expiresInStr} is not a valid integer. Error: ${e}`);
804
+ /**
805
+ * Initialize multiple OAuth2 providers
806
+ */
807
+ async initializeProviders(configs) {
808
+ for (const [providerId, config] of Object.entries(configs)) {
809
+ const internalConfig = this.normalizeConfig(providerId, config);
810
+ this.providers.set(providerId, internalConfig);
811
+ if (internalConfig.logsEnabled) {
812
+ console.log(`[OAuth2:${providerId}] Initialized with config:`, {
813
+ appId: internalConfig.appId,
814
+ issuerUrl: internalConfig.issuerUrl,
815
+ authorizationBaseUrl: internalConfig.authorizationBaseUrl,
816
+ redirectUrl: internalConfig.redirectUrl,
817
+ responseType: internalConfig.responseType,
818
+ pkceEnabled: internalConfig.pkceEnabled,
819
+ });
852
820
  }
853
- // Determine if the access token is valid based on 'expires_in'
854
- return expiresInInt > 5;
855
- }
856
- catch (error) {
857
- console.error(error);
858
- throw error;
821
+ // Pre-resolve discovery on web if issuerUrl is provided.
822
+ await this.ensureDiscovered(providerId);
823
+ // Persist configuration to localStorage so it's available in popup window context
824
+ this.persistConfiguration(providerId, internalConfig);
859
825
  }
860
826
  }
861
- idTokenValid(idToken) {
862
- try {
863
- const parsed = this.parseJwt(idToken);
864
- const currentTime = Math.ceil(Date.now() / 1000) + 5; // Convert current time to seconds since epoch
865
- return parsed.exp && currentTime < parsed.exp;
866
- }
867
- catch (e) {
868
- return false;
827
+ getProvider(providerId) {
828
+ const config = this.providers.get(providerId);
829
+ if (!config) {
830
+ throw new Error(`OAuth2 provider '${providerId}' not configured. Call initialize() first.`);
869
831
  }
832
+ return config;
870
833
  }
871
- async rawLogoutGoogle(accessToken, tokenValid = null) {
872
- if (tokenValid === null) {
873
- tokenValid = await this.accessTokenIsValid(accessToken);
874
- }
875
- if (tokenValid === true) {
876
- try {
877
- await fetch(`https://accounts.google.com/o/oauth2/revoke?token=${encodeURIComponent(accessToken)}`);
878
- this.clearStateGoogle();
879
- }
880
- catch (e) {
881
- // ignore
882
- }
883
- return;
884
- }
885
- else {
886
- this.clearStateGoogle();
887
- return;
888
- }
834
+ getTokensKey(providerId) {
835
+ return `${this.TOKENS_KEY_PREFIX}${providerId}`;
889
836
  }
890
- persistStateGoogle(accessToken, idToken) {
837
+ getConfigKey(providerId) {
838
+ return `${this.CONFIG_KEY_PREFIX}${providerId}`;
839
+ }
840
+ persistConfiguration(providerId, config) {
891
841
  try {
892
- window.localStorage.setItem(this.GOOGLE_STATE_KEY, JSON.stringify({ accessToken, idToken }));
842
+ localStorage.setItem(this.getConfigKey(providerId), JSON.stringify(config));
893
843
  }
894
- catch (e) {
895
- console.error('Cannot persist state google', e);
844
+ catch (err) {
845
+ console.warn(`Failed to persist OAuth2 configuration for provider '${providerId}'`, err);
896
846
  }
897
847
  }
898
- clearStateGoogle() {
899
- try {
900
- window.localStorage.removeItem(this.GOOGLE_STATE_KEY);
901
- }
902
- catch (e) {
903
- console.error('Cannot clear state google', e);
848
+ restoreConfigurationsFromStorage() {
849
+ // Restore all provider configurations from localStorage
850
+ // This is needed for popup window context where the parent's in-memory state is not available
851
+ const keys = Object.keys(localStorage);
852
+ for (const key of keys) {
853
+ if (key.startsWith(this.CONFIG_KEY_PREFIX)) {
854
+ const providerId = key.substring(this.CONFIG_KEY_PREFIX.length);
855
+ try {
856
+ const raw = localStorage.getItem(key);
857
+ if (raw) {
858
+ const config = JSON.parse(raw);
859
+ this.providers.set(providerId, config);
860
+ }
861
+ }
862
+ catch (err) {
863
+ console.warn(`Failed to restore OAuth2 configuration for provider '${providerId}'`, err);
864
+ }
865
+ }
904
866
  }
905
867
  }
906
- getGoogleState() {
907
- try {
908
- const state = window.localStorage.getItem(this.GOOGLE_STATE_KEY);
909
- if (!state)
910
- return null;
911
- const { accessToken, idToken } = JSON.parse(state);
912
- return { accessToken, idToken };
868
+ async login(options) {
869
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
870
+ const { providerId } = options;
871
+ const config = this.getProvider(providerId);
872
+ await this.ensureDiscovered(providerId);
873
+ const redirectUri = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : config.redirectUrl;
874
+ const scope = this.normalizeScopeValue((_c = (_b = options.scope) !== null && _b !== void 0 ? _b : options.scopes) !== null && _c !== void 0 ? _c : config.scope);
875
+ const state = (_d = options.state) !== null && _d !== void 0 ? _d : this.generateState();
876
+ const codeVerifier = (_e = options.codeVerifier) !== null && _e !== void 0 ? _e : this.generateCodeVerifier();
877
+ // Build authorization URL
878
+ const params = new URLSearchParams({
879
+ response_type: config.responseType,
880
+ client_id: config.appId,
881
+ redirect_uri: redirectUri,
882
+ state,
883
+ });
884
+ if (scope) {
885
+ params.set('scope', scope);
913
886
  }
914
- catch (e) {
915
- console.error('Cannot get state google', e);
916
- return null;
887
+ // Convenience OIDC options
888
+ const mergedAdditionalParams = Object.assign(Object.assign({}, ((_f = config.additionalParameters) !== null && _f !== void 0 ? _f : {})), ((_g = options.additionalParameters) !== null && _g !== void 0 ? _g : {}));
889
+ const loginHint = (_h = options.loginHint) !== null && _h !== void 0 ? _h : config.loginHint;
890
+ const prompt = (_j = options.prompt) !== null && _j !== void 0 ? _j : config.prompt;
891
+ if (loginHint && !('login_hint' in mergedAdditionalParams)) {
892
+ mergedAdditionalParams.login_hint = loginHint;
917
893
  }
918
- }
919
- async traditionalOAuth({ scopes, hostedDomain, nonce, prompt, }) {
920
- var _a;
921
- const uniqueScopes = [...new Set([...(scopes || []), 'openid'])];
922
- const params = new URLSearchParams(Object.assign(Object.assign({ client_id: (_a = this.clientId) !== null && _a !== void 0 ? _a : '', redirect_uri: this.redirectUrl || window.location.origin + window.location.pathname, response_type: this.loginType === 'offline' ? 'code' : 'token id_token', scope: uniqueScopes.join(' ') }, (nonce && { nonce })), { include_granted_scopes: 'true', state: 'popup' }));
923
- if (hostedDomain !== undefined) {
924
- params.append('hd', hostedDomain);
894
+ if (prompt && !('prompt' in mergedAdditionalParams)) {
895
+ mergedAdditionalParams.prompt = prompt;
925
896
  }
926
- if (prompt !== undefined) {
927
- params.append('prompt', prompt);
897
+ // Add PKCE for code flow
898
+ if (config.responseType === 'code' && config.pkceEnabled) {
899
+ const codeChallenge = await this.generateCodeChallenge(codeVerifier);
900
+ params.set('code_challenge', codeChallenge);
901
+ params.set('code_challenge_method', 'S256');
928
902
  }
929
- const url = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
903
+ // Add merged additional parameters
904
+ for (const [key, value] of Object.entries(mergedAdditionalParams)) {
905
+ if (value !== undefined) {
906
+ params.set(key, value);
907
+ }
908
+ }
909
+ // Store pending login state
910
+ this.persistPendingLogin(state, {
911
+ providerId,
912
+ codeVerifier,
913
+ redirectUri,
914
+ scope,
915
+ });
916
+ localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'oauth2', providerId, state }));
917
+ if (!config.authorizationBaseUrl) {
918
+ throw new Error(`OAuth2 provider '${providerId}' is missing authorizationBaseUrl (discovery may have failed).`);
919
+ }
920
+ const authUrl = `${config.authorizationBaseUrl}?${params.toString()}`;
921
+ if (config.logsEnabled) {
922
+ console.log(`[OAuth2:${providerId}] Opening authorization URL:`, authUrl);
923
+ }
924
+ if (options.flow === 'redirect') {
925
+ // Trigger a full-page redirect. The promise will not resolve because the page navigates away.
926
+ window.location.assign(authUrl);
927
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
928
+ return new Promise(() => { });
929
+ }
930
+ // Open popup window
930
931
  const width = 500;
931
- const height = 600;
932
+ const height = 650;
932
933
  const left = window.screenX + (window.outerWidth - width) / 2;
933
934
  const top = window.screenY + (window.outerHeight - height) / 2;
934
- localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'google', loginType: this.loginType, nonce }));
935
- const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);
936
- let popupClosedInterval;
937
- let timeoutHandle;
938
- // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)
939
- const channelName = `google_oauth_${nonce || Date.now()}`;
940
- let broadcastChannel = null;
941
- try {
942
- broadcastChannel = new BroadcastChannel(channelName);
943
- }
944
- catch (_b) {
945
- // BroadcastChannel not supported, fall back to postMessage only
946
- }
947
- // This may never return...
935
+ const popup = window.open(authUrl, 'OAuth2Login', `width=${width},height=${height},left=${left},top=${top},popup=1`);
948
936
  return new Promise((resolve, reject) => {
949
937
  if (!popup) {
950
- reject(new Error('Failed to open popup'));
938
+ reject(new Error('Unable to open login window. Please allow popups.'));
951
939
  return;
952
940
  }
953
- const cleanup = (shouldClose = false) => {
954
- window.removeEventListener('message', handleMessage);
955
- clearInterval(popupClosedInterval);
941
+ // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)
942
+ const channelName = `oauth2_${state}`;
943
+ let broadcastChannel = null;
944
+ try {
945
+ broadcastChannel = new BroadcastChannel(channelName);
946
+ }
947
+ catch (_a) {
948
+ // BroadcastChannel not supported, fall back to postMessage only
949
+ if (config.logsEnabled) {
950
+ console.log(`[OAuth2:${providerId}] BroadcastChannel not supported, using postMessage only`);
951
+ }
952
+ }
953
+ const cleanup = (messageHandler, timeoutHandle, intervalHandle) => {
954
+ window.removeEventListener('message', messageHandler);
956
955
  clearTimeout(timeoutHandle);
956
+ clearInterval(intervalHandle);
957
957
  if (broadcastChannel) {
958
958
  broadcastChannel.close();
959
959
  }
960
- if (shouldClose) {
961
- try {
962
- popup.close();
963
- }
964
- catch (_a) {
965
- // Ignore cross-origin errors when closing the popup
966
- }
967
- }
968
960
  };
969
- const processOAuthResponse = (data) => {
970
- if (this.loginType === 'online') {
971
- const { accessToken, idToken } = data;
972
- if (accessToken && idToken) {
973
- const profile = this.parseJwt(idToken);
974
- this.persistStateGoogle(accessToken.token, idToken);
975
- resolve({
976
- provider: 'google',
977
- result: {
978
- accessToken: {
979
- token: accessToken.token,
980
- },
981
- idToken,
982
- profile: {
983
- email: profile.email || null,
984
- familyName: profile.family_name || null,
985
- givenName: profile.given_name || null,
986
- id: profile.sub || null,
987
- name: profile.name || null,
988
- imageUrl: profile.picture || null,
989
- },
990
- responseType: 'online',
991
- },
992
- });
993
- }
994
- else {
995
- reject(new Error('Invalid OAuth response: missing accessToken or idToken'));
961
+ const handleOAuthMessage = (data) => {
962
+ if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
963
+ if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'oauth2') {
964
+ return false;
996
965
  }
997
- }
998
- else {
999
- const { serverAuthCode } = data;
1000
- if (!serverAuthCode) {
1001
- reject(new Error('Invalid OAuth response: missing serverAuthCode'));
1002
- return;
966
+ // Check providerId matches if present
967
+ if ((data === null || data === void 0 ? void 0 : data.providerId) && data.providerId !== providerId) {
968
+ return false;
1003
969
  }
970
+ cleanup(messageHandler, timeoutHandle, popupClosedInterval);
971
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
972
+ const _a = data, { provider: _ignoredProvider, type: _ignoredType } = _a, payload = __rest(_a, ["provider", "type"]);
1004
973
  resolve({
1005
- provider: 'google',
1006
- result: {
1007
- responseType: 'offline',
1008
- serverAuthCode,
1009
- },
974
+ provider: 'oauth2',
975
+ result: payload,
1010
976
  });
977
+ return true;
1011
978
  }
1012
- };
1013
- const handleMessage = (event) => {
1014
- var _a, _b, _c, _d;
1015
- if (event.origin !== window.location.origin || ((_b = (_a = event.data) === null || _a === void 0 ? void 0 : _a.source) === null || _b === void 0 ? void 0 : _b.startsWith('angular')))
1016
- return;
1017
- if (((_c = event.data) === null || _c === void 0 ? void 0 : _c.type) === 'oauth-response') {
1018
- cleanup(true);
1019
- processOAuthResponse(event.data);
1020
- }
1021
- else if (((_d = event.data) === null || _d === void 0 ? void 0 : _d.type) === 'oauth-error') {
1022
- cleanup(true);
1023
- const errorMessage = event.data.error || 'User cancelled the OAuth flow';
1024
- reject(inferUserCancelledError(errorMessage));
979
+ else if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
980
+ if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'oauth2') {
981
+ return false;
982
+ }
983
+ cleanup(messageHandler, timeoutHandle, popupClosedInterval);
984
+ reject(inferUserCancelledError(data.error || 'OAuth2 login was cancelled.'));
985
+ return true;
1025
986
  }
1026
- // Don't reject for non-OAuth messages, just ignore them
987
+ return false;
1027
988
  };
1028
989
  // Listen for BroadcastChannel messages
1029
990
  if (broadcastChannel) {
1030
991
  broadcastChannel.onmessage = (event) => {
1031
- var _a;
1032
- const data = event.data;
1033
- if ((_a = data === null || data === void 0 ? void 0 : data.source) === null || _a === void 0 ? void 0 : _a.toString().startsWith('angular'))
1034
- return;
1035
- if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
1036
- cleanup(true);
1037
- processOAuthResponse(data);
1038
- }
1039
- else if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
1040
- cleanup(true);
1041
- const errorMessage = data.error || 'User cancelled the OAuth flow';
1042
- reject(inferUserCancelledError(errorMessage));
1043
- }
992
+ handleOAuthMessage(event.data);
1044
993
  };
1045
994
  }
1046
- window.addEventListener('message', handleMessage);
1047
- // Timeout after 5 minutes
1048
- timeoutHandle = setTimeout(() => {
1049
- cleanup(true);
1050
- reject(new Error('OAuth timeout'));
995
+ const messageHandler = (event) => {
996
+ if (event.origin !== window.location.origin) {
997
+ return;
998
+ }
999
+ handleOAuthMessage(event.data);
1000
+ };
1001
+ window.addEventListener('message', messageHandler);
1002
+ const timeoutHandle = window.setTimeout(() => {
1003
+ cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1004
+ try {
1005
+ popup.close();
1006
+ }
1007
+ catch (_a) {
1008
+ // Ignore cross-origin errors when closing
1009
+ }
1010
+ reject(new Error('OAuth2 login timed out.'));
1051
1011
  }, 300000);
1052
- popupClosedInterval = setInterval(() => {
1012
+ const popupClosedInterval = window.setInterval(() => {
1053
1013
  try {
1054
1014
  // Check if popup is closed - this may throw cross-origin errors for some providers
1055
1015
  if (popup.closed) {
1056
- cleanup();
1057
- reject(createUserCancelledError('Popup closed'));
1016
+ cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1017
+ reject(createUserCancelledError('OAuth2 login window was closed.'));
1058
1018
  }
1059
1019
  }
1060
1020
  catch (_a) {
1061
1021
  // Cross-origin error when checking popup.closed - this happens when the popup
1062
1022
  // navigates to a third-party OAuth provider with strict security settings.
1063
- // We can't detect if the window was closed, so we rely on timeout and message handlers.
1023
+ // We can't detect if the window was closed, so we just rely on the timeout
1024
+ // and message handlers. Clear the interval to avoid repeated errors.
1064
1025
  clearInterval(popupClosedInterval);
1026
+ if (config.logsEnabled) {
1027
+ console.log(`[OAuth2:${providerId}] Cannot check popup.closed due to cross-origin restrictions. ` +
1028
+ 'Relying on message handlers and timeout.');
1029
+ }
1030
+ }
1031
+ }, 1000);
1032
+ });
1033
+ }
1034
+ async logout(providerId) {
1035
+ await this.ensureDiscovered(providerId);
1036
+ const config = this.providers.get(providerId);
1037
+ const stored = this.getStoredTokens(providerId);
1038
+ localStorage.removeItem(this.getTokensKey(providerId));
1039
+ // If logout URL is configured, build an end-session URL (OIDC) when possible.
1040
+ if (config === null || config === void 0 ? void 0 : config.logoutUrl) {
1041
+ try {
1042
+ const url = new URL(config.logoutUrl);
1043
+ if (stored === null || stored === void 0 ? void 0 : stored.idToken) {
1044
+ url.searchParams.set('id_token_hint', stored.idToken);
1045
+ }
1046
+ const postLogout = config.postLogoutRedirectUrl;
1047
+ if (postLogout) {
1048
+ url.searchParams.set('post_logout_redirect_uri', postLogout);
1049
+ }
1050
+ if (config.additionalLogoutParameters) {
1051
+ for (const [k, v] of Object.entries(config.additionalLogoutParameters)) {
1052
+ url.searchParams.set(k, v);
1053
+ }
1065
1054
  }
1066
- }, 1000);
1067
- });
1055
+ window.open(url.toString(), '_blank');
1056
+ }
1057
+ catch (_a) {
1058
+ window.open(config.logoutUrl, '_blank');
1059
+ }
1060
+ }
1068
1061
  }
1069
- }
1070
-
1071
- /**
1072
- * OAuth2 Social Login Manager
1073
- * Supports multiple OAuth2 provider configurations
1074
- */
1075
- class OAuth2SocialLogin extends BaseSocialLogin {
1076
- constructor() {
1077
- super();
1078
- this.providers = new Map();
1079
- this.TOKENS_KEY_PREFIX = 'capgo_social_login_oauth2_tokens_';
1080
- this.STATE_PREFIX = 'capgo_social_login_oauth2_state_';
1081
- this.CONFIG_KEY_PREFIX = 'capgo_social_login_oauth2_config_';
1082
- // Restore configurations from localStorage for popup window context
1083
- this.restoreConfigurationsFromStorage();
1062
+ async isLoggedIn(providerId) {
1063
+ const tokens = this.getStoredTokens(providerId);
1064
+ if (!tokens) {
1065
+ return { isLoggedIn: false };
1066
+ }
1067
+ const isValid = tokens.expiresAt > Date.now();
1068
+ if (!isValid) {
1069
+ localStorage.removeItem(this.getTokensKey(providerId));
1070
+ }
1071
+ return { isLoggedIn: isValid };
1084
1072
  }
1085
- normalizeScopeValue(scope) {
1086
- if (!scope)
1087
- return '';
1088
- if (typeof scope === 'string')
1089
- return scope;
1090
- if (Array.isArray(scope))
1091
- return scope.filter(Boolean).join(' ');
1092
- return '';
1073
+ async getAuthorizationCode(providerId) {
1074
+ const tokens = this.getStoredTokens(providerId);
1075
+ if (!tokens) {
1076
+ throw new Error(`OAuth2 access token is not available for provider '${providerId}'.`);
1077
+ }
1078
+ return {
1079
+ accessToken: tokens.accessToken,
1080
+ jwt: tokens.idToken,
1081
+ };
1093
1082
  }
1094
- normalizeConfig(providerId, config) {
1095
- var _a, _b, _c, _d, _e, _f, _g, _h;
1096
- const appId = (_a = config.appId) !== null && _a !== void 0 ? _a : config.clientId;
1097
- const authorizationBaseUrl = (_b = config.authorizationBaseUrl) !== null && _b !== void 0 ? _b : config.authorizationEndpoint;
1098
- const accessTokenEndpoint = (_c = config.accessTokenEndpoint) !== null && _c !== void 0 ? _c : config.tokenEndpoint;
1099
- const logoutUrl = (_d = config.logoutUrl) !== null && _d !== void 0 ? _d : config.endSessionEndpoint;
1100
- const scopeSource = (_e = config.scope) !== null && _e !== void 0 ? _e : config.scopes;
1101
- if (!appId) {
1102
- throw new Error(`OAuth2 provider '${providerId}' requires appId (or clientId).`);
1083
+ async refresh(providerId) {
1084
+ await this.refreshToken(providerId);
1085
+ }
1086
+ async refreshToken(providerId, refreshToken, additionalParameters) {
1087
+ var _a, _b, _c, _d, _e, _f;
1088
+ await this.ensureDiscovered(providerId);
1089
+ const config = this.getProvider(providerId);
1090
+ const stored = this.getStoredTokens(providerId);
1091
+ const effectiveRefreshToken = refreshToken !== null && refreshToken !== void 0 ? refreshToken : stored === null || stored === void 0 ? void 0 : stored.refreshToken;
1092
+ if (!effectiveRefreshToken) {
1093
+ throw new Error(`No OAuth2 refresh token is available for provider '${providerId}'. Include offline_access scope to receive one.`);
1103
1094
  }
1104
- if (!config.redirectUrl) {
1105
- throw new Error(`OAuth2 provider '${providerId}' requires redirectUrl.`);
1095
+ if (!config.accessTokenEndpoint) {
1096
+ throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1106
1097
  }
1107
- if (!authorizationBaseUrl && !config.issuerUrl) {
1108
- throw new Error(`OAuth2 provider '${providerId}' requires authorizationBaseUrl (or authorizationEndpoint) or issuerUrl.`);
1098
+ const tokenResponse = await this.refreshWithRefreshToken(providerId, effectiveRefreshToken, additionalParameters);
1099
+ const expiresAt = tokenResponse.expires_in ? Date.now() + tokenResponse.expires_in * 1000 : Date.now() + 3600000;
1100
+ const scopeArray = (_c = (_b = (_a = tokenResponse.scope) === null || _a === void 0 ? void 0 : _a.split(' ').filter(Boolean)) !== null && _b !== void 0 ? _b : stored === null || stored === void 0 ? void 0 : stored.scope) !== null && _c !== void 0 ? _c : [];
1101
+ // Fetch resource data if configured
1102
+ let resourceData = null;
1103
+ if (config.resourceUrl) {
1104
+ resourceData = await this.fetchResource(providerId, tokenResponse.access_token);
1109
1105
  }
1106
+ const nextRefreshToken = (_d = tokenResponse.refresh_token) !== null && _d !== void 0 ? _d : effectiveRefreshToken;
1107
+ this.persistTokens(providerId, {
1108
+ accessToken: tokenResponse.access_token,
1109
+ refreshToken: nextRefreshToken,
1110
+ idToken: tokenResponse.id_token,
1111
+ expiresAt,
1112
+ scope: scopeArray,
1113
+ tokenType: tokenResponse.token_type,
1114
+ });
1110
1115
  return {
1111
- appId,
1112
- clientSecret: config.clientSecret,
1113
- issuerUrl: config.issuerUrl,
1114
- authorizationBaseUrl,
1115
- accessTokenEndpoint,
1116
- redirectUrl: config.redirectUrl,
1117
- resourceUrl: config.resourceUrl,
1118
- responseType: ((_f = config.responseType) !== null && _f !== void 0 ? _f : 'code'),
1119
- pkceEnabled: (_g = config.pkceEnabled) !== null && _g !== void 0 ? _g : true,
1120
- scope: this.normalizeScopeValue(scopeSource),
1121
- additionalParameters: config.additionalParameters,
1122
- loginHint: config.loginHint,
1123
- prompt: config.prompt,
1124
- additionalTokenParameters: config.additionalTokenParameters,
1125
- additionalResourceHeaders: config.additionalResourceHeaders,
1126
- logoutUrl,
1127
- postLogoutRedirectUrl: config.postLogoutRedirectUrl,
1128
- additionalLogoutParameters: config.additionalLogoutParameters,
1129
- logsEnabled: (_h = config.logsEnabled) !== null && _h !== void 0 ? _h : false,
1116
+ providerId,
1117
+ accessToken: {
1118
+ token: tokenResponse.access_token,
1119
+ tokenType: tokenResponse.token_type,
1120
+ expires: new Date(expiresAt).toISOString(),
1121
+ refreshToken: nextRefreshToken,
1122
+ },
1123
+ idToken: (_e = tokenResponse.id_token) !== null && _e !== void 0 ? _e : null,
1124
+ refreshToken: nextRefreshToken !== null && nextRefreshToken !== void 0 ? nextRefreshToken : null,
1125
+ resourceData,
1126
+ scope: scopeArray,
1127
+ tokenType: tokenResponse.token_type,
1128
+ expiresIn: (_f = tokenResponse.expires_in) !== null && _f !== void 0 ? _f : null,
1130
1129
  };
1131
1130
  }
1132
- async ensureDiscovered(providerId) {
1131
+ async handleOAuthRedirect(url, expectedState) {
1132
+ var _a, _b, _c, _d, _e;
1133
+ // Check both query params and hash fragment
1134
+ const params = new URLSearchParams(url.search);
1135
+ const hashParams = new URLSearchParams(url.hash.slice(1));
1136
+ // Merge params, hash takes priority (for implicit flow)
1137
+ hashParams.forEach((value, key) => {
1138
+ params.set(key, value);
1139
+ });
1140
+ const stateFromUrl = expectedState !== null && expectedState !== void 0 ? expectedState : params.get('state');
1141
+ if (!stateFromUrl) {
1142
+ return null;
1143
+ }
1144
+ const pending = this.consumePendingLogin(stateFromUrl);
1145
+ if (!pending) {
1146
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1147
+ return { error: 'OAuth2 login session expired or state mismatch.' };
1148
+ }
1149
+ const { providerId } = pending;
1150
+ await this.ensureDiscovered(providerId);
1133
1151
  const config = this.providers.get(providerId);
1134
- if (!(config === null || config === void 0 ? void 0 : config.issuerUrl))
1135
- return;
1136
- // Resolve endpoints lazily.
1137
- if (config.authorizationBaseUrl && config.accessTokenEndpoint)
1138
- return;
1139
- const issuer = config.issuerUrl.replace(/\/+$/, '');
1140
- const discoveryUrl = `${issuer}/.well-known/openid-configuration`;
1141
- const resp = await fetch(discoveryUrl);
1142
- if (!resp.ok) {
1143
- const text = await resp.text().catch(() => '');
1144
- throw new Error(`OAuth2 discovery failed (${resp.status}): ${text || discoveryUrl}`);
1152
+ if (!config) {
1153
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1154
+ return { error: `OAuth2 provider '${providerId}' configuration not found.` };
1145
1155
  }
1146
- const payload = (await resp.json());
1147
- const authorizationEndpoint = payload['authorization_endpoint'];
1148
- const tokenEndpoint = payload['token_endpoint'];
1149
- const endSessionEndpoint = payload['end_session_endpoint'];
1150
- if (!config.authorizationBaseUrl && typeof authorizationEndpoint === 'string') {
1151
- config.authorizationBaseUrl = authorizationEndpoint;
1156
+ const error = params.get('error');
1157
+ if (error) {
1158
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1159
+ return { error: params.get('error_description') || error };
1160
+ }
1161
+ try {
1162
+ let tokenResponse;
1163
+ // Check response type
1164
+ if (params.has('code')) {
1165
+ // Authorization code flow
1166
+ const code = params.get('code');
1167
+ if (!code) {
1168
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1169
+ return { error: 'OAuth2 authorization code missing from redirect.' };
1170
+ }
1171
+ tokenResponse = await this.exchangeAuthorizationCode(providerId, code, pending);
1172
+ }
1173
+ else if (params.has('access_token')) {
1174
+ // Implicit flow
1175
+ tokenResponse = {
1176
+ access_token: params.get('access_token'),
1177
+ token_type: params.get('token_type') || 'bearer',
1178
+ expires_in: params.has('expires_in') ? parseInt(params.get('expires_in'), 10) : undefined,
1179
+ scope: params.get('scope') || undefined,
1180
+ id_token: params.get('id_token') || undefined,
1181
+ };
1182
+ }
1183
+ else {
1184
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1185
+ return { error: 'No authorization code or access token in redirect.' };
1186
+ }
1187
+ const expiresAt = tokenResponse.expires_in ? Date.now() + tokenResponse.expires_in * 1000 : Date.now() + 3600000;
1188
+ const scopeArray = (_b = (_a = tokenResponse.scope) === null || _a === void 0 ? void 0 : _a.split(' ').filter(Boolean)) !== null && _b !== void 0 ? _b : [];
1189
+ // Fetch resource data if configured
1190
+ let resourceData = null;
1191
+ if (config.resourceUrl) {
1192
+ resourceData = await this.fetchResource(providerId, tokenResponse.access_token);
1193
+ }
1194
+ this.persistTokens(providerId, {
1195
+ accessToken: tokenResponse.access_token,
1196
+ refreshToken: tokenResponse.refresh_token,
1197
+ idToken: tokenResponse.id_token,
1198
+ expiresAt,
1199
+ scope: scopeArray,
1200
+ tokenType: tokenResponse.token_type,
1201
+ });
1202
+ return {
1203
+ provider: 'oauth2',
1204
+ result: {
1205
+ providerId,
1206
+ accessToken: {
1207
+ token: tokenResponse.access_token,
1208
+ tokenType: tokenResponse.token_type,
1209
+ expires: new Date(expiresAt).toISOString(),
1210
+ refreshToken: tokenResponse.refresh_token,
1211
+ },
1212
+ idToken: (_c = tokenResponse.id_token) !== null && _c !== void 0 ? _c : null,
1213
+ refreshToken: (_d = tokenResponse.refresh_token) !== null && _d !== void 0 ? _d : null,
1214
+ resourceData,
1215
+ scope: scopeArray,
1216
+ tokenType: tokenResponse.token_type,
1217
+ expiresIn: (_e = tokenResponse.expires_in) !== null && _e !== void 0 ? _e : null,
1218
+ },
1219
+ };
1220
+ }
1221
+ catch (err) {
1222
+ if (err instanceof Error) {
1223
+ return { error: err.message };
1224
+ }
1225
+ return { error: 'OAuth2 login failed unexpectedly.' };
1226
+ }
1227
+ finally {
1228
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1229
+ }
1230
+ }
1231
+ async exchangeAuthorizationCode(providerId, code, pending) {
1232
+ const config = this.getProvider(providerId);
1233
+ if (!config.accessTokenEndpoint) {
1234
+ throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1235
+ }
1236
+ const params = new URLSearchParams({
1237
+ grant_type: 'authorization_code',
1238
+ client_id: config.appId,
1239
+ code,
1240
+ redirect_uri: pending.redirectUri,
1241
+ });
1242
+ if (config.pkceEnabled) {
1243
+ params.set('code_verifier', pending.codeVerifier);
1152
1244
  }
1153
- if (!config.accessTokenEndpoint && typeof tokenEndpoint === 'string') {
1154
- config.accessTokenEndpoint = tokenEndpoint;
1245
+ if (config.clientSecret) {
1246
+ params.set('client_secret', config.clientSecret);
1155
1247
  }
1156
- if (!config.logoutUrl && typeof endSessionEndpoint === 'string') {
1157
- config.logoutUrl = endSessionEndpoint;
1248
+ if (config.additionalTokenParameters) {
1249
+ for (const [k, v] of Object.entries(config.additionalTokenParameters)) {
1250
+ params.set(k, v);
1251
+ }
1158
1252
  }
1159
1253
  if (config.logsEnabled) {
1160
- console.log(`[OAuth2:${providerId}] Discovery resolved`, {
1161
- authorizationBaseUrl: config.authorizationBaseUrl,
1162
- accessTokenEndpoint: config.accessTokenEndpoint,
1163
- logoutUrl: config.logoutUrl,
1164
- });
1254
+ console.log(`[OAuth2:${providerId}] Exchanging code at:`, config.accessTokenEndpoint);
1165
1255
  }
1166
- // Persist updated configuration after discovery
1167
- this.persistConfiguration(providerId, config);
1256
+ const response = await fetch(config.accessTokenEndpoint, {
1257
+ method: 'POST',
1258
+ headers: {
1259
+ 'Content-Type': 'application/x-www-form-urlencoded',
1260
+ },
1261
+ body: params.toString(),
1262
+ });
1263
+ if (!response.ok) {
1264
+ const text = await response.text();
1265
+ throw new Error(`OAuth2 token exchange failed (${response.status}): ${text}`);
1266
+ }
1267
+ return (await response.json());
1168
1268
  }
1169
- /**
1170
- * Initialize multiple OAuth2 providers
1171
- */
1172
- async initializeProviders(configs) {
1173
- for (const [providerId, config] of Object.entries(configs)) {
1174
- const internalConfig = this.normalizeConfig(providerId, config);
1175
- this.providers.set(providerId, internalConfig);
1176
- if (internalConfig.logsEnabled) {
1177
- console.log(`[OAuth2:${providerId}] Initialized with config:`, {
1178
- appId: internalConfig.appId,
1179
- issuerUrl: internalConfig.issuerUrl,
1180
- authorizationBaseUrl: internalConfig.authorizationBaseUrl,
1181
- redirectUrl: internalConfig.redirectUrl,
1182
- responseType: internalConfig.responseType,
1183
- pkceEnabled: internalConfig.pkceEnabled,
1184
- });
1269
+ async refreshWithRefreshToken(providerId, refreshToken, additionalParameters) {
1270
+ const config = this.getProvider(providerId);
1271
+ if (!config.accessTokenEndpoint) {
1272
+ throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1273
+ }
1274
+ const params = new URLSearchParams({
1275
+ grant_type: 'refresh_token',
1276
+ refresh_token: refreshToken,
1277
+ client_id: config.appId,
1278
+ });
1279
+ if (config.clientSecret) {
1280
+ params.set('client_secret', config.clientSecret);
1281
+ }
1282
+ if (config.additionalTokenParameters) {
1283
+ for (const [k, v] of Object.entries(config.additionalTokenParameters)) {
1284
+ params.set(k, v);
1185
1285
  }
1186
- // Pre-resolve discovery on web if issuerUrl is provided.
1187
- await this.ensureDiscovered(providerId);
1188
- // Persist configuration to localStorage so it's available in popup window context
1189
- this.persistConfiguration(providerId, internalConfig);
1190
1286
  }
1191
- }
1192
- getProvider(providerId) {
1193
- const config = this.providers.get(providerId);
1194
- if (!config) {
1195
- throw new Error(`OAuth2 provider '${providerId}' not configured. Call initialize() first.`);
1287
+ if (additionalParameters) {
1288
+ for (const [k, v] of Object.entries(additionalParameters)) {
1289
+ params.set(k, v);
1290
+ }
1196
1291
  }
1197
- return config;
1292
+ const response = await fetch(config.accessTokenEndpoint, {
1293
+ method: 'POST',
1294
+ headers: {
1295
+ 'Content-Type': 'application/x-www-form-urlencoded',
1296
+ },
1297
+ body: params.toString(),
1298
+ });
1299
+ if (!response.ok) {
1300
+ const text = await response.text();
1301
+ throw new Error(`OAuth2 refresh failed (${response.status}): ${text}`);
1302
+ }
1303
+ return (await response.json());
1198
1304
  }
1199
- getTokensKey(providerId) {
1200
- return `${this.TOKENS_KEY_PREFIX}${providerId}`;
1305
+ async fetchResource(providerId, accessToken) {
1306
+ const config = this.getProvider(providerId);
1307
+ if (!config.resourceUrl) {
1308
+ throw new Error(`No resourceUrl configured for provider '${providerId}'.`);
1309
+ }
1310
+ const headers = {
1311
+ Authorization: `Bearer ${accessToken}`,
1312
+ };
1313
+ if (config.additionalResourceHeaders) {
1314
+ Object.assign(headers, config.additionalResourceHeaders);
1315
+ }
1316
+ const response = await fetch(config.resourceUrl, {
1317
+ headers,
1318
+ });
1319
+ if (!response.ok) {
1320
+ const text = await response.text();
1321
+ throw new Error(`Unable to fetch OAuth2 resource (${response.status}): ${text}`);
1322
+ }
1323
+ return (await response.json());
1201
1324
  }
1202
- getConfigKey(providerId) {
1203
- return `${this.CONFIG_KEY_PREFIX}${providerId}`;
1325
+ persistTokens(providerId, tokens) {
1326
+ localStorage.setItem(this.getTokensKey(providerId), JSON.stringify(tokens));
1204
1327
  }
1205
- persistConfiguration(providerId, config) {
1328
+ getStoredTokens(providerId) {
1329
+ const raw = localStorage.getItem(this.getTokensKey(providerId));
1330
+ if (!raw) {
1331
+ return null;
1332
+ }
1206
1333
  try {
1207
- localStorage.setItem(this.getConfigKey(providerId), JSON.stringify(config));
1334
+ return JSON.parse(raw);
1208
1335
  }
1209
1336
  catch (err) {
1210
- console.warn(`Failed to persist OAuth2 configuration for provider '${providerId}'`, err);
1337
+ console.warn(`Failed to parse stored OAuth2 tokens for provider '${providerId}'`, err);
1338
+ return null;
1211
1339
  }
1212
1340
  }
1213
- restoreConfigurationsFromStorage() {
1214
- // Restore all provider configurations from localStorage
1215
- // This is needed for popup window context where the parent's in-memory state is not available
1216
- const keys = Object.keys(localStorage);
1217
- for (const key of keys) {
1218
- if (key.startsWith(this.CONFIG_KEY_PREFIX)) {
1219
- const providerId = key.substring(this.CONFIG_KEY_PREFIX.length);
1220
- try {
1221
- const raw = localStorage.getItem(key);
1222
- if (raw) {
1223
- const config = JSON.parse(raw);
1224
- this.providers.set(providerId, config);
1225
- }
1226
- }
1227
- catch (err) {
1228
- console.warn(`Failed to restore OAuth2 configuration for provider '${providerId}'`, err);
1229
- }
1230
- }
1231
- }
1341
+ persistPendingLogin(state, payload) {
1342
+ localStorage.setItem(`${this.STATE_PREFIX}${state}`, JSON.stringify(payload));
1232
1343
  }
1233
- async login(options) {
1234
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1235
- const { providerId } = options;
1236
- const config = this.getProvider(providerId);
1237
- await this.ensureDiscovered(providerId);
1238
- const redirectUri = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : config.redirectUrl;
1239
- const scope = this.normalizeScopeValue((_c = (_b = options.scope) !== null && _b !== void 0 ? _b : options.scopes) !== null && _c !== void 0 ? _c : config.scope);
1240
- const state = (_d = options.state) !== null && _d !== void 0 ? _d : this.generateState();
1241
- const codeVerifier = (_e = options.codeVerifier) !== null && _e !== void 0 ? _e : this.generateCodeVerifier();
1242
- // Build authorization URL
1243
- const params = new URLSearchParams({
1244
- response_type: config.responseType,
1245
- client_id: config.appId,
1246
- redirect_uri: redirectUri,
1247
- state,
1248
- });
1249
- if (scope) {
1250
- params.set('scope', scope);
1344
+ consumePendingLogin(state) {
1345
+ const key = `${this.STATE_PREFIX}${state}`;
1346
+ const raw = localStorage.getItem(key);
1347
+ localStorage.removeItem(key);
1348
+ if (!raw) {
1349
+ return null;
1251
1350
  }
1252
- // Convenience OIDC options
1253
- const mergedAdditionalParams = Object.assign(Object.assign({}, ((_f = config.additionalParameters) !== null && _f !== void 0 ? _f : {})), ((_g = options.additionalParameters) !== null && _g !== void 0 ? _g : {}));
1254
- const loginHint = (_h = options.loginHint) !== null && _h !== void 0 ? _h : config.loginHint;
1255
- const prompt = (_j = options.prompt) !== null && _j !== void 0 ? _j : config.prompt;
1256
- if (loginHint && !('login_hint' in mergedAdditionalParams)) {
1257
- mergedAdditionalParams.login_hint = loginHint;
1351
+ try {
1352
+ return JSON.parse(raw);
1258
1353
  }
1259
- if (prompt && !('prompt' in mergedAdditionalParams)) {
1260
- mergedAdditionalParams.prompt = prompt;
1354
+ catch (err) {
1355
+ console.warn('Failed to parse pending OAuth2 login payload', err);
1356
+ return null;
1261
1357
  }
1262
- // Add PKCE for code flow
1263
- if (config.responseType === 'code' && config.pkceEnabled) {
1264
- const codeChallenge = await this.generateCodeChallenge(codeVerifier);
1265
- params.set('code_challenge', codeChallenge);
1266
- params.set('code_challenge_method', 'S256');
1358
+ }
1359
+ generateState() {
1360
+ return [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('');
1361
+ }
1362
+ generateCodeVerifier() {
1363
+ const array = new Uint8Array(64);
1364
+ crypto.getRandomValues(array);
1365
+ return Array.from(array)
1366
+ .map((b) => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'[b % 66])
1367
+ .join('');
1368
+ }
1369
+ async generateCodeChallenge(codeVerifier) {
1370
+ const encoder = new TextEncoder();
1371
+ const data = encoder.encode(codeVerifier);
1372
+ const digest = await crypto.subtle.digest('SHA-256', data);
1373
+ return this.base64UrlEncode(new Uint8Array(digest));
1374
+ }
1375
+ base64UrlEncode(buffer) {
1376
+ let binary = '';
1377
+ buffer.forEach((b) => (binary += String.fromCharCode(b)));
1378
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1379
+ }
1380
+ decodeIdToken(idToken) {
1381
+ const parts = idToken.split('.');
1382
+ if (parts.length < 2) {
1383
+ throw new Error('Invalid JWT: missing parts');
1384
+ }
1385
+ const payload = parts[1];
1386
+ const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
1387
+ const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
1388
+ const json = atob(padded);
1389
+ return JSON.parse(json);
1390
+ }
1391
+ getAccessTokenExpirationDate(providerId) {
1392
+ const tokens = this.getStoredTokens(providerId);
1393
+ if (!(tokens === null || tokens === void 0 ? void 0 : tokens.expiresAt))
1394
+ return { expirationDate: null };
1395
+ return { expirationDate: new Date(tokens.expiresAt).toISOString() };
1396
+ }
1397
+ isAccessTokenAvailable(providerId) {
1398
+ const tokens = this.getStoredTokens(providerId);
1399
+ return { isAvailable: !!(tokens === null || tokens === void 0 ? void 0 : tokens.accessToken) };
1400
+ }
1401
+ isAccessTokenExpired(providerId) {
1402
+ const tokens = this.getStoredTokens(providerId);
1403
+ if (!(tokens === null || tokens === void 0 ? void 0 : tokens.expiresAt))
1404
+ return { isExpired: true };
1405
+ return { isExpired: tokens.expiresAt <= Date.now() };
1406
+ }
1407
+ isRefreshTokenAvailable(providerId) {
1408
+ const tokens = this.getStoredTokens(providerId);
1409
+ return { isAvailable: !!(tokens === null || tokens === void 0 ? void 0 : tokens.refreshToken) };
1410
+ }
1411
+ }
1412
+
1413
+ class TwitterSocialLogin extends BaseSocialLogin {
1414
+ constructor() {
1415
+ super(...arguments);
1416
+ this.clientId = null;
1417
+ this.redirectUrl = null;
1418
+ this.defaultScopes = ['tweet.read', 'users.read'];
1419
+ this.forceLogin = false;
1420
+ this.TOKENS_KEY = 'capgo_social_login_twitter_tokens_v1';
1421
+ this.STATE_PREFIX = 'capgo_social_login_twitter_state_';
1422
+ }
1423
+ async initialize(clientId, redirectUrl, defaultScopes, forceLogin, audience) {
1424
+ this.clientId = clientId;
1425
+ this.redirectUrl = redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : null;
1426
+ if (defaultScopes === null || defaultScopes === void 0 ? void 0 : defaultScopes.length) {
1427
+ this.defaultScopes = defaultScopes;
1267
1428
  }
1268
- // Add merged additional parameters
1269
- for (const [key, value] of Object.entries(mergedAdditionalParams)) {
1270
- if (value !== undefined) {
1271
- params.set(key, value);
1272
- }
1429
+ this.forceLogin = forceLogin !== null && forceLogin !== void 0 ? forceLogin : false;
1430
+ this.audience = audience !== null && audience !== void 0 ? audience : undefined;
1431
+ }
1432
+ async login(options) {
1433
+ var _a, _b, _c, _d, _e, _f;
1434
+ if (!this.clientId) {
1435
+ throw new Error('Twitter Client ID not configured. Call initialize() first.');
1273
1436
  }
1274
- // Store pending login state
1437
+ const redirectUri = (_b = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : this.redirectUrl) !== null && _b !== void 0 ? _b : window.location.origin + window.location.pathname;
1438
+ const scopes = ((_c = options.scopes) === null || _c === void 0 ? void 0 : _c.length) ? options.scopes : this.defaultScopes;
1439
+ const state = (_d = options.state) !== null && _d !== void 0 ? _d : this.generateState();
1440
+ const codeVerifier = (_e = options.codeVerifier) !== null && _e !== void 0 ? _e : this.generateCodeVerifier();
1441
+ const codeChallenge = await this.generateCodeChallenge(codeVerifier);
1275
1442
  this.persistPendingLogin(state, {
1276
- providerId,
1443
+ clientId: this.clientId,
1277
1444
  codeVerifier,
1278
1445
  redirectUri,
1279
- scope,
1446
+ scopes,
1280
1447
  });
1281
- localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'oauth2', providerId, state }));
1282
- if (!config.authorizationBaseUrl) {
1283
- throw new Error(`OAuth2 provider '${providerId}' is missing authorizationBaseUrl (discovery may have failed).`);
1284
- }
1285
- const authUrl = `${config.authorizationBaseUrl}?${params.toString()}`;
1286
- if (config.logsEnabled) {
1287
- console.log(`[OAuth2:${providerId}] Opening authorization URL:`, authUrl);
1448
+ localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'twitter', state }));
1449
+ const params = new URLSearchParams({
1450
+ response_type: 'code',
1451
+ client_id: this.clientId,
1452
+ redirect_uri: redirectUri,
1453
+ scope: scopes.join(' '),
1454
+ state,
1455
+ code_challenge: codeChallenge,
1456
+ code_challenge_method: 'S256',
1457
+ });
1458
+ if (((_f = options.forceLogin) !== null && _f !== void 0 ? _f : this.forceLogin) === true) {
1459
+ params.set('force_login', 'true');
1288
1460
  }
1289
- if (options.flow === 'redirect') {
1290
- // Trigger a full-page redirect. The promise will not resolve because the page navigates away.
1291
- window.location.assign(authUrl);
1292
- // eslint-disable-next-line @typescript-eslint/no-empty-function
1293
- return new Promise(() => { });
1461
+ if (this.audience) {
1462
+ params.set('audience', this.audience);
1294
1463
  }
1295
- // Open popup window
1464
+ const authUrl = `https://x.com/i/oauth2/authorize?${params.toString()}`;
1296
1465
  const width = 500;
1297
1466
  const height = 650;
1298
1467
  const left = window.screenX + (window.outerWidth - width) / 2;
1299
1468
  const top = window.screenY + (window.outerHeight - height) / 2;
1300
- const popup = window.open(authUrl, 'OAuth2Login', `width=${width},height=${height},left=${left},top=${top},popup=1`);
1469
+ const popup = window.open(authUrl, 'XLogin', `width=${width},height=${height},left=${left},top=${top},popup=1`);
1301
1470
  return new Promise((resolve, reject) => {
1302
1471
  if (!popup) {
1303
1472
  reject(new Error('Unable to open login window. Please allow popups.'));
1304
1473
  return;
1305
1474
  }
1306
1475
  // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)
1307
- const channelName = `oauth2_${state}`;
1476
+ const channelName = `twitter_oauth_${state}`;
1308
1477
  let broadcastChannel = null;
1309
1478
  try {
1310
1479
  broadcastChannel = new BroadcastChannel(channelName);
1311
1480
  }
1312
1481
  catch (_a) {
1313
1482
  // BroadcastChannel not supported, fall back to postMessage only
1314
- if (config.logsEnabled) {
1315
- console.log(`[OAuth2:${providerId}] BroadcastChannel not supported, using postMessage only`);
1316
- }
1317
1483
  }
1318
1484
  const cleanup = (messageHandler, timeoutHandle, intervalHandle) => {
1319
1485
  window.removeEventListener('message', messageHandler);
@@ -1325,28 +1491,24 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1325
1491
  };
1326
1492
  const handleOAuthMessage = (data) => {
1327
1493
  if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
1328
- if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'oauth2') {
1329
- return false;
1330
- }
1331
- // Check providerId matches if present
1332
- if ((data === null || data === void 0 ? void 0 : data.providerId) && data.providerId !== providerId) {
1494
+ if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'twitter') {
1333
1495
  return false;
1334
1496
  }
1335
1497
  cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1336
1498
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
1337
1499
  const _a = data, { provider: _ignoredProvider, type: _ignoredType } = _a, payload = __rest(_a, ["provider", "type"]);
1338
1500
  resolve({
1339
- provider: 'oauth2',
1501
+ provider: 'twitter',
1340
1502
  result: payload,
1341
1503
  });
1342
1504
  return true;
1343
1505
  }
1344
1506
  else if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
1345
- if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'oauth2') {
1507
+ if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'twitter') {
1346
1508
  return false;
1347
1509
  }
1348
1510
  cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1349
- reject(inferUserCancelledError(data.error || 'OAuth2 login was cancelled.'));
1511
+ reject(inferUserCancelledError(data.error || 'Twitter login was cancelled.'));
1350
1512
  return true;
1351
1513
  }
1352
1514
  return false;
@@ -1372,136 +1534,57 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1372
1534
  catch (_a) {
1373
1535
  // Ignore cross-origin errors when closing
1374
1536
  }
1375
- reject(new Error('OAuth2 login timed out.'));
1537
+ reject(new Error('Twitter login timed out.'));
1376
1538
  }, 300000);
1377
1539
  const popupClosedInterval = window.setInterval(() => {
1378
1540
  try {
1379
1541
  // Check if popup is closed - this may throw cross-origin errors for some providers
1380
1542
  if (popup.closed) {
1381
1543
  cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1382
- reject(createUserCancelledError('OAuth2 login window was closed.'));
1544
+ reject(createUserCancelledError('Twitter login window was closed.'));
1383
1545
  }
1384
1546
  }
1385
1547
  catch (_a) {
1386
1548
  // Cross-origin error when checking popup.closed - this happens when the popup
1387
1549
  // navigates to a third-party OAuth provider with strict security settings.
1388
- // We can't detect if the window was closed, so we just rely on the timeout
1389
- // and message handlers. Clear the interval to avoid repeated errors.
1550
+ // We can't detect if the window was closed, so we rely on timeout and message handlers.
1390
1551
  clearInterval(popupClosedInterval);
1391
- if (config.logsEnabled) {
1392
- console.log(`[OAuth2:${providerId}] Cannot check popup.closed due to cross-origin restrictions. ` +
1393
- 'Relying on message handlers and timeout.');
1394
- }
1395
1552
  }
1396
1553
  }, 1000);
1397
1554
  });
1398
1555
  }
1399
- async logout(providerId) {
1400
- await this.ensureDiscovered(providerId);
1401
- const config = this.providers.get(providerId);
1402
- const stored = this.getStoredTokens(providerId);
1403
- localStorage.removeItem(this.getTokensKey(providerId));
1404
- // If logout URL is configured, build an end-session URL (OIDC) when possible.
1405
- if (config === null || config === void 0 ? void 0 : config.logoutUrl) {
1406
- try {
1407
- const url = new URL(config.logoutUrl);
1408
- if (stored === null || stored === void 0 ? void 0 : stored.idToken) {
1409
- url.searchParams.set('id_token_hint', stored.idToken);
1410
- }
1411
- const postLogout = config.postLogoutRedirectUrl;
1412
- if (postLogout) {
1413
- url.searchParams.set('post_logout_redirect_uri', postLogout);
1414
- }
1415
- if (config.additionalLogoutParameters) {
1416
- for (const [k, v] of Object.entries(config.additionalLogoutParameters)) {
1417
- url.searchParams.set(k, v);
1418
- }
1419
- }
1420
- window.open(url.toString(), '_blank');
1421
- }
1422
- catch (_a) {
1423
- window.open(config.logoutUrl, '_blank');
1424
- }
1425
- }
1556
+ async logout() {
1557
+ localStorage.removeItem(this.TOKENS_KEY);
1426
1558
  }
1427
- async isLoggedIn(providerId) {
1428
- const tokens = this.getStoredTokens(providerId);
1559
+ async isLoggedIn() {
1560
+ const tokens = this.getStoredTokens();
1429
1561
  if (!tokens) {
1430
1562
  return { isLoggedIn: false };
1431
1563
  }
1432
1564
  const isValid = tokens.expiresAt > Date.now();
1433
1565
  if (!isValid) {
1434
- localStorage.removeItem(this.getTokensKey(providerId));
1566
+ localStorage.removeItem(this.TOKENS_KEY);
1435
1567
  }
1436
1568
  return { isLoggedIn: isValid };
1437
1569
  }
1438
- async getAuthorizationCode(providerId) {
1439
- const tokens = this.getStoredTokens(providerId);
1570
+ async getAuthorizationCode() {
1571
+ const tokens = this.getStoredTokens();
1440
1572
  if (!tokens) {
1441
- throw new Error(`OAuth2 access token is not available for provider '${providerId}'.`);
1573
+ throw new Error('Twitter access token is not available.');
1442
1574
  }
1443
1575
  return {
1444
1576
  accessToken: tokens.accessToken,
1445
- jwt: tokens.idToken,
1446
1577
  };
1447
1578
  }
1448
- async refresh(providerId) {
1449
- await this.refreshToken(providerId);
1450
- }
1451
- async refreshToken(providerId, refreshToken, additionalParameters) {
1452
- var _a, _b, _c, _d, _e, _f;
1453
- await this.ensureDiscovered(providerId);
1454
- const config = this.getProvider(providerId);
1455
- const stored = this.getStoredTokens(providerId);
1456
- const effectiveRefreshToken = refreshToken !== null && refreshToken !== void 0 ? refreshToken : stored === null || stored === void 0 ? void 0 : stored.refreshToken;
1457
- if (!effectiveRefreshToken) {
1458
- throw new Error(`No OAuth2 refresh token is available for provider '${providerId}'. Include offline_access scope to receive one.`);
1459
- }
1460
- if (!config.accessTokenEndpoint) {
1461
- throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1462
- }
1463
- const tokenResponse = await this.refreshWithRefreshToken(providerId, effectiveRefreshToken, additionalParameters);
1464
- const expiresAt = tokenResponse.expires_in ? Date.now() + tokenResponse.expires_in * 1000 : Date.now() + 3600000;
1465
- const scopeArray = (_c = (_b = (_a = tokenResponse.scope) === null || _a === void 0 ? void 0 : _a.split(' ').filter(Boolean)) !== null && _b !== void 0 ? _b : stored === null || stored === void 0 ? void 0 : stored.scope) !== null && _c !== void 0 ? _c : [];
1466
- // Fetch resource data if configured
1467
- let resourceData = null;
1468
- if (config.resourceUrl) {
1469
- resourceData = await this.fetchResource(providerId, tokenResponse.access_token);
1579
+ async refresh() {
1580
+ const tokens = this.getStoredTokens();
1581
+ if (!(tokens === null || tokens === void 0 ? void 0 : tokens.refreshToken)) {
1582
+ throw new Error('No Twitter refresh token is available. Include offline.access scope to receive one.');
1470
1583
  }
1471
- const nextRefreshToken = (_d = tokenResponse.refresh_token) !== null && _d !== void 0 ? _d : effectiveRefreshToken;
1472
- this.persistTokens(providerId, {
1473
- accessToken: tokenResponse.access_token,
1474
- refreshToken: nextRefreshToken,
1475
- idToken: tokenResponse.id_token,
1476
- expiresAt,
1477
- scope: scopeArray,
1478
- tokenType: tokenResponse.token_type,
1479
- });
1480
- return {
1481
- providerId,
1482
- accessToken: {
1483
- token: tokenResponse.access_token,
1484
- tokenType: tokenResponse.token_type,
1485
- expires: new Date(expiresAt).toISOString(),
1486
- refreshToken: nextRefreshToken,
1487
- },
1488
- idToken: (_e = tokenResponse.id_token) !== null && _e !== void 0 ? _e : null,
1489
- refreshToken: nextRefreshToken !== null && nextRefreshToken !== void 0 ? nextRefreshToken : null,
1490
- resourceData,
1491
- scope: scopeArray,
1492
- tokenType: tokenResponse.token_type,
1493
- expiresIn: (_f = tokenResponse.expires_in) !== null && _f !== void 0 ? _f : null,
1494
- };
1584
+ await this.refreshWithRefreshToken(tokens.refreshToken);
1495
1585
  }
1496
1586
  async handleOAuthRedirect(url, expectedState) {
1497
- var _a, _b, _c, _d, _e;
1498
- // Check both query params and hash fragment
1499
- const params = new URLSearchParams(url.search);
1500
- const hashParams = new URLSearchParams(url.hash.slice(1));
1501
- // Merge params, hash takes priority (for implicit flow)
1502
- hashParams.forEach((value, key) => {
1503
- params.set(key, value);
1504
- });
1587
+ const params = url.searchParams;
1505
1588
  const stateFromUrl = expectedState !== null && expectedState !== void 0 ? expectedState : params.get('state');
1506
1589
  if (!stateFromUrl) {
1507
1590
  return null;
@@ -1509,77 +1592,46 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1509
1592
  const pending = this.consumePendingLogin(stateFromUrl);
1510
1593
  if (!pending) {
1511
1594
  localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1512
- return { error: 'OAuth2 login session expired or state mismatch.' };
1513
- }
1514
- const { providerId } = pending;
1515
- await this.ensureDiscovered(providerId);
1516
- const config = this.providers.get(providerId);
1517
- if (!config) {
1518
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1519
- return { error: `OAuth2 provider '${providerId}' configuration not found.` };
1595
+ return { error: 'Twitter login session expired or state mismatch.' };
1520
1596
  }
1521
1597
  const error = params.get('error');
1522
1598
  if (error) {
1523
1599
  localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1524
1600
  return { error: params.get('error_description') || error };
1525
1601
  }
1602
+ const code = params.get('code');
1603
+ if (!code) {
1604
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1605
+ return { error: 'Twitter authorization code missing from redirect.' };
1606
+ }
1526
1607
  try {
1527
- let tokenResponse;
1528
- // Check response type
1529
- if (params.has('code')) {
1530
- // Authorization code flow
1531
- const code = params.get('code');
1532
- if (!code) {
1533
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1534
- return { error: 'OAuth2 authorization code missing from redirect.' };
1535
- }
1536
- tokenResponse = await this.exchangeAuthorizationCode(providerId, code, pending);
1537
- }
1538
- else if (params.has('access_token')) {
1539
- // Implicit flow
1540
- tokenResponse = {
1541
- access_token: params.get('access_token'),
1542
- token_type: params.get('token_type') || 'bearer',
1543
- expires_in: params.has('expires_in') ? parseInt(params.get('expires_in'), 10) : undefined,
1544
- scope: params.get('scope') || undefined,
1545
- id_token: params.get('id_token') || undefined,
1546
- };
1547
- }
1548
- else {
1549
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1550
- return { error: 'No authorization code or access token in redirect.' };
1551
- }
1552
- const expiresAt = tokenResponse.expires_in ? Date.now() + tokenResponse.expires_in * 1000 : Date.now() + 3600000;
1553
- const scopeArray = (_b = (_a = tokenResponse.scope) === null || _a === void 0 ? void 0 : _a.split(' ').filter(Boolean)) !== null && _b !== void 0 ? _b : [];
1554
- // Fetch resource data if configured
1555
- let resourceData = null;
1556
- if (config.resourceUrl) {
1557
- resourceData = await this.fetchResource(providerId, tokenResponse.access_token);
1558
- }
1559
- this.persistTokens(providerId, {
1560
- accessToken: tokenResponse.access_token,
1561
- refreshToken: tokenResponse.refresh_token,
1562
- idToken: tokenResponse.id_token,
1608
+ const tokens = await this.exchangeAuthorizationCode(code, pending);
1609
+ const profile = await this.fetchProfile(tokens.access_token);
1610
+ const expiresAt = Date.now() + tokens.expires_in * 1000;
1611
+ const scopeArray = tokens.scope.split(' ').filter(Boolean);
1612
+ this.persistTokens({
1613
+ accessToken: tokens.access_token,
1614
+ refreshToken: tokens.refresh_token,
1563
1615
  expiresAt,
1564
1616
  scope: scopeArray,
1565
- tokenType: tokenResponse.token_type,
1617
+ tokenType: tokens.token_type,
1618
+ userId: profile.id,
1619
+ profile,
1566
1620
  });
1567
1621
  return {
1568
- provider: 'oauth2',
1622
+ provider: 'twitter',
1569
1623
  result: {
1570
- providerId,
1571
1624
  accessToken: {
1572
- token: tokenResponse.access_token,
1573
- tokenType: tokenResponse.token_type,
1625
+ token: tokens.access_token,
1626
+ tokenType: tokens.token_type,
1574
1627
  expires: new Date(expiresAt).toISOString(),
1575
- refreshToken: tokenResponse.refresh_token,
1576
- },
1577
- idToken: (_c = tokenResponse.id_token) !== null && _c !== void 0 ? _c : null,
1578
- refreshToken: (_d = tokenResponse.refresh_token) !== null && _d !== void 0 ? _d : null,
1579
- resourceData,
1628
+ userId: profile.id,
1629
+ },
1630
+ refreshToken: tokens.refresh_token,
1580
1631
  scope: scopeArray,
1581
- tokenType: tokenResponse.token_type,
1582
- expiresIn: (_e = tokenResponse.expires_in) !== null && _e !== void 0 ? _e : null,
1632
+ tokenType: tokens.token_type,
1633
+ expiresIn: tokens.expires_in,
1634
+ profile,
1583
1635
  },
1584
1636
  };
1585
1637
  }
@@ -1587,38 +1639,21 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1587
1639
  if (err instanceof Error) {
1588
1640
  return { error: err.message };
1589
1641
  }
1590
- return { error: 'OAuth2 login failed unexpectedly.' };
1642
+ return { error: 'Twitter login failed unexpectedly.' };
1591
1643
  }
1592
1644
  finally {
1593
1645
  localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1594
1646
  }
1595
1647
  }
1596
- async exchangeAuthorizationCode(providerId, code, pending) {
1597
- const config = this.getProvider(providerId);
1598
- if (!config.accessTokenEndpoint) {
1599
- throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1600
- }
1648
+ async exchangeAuthorizationCode(code, pending) {
1601
1649
  const params = new URLSearchParams({
1602
1650
  grant_type: 'authorization_code',
1603
- client_id: config.appId,
1651
+ client_id: pending.clientId,
1604
1652
  code,
1605
1653
  redirect_uri: pending.redirectUri,
1654
+ code_verifier: pending.codeVerifier,
1606
1655
  });
1607
- if (config.pkceEnabled) {
1608
- params.set('code_verifier', pending.codeVerifier);
1609
- }
1610
- if (config.clientSecret) {
1611
- params.set('client_secret', config.clientSecret);
1612
- }
1613
- if (config.additionalTokenParameters) {
1614
- for (const [k, v] of Object.entries(config.additionalTokenParameters)) {
1615
- params.set(k, v);
1616
- }
1617
- }
1618
- if (config.logsEnabled) {
1619
- console.log(`[OAuth2:${providerId}] Exchanging code at:`, config.accessTokenEndpoint);
1620
- }
1621
- const response = await fetch(config.accessTokenEndpoint, {
1656
+ const response = await fetch('https://api.x.com/2/oauth2/token', {
1622
1657
  method: 'POST',
1623
1658
  headers: {
1624
1659
  'Content-Type': 'application/x-www-form-urlencoded',
@@ -1627,34 +1662,18 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1627
1662
  });
1628
1663
  if (!response.ok) {
1629
1664
  const text = await response.text();
1630
- throw new Error(`OAuth2 token exchange failed (${response.status}): ${text}`);
1665
+ throw new Error(`Twitter token exchange failed (${response.status}): ${text}`);
1631
1666
  }
1632
1667
  return (await response.json());
1633
1668
  }
1634
- async refreshWithRefreshToken(providerId, refreshToken, additionalParameters) {
1635
- const config = this.getProvider(providerId);
1636
- if (!config.accessTokenEndpoint) {
1637
- throw new Error(`No accessTokenEndpoint configured for provider '${providerId}'.`);
1638
- }
1669
+ async refreshWithRefreshToken(refreshToken) {
1670
+ var _a, _b;
1639
1671
  const params = new URLSearchParams({
1640
1672
  grant_type: 'refresh_token',
1641
1673
  refresh_token: refreshToken,
1642
- client_id: config.appId,
1674
+ client_id: (_a = this.clientId) !== null && _a !== void 0 ? _a : '',
1643
1675
  });
1644
- if (config.clientSecret) {
1645
- params.set('client_secret', config.clientSecret);
1646
- }
1647
- if (config.additionalTokenParameters) {
1648
- for (const [k, v] of Object.entries(config.additionalTokenParameters)) {
1649
- params.set(k, v);
1650
- }
1651
- }
1652
- if (additionalParameters) {
1653
- for (const [k, v] of Object.entries(additionalParameters)) {
1654
- params.set(k, v);
1655
- }
1656
- }
1657
- const response = await fetch(config.accessTokenEndpoint, {
1676
+ const response = await fetch('https://api.x.com/2/oauth2/token', {
1658
1677
  method: 'POST',
1659
1678
  headers: {
1660
1679
  'Content-Type': 'application/x-www-form-urlencoded',
@@ -1663,35 +1682,52 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1663
1682
  });
1664
1683
  if (!response.ok) {
1665
1684
  const text = await response.text();
1666
- throw new Error(`OAuth2 refresh failed (${response.status}): ${text}`);
1685
+ throw new Error(`Twitter refresh failed (${response.status}): ${text}`);
1667
1686
  }
1668
- return (await response.json());
1687
+ const tokens = (await response.json());
1688
+ const profile = await this.fetchProfile(tokens.access_token);
1689
+ const expiresAt = Date.now() + tokens.expires_in * 1000;
1690
+ const scopeArray = tokens.scope.split(' ').filter(Boolean);
1691
+ this.persistTokens({
1692
+ accessToken: tokens.access_token,
1693
+ refreshToken: (_b = tokens.refresh_token) !== null && _b !== void 0 ? _b : refreshToken,
1694
+ expiresAt,
1695
+ scope: scopeArray,
1696
+ tokenType: tokens.token_type,
1697
+ userId: profile.id,
1698
+ profile,
1699
+ });
1669
1700
  }
1670
- async fetchResource(providerId, accessToken) {
1671
- const config = this.getProvider(providerId);
1672
- if (!config.resourceUrl) {
1673
- throw new Error(`No resourceUrl configured for provider '${providerId}'.`);
1674
- }
1675
- const headers = {
1676
- Authorization: `Bearer ${accessToken}`,
1677
- };
1678
- if (config.additionalResourceHeaders) {
1679
- Object.assign(headers, config.additionalResourceHeaders);
1680
- }
1681
- const response = await fetch(config.resourceUrl, {
1682
- headers,
1701
+ async fetchProfile(accessToken) {
1702
+ var _a, _b, _c, _d;
1703
+ const fields = ['profile_image_url', 'verified', 'name', 'username'];
1704
+ const response = await fetch(`https://api.x.com/2/users/me?user.fields=${fields.join(',')}`, {
1705
+ headers: {
1706
+ Authorization: `Bearer ${accessToken}`,
1707
+ },
1683
1708
  });
1684
1709
  if (!response.ok) {
1685
1710
  const text = await response.text();
1686
- throw new Error(`Unable to fetch OAuth2 resource (${response.status}): ${text}`);
1711
+ throw new Error(`Unable to fetch Twitter profile (${response.status}): ${text}`);
1687
1712
  }
1688
- return (await response.json());
1713
+ const payload = (await response.json());
1714
+ if (!payload.data) {
1715
+ throw new Error('Twitter profile payload is missing data.');
1716
+ }
1717
+ return {
1718
+ id: payload.data.id,
1719
+ username: payload.data.username,
1720
+ name: (_a = payload.data.name) !== null && _a !== void 0 ? _a : null,
1721
+ profileImageUrl: (_b = payload.data.profile_image_url) !== null && _b !== void 0 ? _b : null,
1722
+ verified: (_c = payload.data.verified) !== null && _c !== void 0 ? _c : false,
1723
+ email: (_d = payload.data.email) !== null && _d !== void 0 ? _d : null,
1724
+ };
1689
1725
  }
1690
- persistTokens(providerId, tokens) {
1691
- localStorage.setItem(this.getTokensKey(providerId), JSON.stringify(tokens));
1726
+ persistTokens(tokens) {
1727
+ localStorage.setItem(this.TOKENS_KEY, JSON.stringify(tokens));
1692
1728
  }
1693
- getStoredTokens(providerId) {
1694
- const raw = localStorage.getItem(this.getTokensKey(providerId));
1729
+ getStoredTokens() {
1730
+ const raw = localStorage.getItem(this.TOKENS_KEY);
1695
1731
  if (!raw) {
1696
1732
  return null;
1697
1733
  }
@@ -1699,7 +1735,7 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1699
1735
  return JSON.parse(raw);
1700
1736
  }
1701
1737
  catch (err) {
1702
- console.warn(`Failed to parse stored OAuth2 tokens for provider '${providerId}'`, err);
1738
+ console.warn('Failed to parse stored Twitter tokens', err);
1703
1739
  return null;
1704
1740
  }
1705
1741
  }
@@ -1717,7 +1753,7 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1717
1753
  return JSON.parse(raw);
1718
1754
  }
1719
1755
  catch (err) {
1720
- console.warn('Failed to parse pending OAuth2 login payload', err);
1756
+ console.warn('Failed to parse pending Twitter login payload', err);
1721
1757
  return null;
1722
1758
  }
1723
1759
  }
@@ -1742,406 +1778,633 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1742
1778
  buffer.forEach((b) => (binary += String.fromCharCode(b)));
1743
1779
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1744
1780
  }
1745
- decodeIdToken(idToken) {
1746
- const parts = idToken.split('.');
1747
- if (parts.length < 2) {
1748
- throw new Error('Invalid JWT: missing parts');
1749
- }
1750
- const payload = parts[1];
1751
- const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
1752
- const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
1753
- const json = atob(padded);
1754
- return JSON.parse(json);
1781
+ }
1782
+
1783
+ async function parseRedirectResult() {
1784
+ var _a;
1785
+ const url = new URL(window.location.href);
1786
+ const stateRaw = localStorage.getItem(OAUTH_STATE_KEY);
1787
+ let provider = null;
1788
+ let state;
1789
+ let nonce;
1790
+ if (stateRaw) {
1791
+ try {
1792
+ const parsed = JSON.parse(stateRaw);
1793
+ provider = (_a = parsed.provider) !== null && _a !== void 0 ? _a : null;
1794
+ state = parsed.state;
1795
+ nonce = parsed.nonce;
1796
+ }
1797
+ catch (_b) {
1798
+ provider = stateRaw === 'true' ? 'google' : null;
1799
+ }
1800
+ }
1801
+ const googleProvider = new GoogleSocialLogin();
1802
+ const oauth2Provider = new OAuth2SocialLogin();
1803
+ const twitterProvider = new TwitterSocialLogin();
1804
+ let result = null;
1805
+ switch (provider) {
1806
+ case 'twitter':
1807
+ result = await twitterProvider.handleOAuthRedirect(url, state);
1808
+ break;
1809
+ case 'oauth2':
1810
+ result = await oauth2Provider.handleOAuthRedirect(url, state);
1811
+ break;
1812
+ case 'google':
1813
+ default:
1814
+ result = googleProvider.handleOAuthRedirect(url);
1815
+ break;
1816
+ }
1817
+ return { provider, state, nonce, result };
1818
+ }
1819
+ function buildOAuthMessage(parsed) {
1820
+ const { result } = parsed;
1821
+ if (!result)
1822
+ return null;
1823
+ if ('error' in result) {
1824
+ const error = inferUserCancelledError(result.error);
1825
+ return Object.assign({ type: 'oauth-error', provider: parsed.provider, error: error.message }, (error.code ? { code: error.code } : null));
1826
+ }
1827
+ return Object.assign({ type: 'oauth-response', provider: result.provider }, result.result);
1828
+ }
1829
+ async function finishOAuthRedirectInPopup() {
1830
+ var _a, _b, _c, _d, _e;
1831
+ const parsed = await parseRedirectResult();
1832
+ const nonceOrState = (_a = parsed.nonce) !== null && _a !== void 0 ? _a : parsed.state;
1833
+ const message = buildOAuthMessage(parsed);
1834
+ if (!message) {
1835
+ // OAuth params may not be ready yet (SPA router). Retry briefly.
1836
+ if (shouldAutoFinishOAuthRedirect()) {
1837
+ await new Promise((resolve) => setTimeout(resolve, 100));
1838
+ const retryParsed = await parseRedirectResult();
1839
+ const retryMessage = buildOAuthMessage(retryParsed);
1840
+ if (retryMessage) {
1841
+ deliverOAuthResult((_b = retryParsed.provider) !== null && _b !== void 0 ? _b : 'google', (_c = retryParsed.nonce) !== null && _c !== void 0 ? _c : retryParsed.state, retryMessage);
1842
+ }
1843
+ else {
1844
+ deliverOAuthResult((_d = parsed.provider) !== null && _d !== void 0 ? _d : 'google', nonceOrState, {
1845
+ type: 'oauth-error',
1846
+ provider: parsed.provider,
1847
+ error: 'OAuth redirect did not contain expected parameters.',
1848
+ });
1849
+ }
1850
+ }
1851
+ }
1852
+ else {
1853
+ deliverOAuthResult((_e = parsed.provider) !== null && _e !== void 0 ? _e : 'google', nonceOrState, message);
1854
+ }
1855
+ clearOAuthPopupMarker();
1856
+ try {
1857
+ window.close();
1858
+ }
1859
+ catch (_f) {
1860
+ // Popup may not be allowed to close itself in some contexts
1861
+ }
1862
+ }
1863
+ function onHashChange() {
1864
+ if (!shouldAutoFinishOAuthRedirect())
1865
+ return;
1866
+ void finishOAuthRedirectInPopup();
1867
+ }
1868
+ function initOAuthPopupRedirectHandler() {
1869
+ if (typeof window === 'undefined')
1870
+ return;
1871
+ if (shouldAutoFinishOAuthRedirect()) {
1872
+ void finishOAuthRedirectInPopup();
1873
+ }
1874
+ // SPA routers may apply the OAuth hash after initial load
1875
+ window.addEventListener('hashchange', onHashChange);
1876
+ }
1877
+ // Auto-run on import so popup windows finish OAuth even before plugin lazy-load
1878
+ initOAuthPopupRedirectHandler();
1879
+
1880
+ const GOOGLE_OFFLINE_REFRESH_MESSAGE = "Google refresh() is not available when using offline mode. Offline mode only returns serverAuthCode for backend token exchange. Send serverAuthCode to your backend and refresh tokens there, or switch google.mode to 'online' for client-side refresh.";
1881
+ const rawSocialLogin = core.registerPlugin('SocialLogin', {
1882
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.SocialLoginWeb()),
1883
+ });
1884
+ class SocialLoginClient {
1885
+ constructor() {
1886
+ this.initialize = this.initialize.bind(this);
1887
+ this.refresh = this.refresh.bind(this);
1888
+ }
1889
+ async initialize(options) {
1890
+ await rawSocialLogin.initialize(options);
1891
+ this.initializeOptions = options;
1892
+ }
1893
+ async login(options) {
1894
+ return rawSocialLogin.login(options);
1895
+ }
1896
+ async logout(options) {
1897
+ return rawSocialLogin.logout(options);
1898
+ }
1899
+ async isLoggedIn(options) {
1900
+ return rawSocialLogin.isLoggedIn(options);
1901
+ }
1902
+ async getAuthorizationCode(options) {
1903
+ return rawSocialLogin.getAuthorizationCode(options);
1904
+ }
1905
+ async refresh(options) {
1906
+ var _a, _b;
1907
+ if (options.provider === 'google' && ((_b = (_a = this.initializeOptions) === null || _a === void 0 ? void 0 : _a.google) === null || _b === void 0 ? void 0 : _b.mode) === 'offline') {
1908
+ console.warn(`[SocialLogin] ${GOOGLE_OFFLINE_REFRESH_MESSAGE}`);
1909
+ }
1910
+ return rawSocialLogin.refresh(options);
1911
+ }
1912
+ async refreshToken(options) {
1913
+ return rawSocialLogin.refreshToken(options);
1914
+ }
1915
+ async handleRedirectCallback() {
1916
+ return rawSocialLogin.handleRedirectCallback();
1917
+ }
1918
+ async decodeIdToken(options) {
1919
+ return rawSocialLogin.decodeIdToken(options);
1920
+ }
1921
+ async getAccessTokenExpirationDate(options) {
1922
+ return rawSocialLogin.getAccessTokenExpirationDate(options);
1923
+ }
1924
+ async isAccessTokenAvailable(options) {
1925
+ return rawSocialLogin.isAccessTokenAvailable(options);
1926
+ }
1927
+ async isAccessTokenExpired(options) {
1928
+ return rawSocialLogin.isAccessTokenExpired(options);
1929
+ }
1930
+ async isRefreshTokenAvailable(options) {
1931
+ return rawSocialLogin.isRefreshTokenAvailable(options);
1932
+ }
1933
+ async providerSpecificCall(options) {
1934
+ return rawSocialLogin.providerSpecificCall(options);
1935
+ }
1936
+ async getPluginVersion() {
1937
+ return rawSocialLogin.getPluginVersion();
1938
+ }
1939
+ async openSecureWindow(options) {
1940
+ return rawSocialLogin.openSecureWindow(options);
1941
+ }
1942
+ }
1943
+ const SocialLoginBase = rawSocialLogin;
1944
+ const SocialLogin = new SocialLoginClient();
1945
+
1946
+ const AUTH_CONNECT_PROVIDERS = ['auth0', 'azure', 'cognito', 'okta', 'onelogin'];
1947
+ const DEFAULT_SCOPES = {
1948
+ auth0: 'openid profile email offline_access',
1949
+ azure: 'openid profile email',
1950
+ cognito: 'openid profile email',
1951
+ okta: 'openid profile email offline_access',
1952
+ onelogin: 'openid profile email',
1953
+ };
1954
+ const DEFAULT_RESOURCE_URLS = {
1955
+ azure: 'https://graph.microsoft.com/v1.0/me',
1956
+ };
1957
+ const DEFAULT_AUTHORITY_HOST = 'https://login.microsoftonline.com';
1958
+ const ensureProtocol = (value) => {
1959
+ if (value.startsWith('http://') || value.startsWith('https://')) {
1960
+ return value;
1961
+ }
1962
+ return `https://${value}`;
1963
+ };
1964
+ const trimTrailingSlash = (value) => value.replace(/\/+$/, '');
1965
+ const joinUrl = (base, path) => {
1966
+ const sanitizedBase = trimTrailingSlash(base);
1967
+ const sanitizedPath = path.replace(/^\/+/, '');
1968
+ return `${sanitizedBase}/${sanitizedPath}`;
1969
+ };
1970
+ const mergeRecords = (base, overrides) => {
1971
+ if (!base && !overrides) {
1972
+ return undefined;
1973
+ }
1974
+ return Object.assign(Object.assign({}, (base !== null && base !== void 0 ? base : {})), (overrides !== null && overrides !== void 0 ? overrides : {}));
1975
+ };
1976
+ const validatePreset = (providerId, preset) => {
1977
+ if (!preset.clientId) {
1978
+ throw new Error(`[authConnect] ${providerId} requires clientId.`);
1979
+ }
1980
+ if (!preset.redirectUrl) {
1981
+ throw new Error(`[authConnect] ${providerId} requires redirectUrl.`);
1982
+ }
1983
+ };
1984
+ const buildAuth0Config = (preset) => {
1985
+ validatePreset('auth0', preset);
1986
+ if (!preset.domain) {
1987
+ throw new Error('[authConnect] auth0 requires domain.');
1988
+ }
1989
+ const base = trimTrailingSlash(ensureProtocol(preset.domain));
1990
+ return buildConfigFromPreset('auth0', preset, {
1991
+ authorizationBaseUrl: joinUrl(base, 'authorize'),
1992
+ accessTokenEndpoint: joinUrl(base, 'oauth/token'),
1993
+ resourceUrl: joinUrl(base, 'userinfo'),
1994
+ logoutUrl: joinUrl(base, 'v2/logout'),
1995
+ additionalParameters: preset.audience ? { audience: preset.audience } : undefined,
1996
+ });
1997
+ };
1998
+ const buildAzureConfig = (preset) => {
1999
+ var _a, _b;
2000
+ validatePreset('azure', preset);
2001
+ const tenantId = (_a = preset.tenantId) !== null && _a !== void 0 ? _a : 'common';
2002
+ const authorityHost = trimTrailingSlash(ensureProtocol((_b = preset.authorityHost) !== null && _b !== void 0 ? _b : DEFAULT_AUTHORITY_HOST));
2003
+ const base = joinUrl(authorityHost, `${tenantId}/oauth2/v2.0`);
2004
+ return buildConfigFromPreset('azure', preset, {
2005
+ authorizationBaseUrl: joinUrl(base, 'authorize'),
2006
+ accessTokenEndpoint: joinUrl(base, 'token'),
2007
+ resourceUrl: DEFAULT_RESOURCE_URLS.azure,
2008
+ });
2009
+ };
2010
+ const buildCognitoConfig = (preset) => {
2011
+ validatePreset('cognito', preset);
2012
+ if (!preset.domain) {
2013
+ throw new Error('[authConnect] cognito requires domain.');
1755
2014
  }
1756
- getAccessTokenExpirationDate(providerId) {
1757
- const tokens = this.getStoredTokens(providerId);
1758
- if (!(tokens === null || tokens === void 0 ? void 0 : tokens.expiresAt))
1759
- return { expirationDate: null };
1760
- return { expirationDate: new Date(tokens.expiresAt).toISOString() };
2015
+ const base = trimTrailingSlash(ensureProtocol(preset.domain));
2016
+ return buildConfigFromPreset('cognito', preset, {
2017
+ authorizationBaseUrl: joinUrl(base, 'oauth2/authorize'),
2018
+ accessTokenEndpoint: joinUrl(base, 'oauth2/token'),
2019
+ resourceUrl: joinUrl(base, 'oauth2/userInfo'),
2020
+ logoutUrl: joinUrl(base, 'logout'),
2021
+ });
2022
+ };
2023
+ const buildOktaConfig = (preset) => {
2024
+ validatePreset('okta', preset);
2025
+ if (!preset.issuer) {
2026
+ throw new Error('[authConnect] okta requires issuer.');
1761
2027
  }
1762
- isAccessTokenAvailable(providerId) {
1763
- const tokens = this.getStoredTokens(providerId);
1764
- return { isAvailable: !!(tokens === null || tokens === void 0 ? void 0 : tokens.accessToken) };
2028
+ const base = trimTrailingSlash(ensureProtocol(preset.issuer));
2029
+ return buildConfigFromPreset('okta', preset, {
2030
+ authorizationBaseUrl: joinUrl(base, 'v1/authorize'),
2031
+ accessTokenEndpoint: joinUrl(base, 'v1/token'),
2032
+ resourceUrl: joinUrl(base, 'v1/userinfo'),
2033
+ logoutUrl: joinUrl(base, 'v1/logout'),
2034
+ });
2035
+ };
2036
+ const buildOneLoginConfig = (preset) => {
2037
+ validatePreset('onelogin', preset);
2038
+ if (!preset.issuer) {
2039
+ throw new Error('[authConnect] onelogin requires issuer.');
1765
2040
  }
1766
- isAccessTokenExpired(providerId) {
1767
- const tokens = this.getStoredTokens(providerId);
1768
- if (!(tokens === null || tokens === void 0 ? void 0 : tokens.expiresAt))
1769
- return { isExpired: true };
1770
- return { isExpired: tokens.expiresAt <= Date.now() };
2041
+ const base = trimTrailingSlash(ensureProtocol(preset.issuer));
2042
+ return buildConfigFromPreset('onelogin', preset, {
2043
+ authorizationBaseUrl: joinUrl(base, 'auth'),
2044
+ accessTokenEndpoint: joinUrl(base, 'token'),
2045
+ resourceUrl: joinUrl(base, 'me'),
2046
+ logoutUrl: joinUrl(base, 'logout'),
2047
+ });
2048
+ };
2049
+ const buildConfigFromPreset = (providerId, preset, defaults) => {
2050
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
2051
+ const additionalParameters = mergeRecords(defaults.additionalParameters, preset.additionalParameters);
2052
+ const additionalResourceHeaders = mergeRecords(defaults.additionalResourceHeaders, preset.additionalResourceHeaders);
2053
+ const config = {
2054
+ appId: preset.clientId,
2055
+ authorizationBaseUrl: (_b = (_a = preset.authorizationBaseUrl) !== null && _a !== void 0 ? _a : defaults.authorizationBaseUrl) !== null && _b !== void 0 ? _b : '',
2056
+ accessTokenEndpoint: (_c = preset.accessTokenEndpoint) !== null && _c !== void 0 ? _c : defaults.accessTokenEndpoint,
2057
+ redirectUrl: preset.redirectUrl,
2058
+ resourceUrl: (_d = preset.resourceUrl) !== null && _d !== void 0 ? _d : defaults.resourceUrl,
2059
+ responseType: (_f = (_e = preset.responseType) !== null && _e !== void 0 ? _e : defaults.responseType) !== null && _f !== void 0 ? _f : 'code',
2060
+ pkceEnabled: (_h = (_g = preset.pkceEnabled) !== null && _g !== void 0 ? _g : defaults.pkceEnabled) !== null && _h !== void 0 ? _h : true,
2061
+ scope: (_k = (_j = preset.scope) !== null && _j !== void 0 ? _j : defaults.scope) !== null && _k !== void 0 ? _k : DEFAULT_SCOPES[providerId],
2062
+ additionalParameters,
2063
+ additionalResourceHeaders,
2064
+ logoutUrl: (_l = preset.logoutUrl) !== null && _l !== void 0 ? _l : defaults.logoutUrl,
2065
+ logsEnabled: (_m = preset.logsEnabled) !== null && _m !== void 0 ? _m : defaults.logsEnabled,
2066
+ };
2067
+ if (!config.authorizationBaseUrl) {
2068
+ throw new Error(`[authConnect] ${providerId} authorizationBaseUrl is required.`);
1771
2069
  }
1772
- isRefreshTokenAvailable(providerId) {
1773
- const tokens = this.getStoredTokens(providerId);
1774
- return { isAvailable: !!(tokens === null || tokens === void 0 ? void 0 : tokens.refreshToken) };
2070
+ return config;
2071
+ };
2072
+ const buildAuthConnectProviders = (presets) => {
2073
+ if (!presets) {
2074
+ return {};
1775
2075
  }
1776
- }
1777
-
1778
- class TwitterSocialLogin extends BaseSocialLogin {
1779
- constructor() {
1780
- super(...arguments);
1781
- this.clientId = null;
1782
- this.redirectUrl = null;
1783
- this.defaultScopes = ['tweet.read', 'users.read'];
1784
- this.forceLogin = false;
1785
- this.TOKENS_KEY = 'capgo_social_login_twitter_tokens_v1';
1786
- this.STATE_PREFIX = 'capgo_social_login_twitter_state_';
2076
+ const providers = {};
2077
+ if (presets.auth0) {
2078
+ providers.auth0 = buildAuth0Config(presets.auth0);
1787
2079
  }
1788
- async initialize(clientId, redirectUrl, defaultScopes, forceLogin, audience) {
1789
- this.clientId = clientId;
1790
- this.redirectUrl = redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : null;
1791
- if (defaultScopes === null || defaultScopes === void 0 ? void 0 : defaultScopes.length) {
1792
- this.defaultScopes = defaultScopes;
1793
- }
1794
- this.forceLogin = forceLogin !== null && forceLogin !== void 0 ? forceLogin : false;
1795
- this.audience = audience !== null && audience !== void 0 ? audience : undefined;
2080
+ if (presets.azure) {
2081
+ providers.azure = buildAzureConfig(presets.azure);
1796
2082
  }
1797
- async login(options) {
1798
- var _a, _b, _c, _d, _e, _f;
1799
- if (!this.clientId) {
1800
- throw new Error('Twitter Client ID not configured. Call initialize() first.');
1801
- }
1802
- const redirectUri = (_b = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : this.redirectUrl) !== null && _b !== void 0 ? _b : window.location.origin + window.location.pathname;
1803
- const scopes = ((_c = options.scopes) === null || _c === void 0 ? void 0 : _c.length) ? options.scopes : this.defaultScopes;
1804
- const state = (_d = options.state) !== null && _d !== void 0 ? _d : this.generateState();
1805
- const codeVerifier = (_e = options.codeVerifier) !== null && _e !== void 0 ? _e : this.generateCodeVerifier();
1806
- const codeChallenge = await this.generateCodeChallenge(codeVerifier);
1807
- this.persistPendingLogin(state, {
1808
- clientId: this.clientId,
1809
- codeVerifier,
1810
- redirectUri,
1811
- scopes,
1812
- });
1813
- localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'twitter', state }));
1814
- const params = new URLSearchParams({
1815
- response_type: 'code',
1816
- client_id: this.clientId,
1817
- redirect_uri: redirectUri,
1818
- scope: scopes.join(' '),
1819
- state,
1820
- code_challenge: codeChallenge,
1821
- code_challenge_method: 'S256',
1822
- });
1823
- if (((_f = options.forceLogin) !== null && _f !== void 0 ? _f : this.forceLogin) === true) {
1824
- params.set('force_login', 'true');
1825
- }
1826
- if (this.audience) {
1827
- params.set('audience', this.audience);
1828
- }
1829
- const authUrl = `https://x.com/i/oauth2/authorize?${params.toString()}`;
1830
- const width = 500;
1831
- const height = 650;
1832
- const left = window.screenX + (window.outerWidth - width) / 2;
1833
- const top = window.screenY + (window.outerHeight - height) / 2;
1834
- const popup = window.open(authUrl, 'XLogin', `width=${width},height=${height},left=${left},top=${top},popup=1`);
1835
- return new Promise((resolve, reject) => {
1836
- if (!popup) {
1837
- reject(new Error('Unable to open login window. Please allow popups.'));
1838
- return;
1839
- }
1840
- // Use BroadcastChannel for cross-origin communication (works when postMessage doesn't)
1841
- const channelName = `twitter_oauth_${state}`;
1842
- let broadcastChannel = null;
1843
- try {
1844
- broadcastChannel = new BroadcastChannel(channelName);
1845
- }
1846
- catch (_a) {
1847
- // BroadcastChannel not supported, fall back to postMessage only
1848
- }
1849
- const cleanup = (messageHandler, timeoutHandle, intervalHandle) => {
1850
- window.removeEventListener('message', messageHandler);
1851
- clearTimeout(timeoutHandle);
1852
- clearInterval(intervalHandle);
1853
- if (broadcastChannel) {
1854
- broadcastChannel.close();
1855
- }
1856
- };
1857
- const handleOAuthMessage = (data) => {
1858
- if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-response') {
1859
- if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'twitter') {
1860
- return false;
1861
- }
1862
- cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1863
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1864
- const _a = data, { provider: _ignoredProvider, type: _ignoredType } = _a, payload = __rest(_a, ["provider", "type"]);
1865
- resolve({
1866
- provider: 'twitter',
1867
- result: payload,
1868
- });
1869
- return true;
1870
- }
1871
- else if ((data === null || data === void 0 ? void 0 : data.type) === 'oauth-error') {
1872
- if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'twitter') {
1873
- return false;
1874
- }
1875
- cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1876
- reject(inferUserCancelledError(data.error || 'Twitter login was cancelled.'));
1877
- return true;
1878
- }
1879
- return false;
1880
- };
1881
- // Listen for BroadcastChannel messages
1882
- if (broadcastChannel) {
1883
- broadcastChannel.onmessage = (event) => {
1884
- handleOAuthMessage(event.data);
1885
- };
1886
- }
1887
- const messageHandler = (event) => {
1888
- if (event.origin !== window.location.origin) {
1889
- return;
1890
- }
1891
- handleOAuthMessage(event.data);
1892
- };
1893
- window.addEventListener('message', messageHandler);
1894
- const timeoutHandle = window.setTimeout(() => {
1895
- cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1896
- try {
1897
- popup.close();
1898
- }
1899
- catch (_a) {
1900
- // Ignore cross-origin errors when closing
1901
- }
1902
- reject(new Error('Twitter login timed out.'));
1903
- }, 300000);
1904
- const popupClosedInterval = window.setInterval(() => {
1905
- try {
1906
- // Check if popup is closed - this may throw cross-origin errors for some providers
1907
- if (popup.closed) {
1908
- cleanup(messageHandler, timeoutHandle, popupClosedInterval);
1909
- reject(createUserCancelledError('Twitter login window was closed.'));
1910
- }
1911
- }
1912
- catch (_a) {
1913
- // Cross-origin error when checking popup.closed - this happens when the popup
1914
- // navigates to a third-party OAuth provider with strict security settings.
1915
- // We can't detect if the window was closed, so we rely on timeout and message handlers.
1916
- clearInterval(popupClosedInterval);
1917
- }
1918
- }, 1000);
1919
- });
2083
+ if (presets.cognito) {
2084
+ providers.cognito = buildCognitoConfig(presets.cognito);
1920
2085
  }
1921
- async logout() {
1922
- localStorage.removeItem(this.TOKENS_KEY);
2086
+ if (presets.okta) {
2087
+ providers.okta = buildOktaConfig(presets.okta);
1923
2088
  }
1924
- async isLoggedIn() {
1925
- const tokens = this.getStoredTokens();
1926
- if (!tokens) {
1927
- return { isLoggedIn: false };
1928
- }
1929
- const isValid = tokens.expiresAt > Date.now();
1930
- if (!isValid) {
1931
- localStorage.removeItem(this.TOKENS_KEY);
1932
- }
1933
- return { isLoggedIn: isValid };
2089
+ if (presets.onelogin) {
2090
+ providers.onelogin = buildOneLoginConfig(presets.onelogin);
1934
2091
  }
1935
- async getAuthorizationCode() {
1936
- const tokens = this.getStoredTokens();
1937
- if (!tokens) {
1938
- throw new Error('Twitter access token is not available.');
1939
- }
2092
+ return providers;
2093
+ };
2094
+ const isAuthConnectProvider = (provider) => AUTH_CONNECT_PROVIDERS.includes(provider);
2095
+ const isAuthConnectProviderOptions = (options) => isAuthConnectProvider(options.provider);
2096
+ const isAuthConnectLoginOptions = (options) => isAuthConnectProvider(options.provider);
2097
+ const mapLoginOptions = (options) => {
2098
+ var _a;
2099
+ if (isAuthConnectLoginOptions(options)) {
1940
2100
  return {
1941
- accessToken: tokens.accessToken,
2101
+ provider: 'oauth2',
2102
+ options: Object.assign({ providerId: options.provider }, ((_a = options.options) !== null && _a !== void 0 ? _a : {})),
1942
2103
  };
1943
2104
  }
1944
- async refresh() {
1945
- const tokens = this.getStoredTokens();
1946
- if (!(tokens === null || tokens === void 0 ? void 0 : tokens.refreshToken)) {
1947
- throw new Error('No Twitter refresh token is available. Include offline.access scope to receive one.');
1948
- }
1949
- await this.refreshWithRefreshToken(tokens.refreshToken);
2105
+ return options;
2106
+ };
2107
+ const mapProviderOptions = (options) => {
2108
+ if (isAuthConnectProviderOptions(options)) {
2109
+ return {
2110
+ provider: 'oauth2',
2111
+ providerId: options.provider,
2112
+ };
1950
2113
  }
1951
- async handleOAuthRedirect(url, expectedState) {
1952
- const params = url.searchParams;
1953
- const stateFromUrl = expectedState !== null && expectedState !== void 0 ? expectedState : params.get('state');
1954
- if (!stateFromUrl) {
1955
- return null;
1956
- }
1957
- const pending = this.consumePendingLogin(stateFromUrl);
1958
- if (!pending) {
1959
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1960
- return { error: 'Twitter login session expired or state mismatch.' };
1961
- }
1962
- const error = params.get('error');
1963
- if (error) {
1964
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1965
- return { error: params.get('error_description') || error };
1966
- }
1967
- const code = params.get('code');
1968
- if (!code) {
1969
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1970
- return { error: 'Twitter authorization code missing from redirect.' };
1971
- }
1972
- try {
1973
- const tokens = await this.exchangeAuthorizationCode(code, pending);
1974
- const profile = await this.fetchProfile(tokens.access_token);
1975
- const expiresAt = Date.now() + tokens.expires_in * 1000;
1976
- const scopeArray = tokens.scope.split(' ').filter(Boolean);
1977
- this.persistTokens({
1978
- accessToken: tokens.access_token,
1979
- refreshToken: tokens.refresh_token,
1980
- expiresAt,
1981
- scope: scopeArray,
1982
- tokenType: tokens.token_type,
1983
- userId: profile.id,
1984
- profile,
1985
- });
2114
+ return options;
2115
+ };
2116
+ const mapRefreshOptions = (options) => mapLoginOptions(options);
2117
+ const mergeOAuth2Configs = (presets, oauth2) => {
2118
+ if (!Object.keys(presets).length && !oauth2) {
2119
+ return oauth2;
2120
+ }
2121
+ return Object.assign(Object.assign({}, presets), (oauth2 !== null && oauth2 !== void 0 ? oauth2 : {}));
2122
+ };
2123
+ const createAuthConnectClient = (client) => ({
2124
+ initialize: async (options) => {
2125
+ const { authConnect, oauth2 } = options, rest = __rest(options, ["authConnect", "oauth2"]);
2126
+ const presetProviders = buildAuthConnectProviders(authConnect);
2127
+ const mergedOauth2 = mergeOAuth2Configs(presetProviders, oauth2);
2128
+ const payload = Object.assign(Object.assign({}, rest), (mergedOauth2 ? { oauth2: mergedOauth2 } : {}));
2129
+ return client.initialize(payload);
2130
+ },
2131
+ login: async (options) => {
2132
+ if (isAuthConnectProvider(options.provider)) {
2133
+ const mapped = mapLoginOptions(options);
2134
+ const response = await client.login(mapped);
1986
2135
  return {
1987
- provider: 'twitter',
1988
- result: {
1989
- accessToken: {
1990
- token: tokens.access_token,
1991
- tokenType: tokens.token_type,
1992
- expires: new Date(expiresAt).toISOString(),
1993
- userId: profile.id,
1994
- },
1995
- refreshToken: tokens.refresh_token,
1996
- scope: scopeArray,
1997
- tokenType: tokens.token_type,
1998
- expiresIn: tokens.expires_in,
1999
- profile,
2000
- },
2136
+ provider: options.provider,
2137
+ result: response.result,
2001
2138
  };
2002
2139
  }
2003
- catch (err) {
2004
- if (err instanceof Error) {
2005
- return { error: err.message };
2006
- }
2007
- return { error: 'Twitter login failed unexpectedly.' };
2008
- }
2009
- finally {
2010
- localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
2011
- }
2140
+ return client.login(options);
2141
+ },
2142
+ logout: async (options) => client.logout(mapProviderOptions(options)),
2143
+ isLoggedIn: async (options) => client.isLoggedIn(mapProviderOptions(options)),
2144
+ getAuthorizationCode: async (options) => client.getAuthorizationCode(mapProviderOptions(options)),
2145
+ refresh: async (options) => client.refresh(mapRefreshOptions(options)),
2146
+ providerSpecificCall: async (options) => client.providerSpecificCall(options),
2147
+ getPluginVersion: async () => client.getPluginVersion(),
2148
+ });
2149
+ const SocialLoginAuthConnect = createAuthConnectClient(SocialLoginBase);
2150
+
2151
+ class AppleSocialLogin extends BaseSocialLogin {
2152
+ constructor() {
2153
+ super(...arguments);
2154
+ this.clientId = null;
2155
+ this.redirectUrl = null;
2156
+ this.scriptLoaded = false;
2157
+ this.scriptUrl = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
2158
+ this.useProperTokenExchange = false;
2012
2159
  }
2013
- async exchangeAuthorizationCode(code, pending) {
2014
- const params = new URLSearchParams({
2015
- grant_type: 'authorization_code',
2016
- client_id: pending.clientId,
2017
- code,
2018
- redirect_uri: pending.redirectUri,
2019
- code_verifier: pending.codeVerifier,
2020
- });
2021
- const response = await fetch('https://api.x.com/2/oauth2/token', {
2022
- method: 'POST',
2023
- headers: {
2024
- 'Content-Type': 'application/x-www-form-urlencoded',
2025
- },
2026
- body: params.toString(),
2027
- });
2028
- if (!response.ok) {
2029
- const text = await response.text();
2030
- throw new Error(`Twitter token exchange failed (${response.status}): ${text}`);
2160
+ async initialize(clientId, redirectUrl, useProperTokenExchange = false) {
2161
+ this.clientId = clientId;
2162
+ this.redirectUrl = redirectUrl || null;
2163
+ this.useProperTokenExchange = useProperTokenExchange;
2164
+ if (clientId) {
2165
+ await this.loadAppleScript();
2031
2166
  }
2032
- return (await response.json());
2033
2167
  }
2034
- async refreshWithRefreshToken(refreshToken) {
2035
- var _a, _b;
2036
- const params = new URLSearchParams({
2037
- grant_type: 'refresh_token',
2038
- refresh_token: refreshToken,
2039
- client_id: (_a = this.clientId) !== null && _a !== void 0 ? _a : '',
2040
- });
2041
- const response = await fetch('https://api.x.com/2/oauth2/token', {
2042
- method: 'POST',
2043
- headers: {
2044
- 'Content-Type': 'application/x-www-form-urlencoded',
2045
- },
2046
- body: params.toString(),
2047
- });
2048
- if (!response.ok) {
2049
- const text = await response.text();
2050
- throw new Error(`Twitter refresh failed (${response.status}): ${text}`);
2168
+ async login(options) {
2169
+ if (!this.clientId) {
2170
+ throw new Error('Apple Client ID not set. Call initialize() first.');
2051
2171
  }
2052
- const tokens = (await response.json());
2053
- const profile = await this.fetchProfile(tokens.access_token);
2054
- const expiresAt = Date.now() + tokens.expires_in * 1000;
2055
- const scopeArray = tokens.scope.split(' ').filter(Boolean);
2056
- this.persistTokens({
2057
- accessToken: tokens.access_token,
2058
- refreshToken: (_b = tokens.refresh_token) !== null && _b !== void 0 ? _b : refreshToken,
2059
- expiresAt,
2060
- scope: scopeArray,
2061
- tokenType: tokens.token_type,
2062
- userId: profile.id,
2063
- profile,
2172
+ if (!this.scriptLoaded) {
2173
+ throw new Error('Apple Sign-In script not loaded.');
2174
+ }
2175
+ return new Promise((resolve, reject) => {
2176
+ var _a, _b;
2177
+ AppleID.auth.init({
2178
+ clientId: (_a = this.clientId) !== null && _a !== void 0 ? _a : '',
2179
+ scope: ((_b = options.scopes) === null || _b === void 0 ? void 0 : _b.join(' ')) || 'name email',
2180
+ redirectURI: this.redirectUrl || window.location.href,
2181
+ state: options.state,
2182
+ nonce: options.nonce,
2183
+ usePopup: true,
2184
+ });
2185
+ AppleID.auth
2186
+ .signIn()
2187
+ .then((res) => {
2188
+ var _a, _b, _c, _d, _e;
2189
+ let accessToken = null;
2190
+ if (this.useProperTokenExchange) {
2191
+ // When using proper token exchange, the authorization code should be exchanged
2192
+ // for a proper access token on the backend. For now, we set accessToken to null
2193
+ // and provide the authorization code in a separate field for backend processing.
2194
+ accessToken = null;
2195
+ }
2196
+ else {
2197
+ // Legacy behavior: use authorization code as access token for backward compatibility
2198
+ accessToken = {
2199
+ token: res.authorization.code || '',
2200
+ };
2201
+ }
2202
+ const result = Object.assign({ profile: {
2203
+ user: res.user || '',
2204
+ email: ((_a = res.user) === null || _a === void 0 ? void 0 : _a.email) || null,
2205
+ givenName: ((_c = (_b = res.user) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.firstName) || null,
2206
+ familyName: ((_e = (_d = res.user) === null || _d === void 0 ? void 0 : _d.name) === null || _e === void 0 ? void 0 : _e.lastName) || null,
2207
+ }, accessToken: accessToken, idToken: res.authorization.id_token || null }, (this.useProperTokenExchange && { authorizationCode: res.authorization.code }));
2208
+ resolve({ provider: 'apple', result });
2209
+ })
2210
+ .catch((error) => {
2211
+ var _a, _b, _c;
2212
+ const message = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.localizedDescription) !== null && _b !== void 0 ? _b : error === null || error === void 0 ? void 0 : error.error) !== null && _c !== void 0 ? _c : 'Apple login failed';
2213
+ reject(inferUserCancelledError(message));
2214
+ });
2064
2215
  });
2065
2216
  }
2066
- async fetchProfile(accessToken) {
2067
- var _a, _b, _c, _d;
2068
- const fields = ['profile_image_url', 'verified', 'name', 'username'];
2069
- const response = await fetch(`https://api.x.com/2/users/me?user.fields=${fields.join(',')}`, {
2070
- headers: {
2071
- Authorization: `Bearer ${accessToken}`,
2072
- },
2217
+ async logout() {
2218
+ // Apple doesn't provide a logout method for web
2219
+ console.log('Apple logout: Session should be managed on the client side');
2220
+ }
2221
+ async isLoggedIn() {
2222
+ // Apple doesn't provide a method to check login status on web
2223
+ console.log('Apple login status should be managed on the client side');
2224
+ return { isLoggedIn: false };
2225
+ }
2226
+ async getAuthorizationCode() {
2227
+ // Apple authorization code should be obtained during login
2228
+ console.log('Apple authorization code should be stored during login');
2229
+ throw new Error('Apple authorization code not available');
2230
+ }
2231
+ async refresh() {
2232
+ // Apple doesn't provide a refresh method for web
2233
+ console.log('Apple refresh not available on web');
2234
+ }
2235
+ async loadAppleScript() {
2236
+ if (this.scriptLoaded)
2237
+ return;
2238
+ return this.loadScript(this.scriptUrl).then(() => {
2239
+ this.scriptLoaded = true;
2073
2240
  });
2074
- if (!response.ok) {
2075
- const text = await response.text();
2076
- throw new Error(`Unable to fetch Twitter profile (${response.status}): ${text}`);
2077
- }
2078
- const payload = (await response.json());
2079
- if (!payload.data) {
2080
- throw new Error('Twitter profile payload is missing data.');
2081
- }
2082
- return {
2083
- id: payload.data.id,
2084
- username: payload.data.username,
2085
- name: (_a = payload.data.name) !== null && _a !== void 0 ? _a : null,
2086
- profileImageUrl: (_b = payload.data.profile_image_url) !== null && _b !== void 0 ? _b : null,
2087
- verified: (_c = payload.data.verified) !== null && _c !== void 0 ? _c : false,
2088
- email: (_d = payload.data.email) !== null && _d !== void 0 ? _d : null,
2089
- };
2090
2241
  }
2091
- persistTokens(tokens) {
2092
- localStorage.setItem(this.TOKENS_KEY, JSON.stringify(tokens));
2242
+ }
2243
+
2244
+ class FacebookSocialLogin extends BaseSocialLogin {
2245
+ constructor() {
2246
+ super(...arguments);
2247
+ this.appId = null;
2248
+ this.scriptLoaded = false;
2249
+ this.locale = 'en_US';
2093
2250
  }
2094
- getStoredTokens() {
2095
- const raw = localStorage.getItem(this.TOKENS_KEY);
2096
- if (!raw) {
2097
- return null;
2251
+ async initialize(appId, locale) {
2252
+ this.appId = appId;
2253
+ if (locale) {
2254
+ this.locale = locale;
2098
2255
  }
2099
- try {
2100
- return JSON.parse(raw);
2256
+ if (appId) {
2257
+ // Load with the specified locale or default
2258
+ await this.loadFacebookScript(this.locale);
2259
+ FB.init({
2260
+ appId: this.appId,
2261
+ version: 'v17.0',
2262
+ xfbml: true,
2263
+ cookie: true,
2264
+ });
2101
2265
  }
2102
- catch (err) {
2103
- console.warn('Failed to parse stored Twitter tokens', err);
2104
- return null;
2266
+ }
2267
+ async login(options) {
2268
+ if (!this.appId) {
2269
+ throw new Error('Facebook App ID not set. Call initialize() first.');
2105
2270
  }
2271
+ return new Promise((resolve, reject) => {
2272
+ var _a;
2273
+ let settled = false;
2274
+ let waitingForStatus = false;
2275
+ const resolveWithProfile = (authResponse) => {
2276
+ if (settled)
2277
+ return;
2278
+ if (!(authResponse === null || authResponse === void 0 ? void 0 : authResponse.accessToken) || !authResponse.userID) {
2279
+ settled = true;
2280
+ reject(new Error('Facebook login failed'));
2281
+ return;
2282
+ }
2283
+ const accessToken = authResponse.accessToken;
2284
+ const userId = authResponse.userID;
2285
+ FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo) => {
2286
+ var _a, _b;
2287
+ settled = true;
2288
+ const result = {
2289
+ accessToken: {
2290
+ token: accessToken,
2291
+ userId,
2292
+ },
2293
+ profile: {
2294
+ userID: userInfo.id,
2295
+ name: userInfo.name,
2296
+ email: userInfo.email || null,
2297
+ imageURL: ((_b = (_a = userInfo.picture) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.url) || null,
2298
+ friendIDs: [],
2299
+ birthday: null,
2300
+ ageRange: null,
2301
+ gender: null,
2302
+ location: null,
2303
+ hometown: null,
2304
+ profileURL: null,
2305
+ },
2306
+ idToken: null,
2307
+ };
2308
+ resolve({ provider: 'facebook', result });
2309
+ });
2310
+ };
2311
+ const waitForConnected = () => {
2312
+ if (settled || waitingForStatus)
2313
+ return;
2314
+ waitingForStatus = true;
2315
+ this.waitForConnection()
2316
+ .then((statusResponse) => resolveWithProfile(statusResponse.authResponse))
2317
+ .catch((error) => {
2318
+ if (settled)
2319
+ return;
2320
+ settled = true;
2321
+ reject(error);
2322
+ });
2323
+ };
2324
+ FB.login((response) => {
2325
+ if (response.status === 'connected') {
2326
+ resolveWithProfile(response.authResponse);
2327
+ }
2328
+ else if (response.status === 'not_authorized' || response.status === 'unknown') {
2329
+ reject(createUserCancelledError('Facebook login was cancelled.'));
2330
+ }
2331
+ else {
2332
+ waitForConnected();
2333
+ }
2334
+ }, ((_a = options.permissions) === null || _a === void 0 ? void 0 : _a.length) ? { scope: options.permissions.join(',') } : undefined);
2335
+ });
2106
2336
  }
2107
- persistPendingLogin(state, payload) {
2108
- localStorage.setItem(`${this.STATE_PREFIX}${state}`, JSON.stringify(payload));
2337
+ async logout() {
2338
+ return new Promise((resolve) => {
2339
+ FB.logout(() => resolve());
2340
+ });
2109
2341
  }
2110
- consumePendingLogin(state) {
2111
- const key = `${this.STATE_PREFIX}${state}`;
2112
- const raw = localStorage.getItem(key);
2113
- localStorage.removeItem(key);
2114
- if (!raw) {
2115
- return null;
2116
- }
2117
- try {
2118
- return JSON.parse(raw);
2119
- }
2120
- catch (err) {
2121
- console.warn('Failed to parse pending Twitter login payload', err);
2122
- return null;
2123
- }
2342
+ async isLoggedIn() {
2343
+ return new Promise((resolve) => {
2344
+ FB.getLoginStatus((response) => {
2345
+ resolve({ isLoggedIn: response.status === 'connected' });
2346
+ });
2347
+ });
2124
2348
  }
2125
- generateState() {
2126
- return [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('');
2349
+ async getAuthorizationCode() {
2350
+ return new Promise((resolve, reject) => {
2351
+ FB.getLoginStatus((response) => {
2352
+ var _a;
2353
+ if (response.status === 'connected') {
2354
+ resolve({ accessToken: ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken) || '' });
2355
+ }
2356
+ else {
2357
+ reject(new Error('No Facebook authorization code available'));
2358
+ }
2359
+ });
2360
+ });
2127
2361
  }
2128
- generateCodeVerifier() {
2129
- const array = new Uint8Array(64);
2130
- crypto.getRandomValues(array);
2131
- return Array.from(array)
2132
- .map((b) => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'[b % 66])
2133
- .join('');
2362
+ async refresh(options) {
2363
+ await this.login(options);
2134
2364
  }
2135
- async generateCodeChallenge(codeVerifier) {
2136
- const encoder = new TextEncoder();
2137
- const data = encoder.encode(codeVerifier);
2138
- const digest = await crypto.subtle.digest('SHA-256', data);
2139
- return this.base64UrlEncode(new Uint8Array(digest));
2365
+ waitForConnection(timeoutMs = 120000, pollIntervalMs = 500) {
2366
+ const start = Date.now();
2367
+ return new Promise((resolve, reject) => {
2368
+ let finished = false;
2369
+ const pollStatus = () => {
2370
+ if (finished)
2371
+ return;
2372
+ FB.getLoginStatus((response) => {
2373
+ var _a;
2374
+ if (finished)
2375
+ return;
2376
+ if (response.status === 'connected' && ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken)) {
2377
+ finished = true;
2378
+ resolve(response);
2379
+ return;
2380
+ }
2381
+ if (response.status === 'not_authorized' || response.status === 'unknown') {
2382
+ finished = true;
2383
+ reject(createUserCancelledError('Facebook login was cancelled.'));
2384
+ return;
2385
+ }
2386
+ if (Date.now() - start >= timeoutMs) {
2387
+ finished = true;
2388
+ reject(new Error('Facebook login failed or timed out'));
2389
+ return;
2390
+ }
2391
+ setTimeout(pollStatus, pollIntervalMs);
2392
+ });
2393
+ };
2394
+ pollStatus();
2395
+ });
2140
2396
  }
2141
- base64UrlEncode(buffer) {
2142
- let binary = '';
2143
- buffer.forEach((b) => (binary += String.fromCharCode(b)));
2144
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
2397
+ async loadFacebookScript(locale) {
2398
+ if (this.scriptLoaded)
2399
+ return;
2400
+ // Remove any existing Facebook SDK script
2401
+ const existingScript = document.querySelector('script[src*="connect.facebook.net"]');
2402
+ if (existingScript) {
2403
+ existingScript.remove();
2404
+ }
2405
+ return this.loadScript(`https://connect.facebook.net/${locale}/sdk.js`).then(() => {
2406
+ this.scriptLoaded = true;
2407
+ });
2145
2408
  }
2146
2409
  }
2147
2410
 
@@ -2155,9 +2418,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2155
2418
  this.oauth2Provider = new OAuth2SocialLogin();
2156
2419
  // Auto-finish OAuth redirects only when running inside a popup window.
2157
2420
  // For redirect-based flows (full page navigation), the app should call `handleRedirectCallback()` explicitly.
2158
- const hasPending = !!localStorage.getItem(SocialLoginWeb.OAUTH_STATE_KEY);
2159
- const isPopup = !!window.opener || SocialLoginWeb.POPUP_WINDOW_NAMES.has(window.name);
2160
- if (hasPending && isPopup) {
2421
+ // Note: oauth-popup-redirect.ts also handles this eagerly on package import for COOP-safe popup completion.
2422
+ if (shouldAutoFinishOAuthRedirect()) {
2161
2423
  this.finishOAuthRedirectInPopup().catch((error) => {
2162
2424
  console.error('Failed to finish OAuth redirect', error);
2163
2425
  try {
@@ -2203,56 +2465,33 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2203
2465
  return { provider, state, nonce, result };
2204
2466
  }
2205
2467
  async finishOAuthRedirectInPopup() {
2206
- var _a;
2468
+ var _a, _b, _c;
2207
2469
  const parsed = await this.parseRedirectResult();
2208
- const result = parsed.result;
2209
- if (!result)
2210
- return;
2211
- // Build the message to send
2470
+ const nonceOrState = (_a = parsed.nonce) !== null && _a !== void 0 ? _a : parsed.state;
2212
2471
  let message;
2213
- if ('error' in result) {
2214
- const resolvedProvider = (_a = parsed.provider) !== null && _a !== void 0 ? _a : null;
2215
- const error = inferUserCancelledError(result.error);
2472
+ if (!parsed.result) {
2473
+ message = {
2474
+ type: 'oauth-error',
2475
+ provider: parsed.provider,
2476
+ error: 'OAuth redirect did not contain expected parameters.',
2477
+ };
2478
+ }
2479
+ else if ('error' in parsed.result) {
2480
+ const resolvedProvider = (_b = parsed.provider) !== null && _b !== void 0 ? _b : null;
2481
+ const error = inferUserCancelledError(parsed.result.error);
2216
2482
  message = Object.assign({ type: 'oauth-error', provider: resolvedProvider, error: error.message }, (error.code ? { code: error.code } : null));
2217
2483
  }
2218
2484
  else {
2219
- message = Object.assign({ type: 'oauth-response', provider: result.provider }, result.result);
2220
- }
2221
- // Try postMessage first (works when window.opener is accessible)
2222
- try {
2223
- if (window.opener) {
2224
- window.opener.postMessage(message, window.location.origin);
2225
- }
2485
+ message = Object.assign({ type: 'oauth-response', provider: parsed.result.provider }, parsed.result.result);
2226
2486
  }
2227
- catch (_b) {
2228
- // Cross-origin error - window.opener may not be accessible
2229
- console.log('postMessage to opener failed, using BroadcastChannel');
2230
- }
2231
- // Also use BroadcastChannel as a fallback (works across same-origin windows
2232
- // even when window.opener is not accessible due to cross-origin navigation)
2487
+ deliverOAuthResult((_c = parsed.provider) !== null && _c !== void 0 ? _c : 'google', nonceOrState, message);
2488
+ clearOAuthPopupMarker();
2233
2489
  try {
2234
- // Determine the channel name based on provider and state/nonce
2235
- let channelName = null;
2236
- if (parsed.provider === 'oauth2' && parsed.state) {
2237
- channelName = `oauth2_${parsed.state}`;
2238
- }
2239
- else if (parsed.provider === 'twitter' && parsed.state) {
2240
- channelName = `twitter_oauth_${parsed.state}`;
2241
- }
2242
- else if (parsed.provider === 'google' && parsed.nonce) {
2243
- channelName = `google_oauth_${parsed.nonce}`;
2244
- }
2245
- if (channelName) {
2246
- const channel = new BroadcastChannel(channelName);
2247
- channel.postMessage(message);
2248
- channel.close();
2249
- }
2490
+ window.close();
2250
2491
  }
2251
- catch (_c) {
2252
- // BroadcastChannel not supported or other error
2253
- console.log('BroadcastChannel not available');
2492
+ catch (_d) {
2493
+ // Popup may not be allowed to close itself in some contexts
2254
2494
  }
2255
- window.close();
2256
2495
  }
2257
2496
  async initialize(options) {
2258
2497
  var _a, _b, _c, _d;
@@ -2455,8 +2694,7 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2455
2694
  });
2456
2695
  }
2457
2696
  }
2458
- SocialLoginWeb.OAUTH_STATE_KEY = 'social_login_oauth_pending';
2459
- SocialLoginWeb.POPUP_WINDOW_NAMES = new Set(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);
2697
+ SocialLoginWeb.OAUTH_STATE_KEY = OAUTH_STATE_KEY;
2460
2698
 
2461
2699
  var web = /*#__PURE__*/Object.freeze({
2462
2700
  __proto__: null,