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