capacitor-auth-manager 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CapacitorAuthManager.podspec +36 -0
  2. package/LICENSE +1 -1
  3. package/Readme.md +577 -20
  4. package/android/build.gradle +79 -0
  5. package/android/gradle.properties +25 -0
  6. package/android/proguard-rules.pro +38 -0
  7. package/android/settings.gradle +2 -0
  8. package/android/src/main/AndroidManifest.xml +11 -0
  9. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthLogger.java +117 -0
  10. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +124 -0
  11. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/BaseAuthProvider.java +16 -0
  12. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +385 -0
  13. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +469 -0
  14. package/dist/esm/definitions.d.ts +521 -0
  15. package/dist/esm/definitions.js +103 -1
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/dist/esm/index.d.ts +4 -0
  18. package/dist/esm/index.js +6 -1
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/providers/base-provider.d.ts +43 -0
  21. package/dist/esm/providers/base-provider.js +112 -0
  22. package/dist/esm/providers/base-provider.js.map +1 -0
  23. package/dist/esm/providers/oauth-provider.d.ts +30 -0
  24. package/dist/esm/providers/oauth-provider.js +255 -0
  25. package/dist/esm/providers/oauth-provider.js.map +1 -0
  26. package/dist/esm/providers/provider-factory.d.ts +7 -0
  27. package/dist/esm/providers/provider-factory.js +76 -0
  28. package/dist/esm/providers/provider-factory.js.map +1 -0
  29. package/dist/esm/providers/web/apple-provider.d.ts +33 -0
  30. package/dist/esm/providers/web/apple-provider.js +270 -0
  31. package/dist/esm/providers/web/apple-provider.js.map +1 -0
  32. package/dist/esm/providers/web/google-provider.d.ts +27 -0
  33. package/dist/esm/providers/web/google-provider.js +258 -0
  34. package/dist/esm/providers/web/google-provider.js.map +1 -0
  35. package/dist/esm/utils/auth-error.d.ts +16 -0
  36. package/dist/esm/utils/auth-error.js +53 -0
  37. package/dist/esm/utils/auth-error.js.map +1 -0
  38. package/dist/esm/utils/event-emitter.d.ts +9 -0
  39. package/dist/esm/utils/event-emitter.js +28 -0
  40. package/dist/esm/utils/event-emitter.js.map +1 -0
  41. package/dist/esm/utils/logger.d.ts +19 -0
  42. package/dist/esm/utils/logger.js +48 -0
  43. package/dist/esm/utils/logger.js.map +1 -0
  44. package/dist/esm/utils/storage.d.ts +16 -0
  45. package/dist/esm/utils/storage.js +86 -0
  46. package/dist/esm/utils/storage.js.map +1 -0
  47. package/dist/esm/web.d.ts +43 -0
  48. package/dist/esm/web.js +374 -1
  49. package/dist/esm/web.js.map +1 -1
  50. package/dist/plugin.cjs.js +1650 -0
  51. package/dist/plugin.cjs.js.map +1 -1
  52. package/dist/plugin.js +1652 -3
  53. package/dist/plugin.js.map +1 -1
  54. package/ios/Plugin/AuthLogger.swift +71 -0
  55. package/ios/Plugin/AuthStorage.swift +139 -0
  56. package/ios/Plugin/BaseAuthProvider.swift +33 -0
  57. package/ios/Plugin/CapacitorAuthManager.swift +406 -0
  58. package/ios/Plugin/Models.swift +376 -0
  59. package/ios/Plugin/Plugin.m +27 -0
  60. package/ios/Plugin/Plugin.swift +413 -0
  61. package/package.json +6 -2
  62. package/scripts/configure.js +295 -0
package/dist/plugin.js CHANGED
@@ -1,7 +1,1656 @@
1
- (function () {
2
- 'use strict';
1
+ var CapacitorAuthManager = (function (exports, core) {
2
+ 'use strict';
3
3
 
4
+ exports.AuthProvider = void 0;
5
+ (function (AuthProvider) {
6
+ AuthProvider["GOOGLE"] = "google";
7
+ AuthProvider["APPLE"] = "apple";
8
+ AuthProvider["MICROSOFT"] = "microsoft";
9
+ AuthProvider["FACEBOOK"] = "facebook";
10
+ AuthProvider["GITHUB"] = "github";
11
+ AuthProvider["SLACK"] = "slack";
12
+ AuthProvider["LINKEDIN"] = "linkedin";
13
+ AuthProvider["FIREBASE"] = "firebase";
14
+ AuthProvider["EMAIL_MAGIC_LINK"] = "email_magic_link";
15
+ AuthProvider["SMS"] = "sms";
16
+ AuthProvider["EMAIL_PASSWORD"] = "email_password";
17
+ AuthProvider["PHONE_PASSWORD"] = "phone_password";
18
+ AuthProvider["USERNAME_PASSWORD"] = "username_password";
19
+ AuthProvider["EMAIL_CODE"] = "email_code";
20
+ AuthProvider["BIOMETRIC"] = "biometric";
21
+ })(exports.AuthProvider || (exports.AuthProvider = {}));
22
+ exports.AppleAuthScope = void 0;
23
+ (function (AppleAuthScope) {
24
+ AppleAuthScope["EMAIL"] = "email";
25
+ AppleAuthScope["NAME"] = "name";
26
+ })(exports.AppleAuthScope || (exports.AppleAuthScope = {}));
27
+ exports.BiometricType = void 0;
28
+ (function (BiometricType) {
29
+ BiometricType["FINGERPRINT"] = "fingerprint";
30
+ BiometricType["FACE_ID"] = "faceId";
31
+ BiometricType["TOUCH_ID"] = "touchId";
32
+ BiometricType["IRIS"] = "iris";
33
+ BiometricType["VOICE"] = "voice";
34
+ })(exports.BiometricType || (exports.BiometricType = {}));
35
+ exports.AuthPersistence = void 0;
36
+ (function (AuthPersistence) {
37
+ AuthPersistence["LOCAL"] = "local";
38
+ AuthPersistence["SESSION"] = "session";
39
+ AuthPersistence["NONE"] = "none";
40
+ })(exports.AuthPersistence || (exports.AuthPersistence = {}));
41
+ exports.AuthErrorCode = void 0;
42
+ (function (AuthErrorCode) {
43
+ AuthErrorCode["INVALID_CREDENTIALS"] = "auth/invalid-credentials";
44
+ AuthErrorCode["USER_NOT_FOUND"] = "auth/user-not-found";
45
+ AuthErrorCode["WRONG_PASSWORD"] = "auth/wrong-password";
46
+ AuthErrorCode["EMAIL_ALREADY_IN_USE"] = "auth/email-already-in-use";
47
+ AuthErrorCode["WEAK_PASSWORD"] = "auth/weak-password";
48
+ AuthErrorCode["NETWORK_ERROR"] = "auth/network-error";
49
+ AuthErrorCode["TOO_MANY_REQUESTS"] = "auth/too-many-requests";
50
+ AuthErrorCode["USER_DISABLED"] = "auth/user-disabled";
51
+ AuthErrorCode["OPERATION_NOT_ALLOWED"] = "auth/operation-not-allowed";
52
+ AuthErrorCode["INVALID_EMAIL"] = "auth/invalid-email";
53
+ AuthErrorCode["INVALID_PHONE_NUMBER"] = "auth/invalid-phone-number";
54
+ AuthErrorCode["INVALID_VERIFICATION_CODE"] = "auth/invalid-verification-code";
55
+ AuthErrorCode["EXPIRED_ACTION_CODE"] = "auth/expired-action-code";
56
+ AuthErrorCode["CREDENTIAL_ALREADY_IN_USE"] = "auth/credential-already-in-use";
57
+ AuthErrorCode["ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"] = "auth/account-exists-with-different-credential";
58
+ AuthErrorCode["REQUIRES_RECENT_LOGIN"] = "auth/requires-recent-login";
59
+ AuthErrorCode["PROVIDER_ALREADY_LINKED"] = "auth/provider-already-linked";
60
+ AuthErrorCode["NO_SUCH_PROVIDER"] = "auth/no-such-provider";
61
+ AuthErrorCode["INVALID_USER_TOKEN"] = "auth/invalid-user-token";
62
+ AuthErrorCode["TOKEN_EXPIRED"] = "auth/token-expired";
63
+ AuthErrorCode["USER_TOKEN_EXPIRED"] = "auth/user-token-expired";
64
+ AuthErrorCode["INVALID_API_KEY"] = "auth/invalid-api-key";
65
+ AuthErrorCode["USER_CANCELLED"] = "auth/user-cancelled";
66
+ AuthErrorCode["APP_NOT_AUTHORIZED"] = "auth/app-not-authorized";
67
+ AuthErrorCode["KEYCHAIN_ERROR"] = "auth/keychain-error";
68
+ AuthErrorCode["INTERNAL_ERROR"] = "auth/internal-error";
69
+ AuthErrorCode["BIOMETRIC_NOT_AVAILABLE"] = "auth/biometric-not-available";
70
+ AuthErrorCode["BIOMETRIC_NOT_ENROLLED"] = "auth/biometric-not-enrolled";
71
+ AuthErrorCode["BIOMETRIC_AUTHENTICATION_FAILED"] = "auth/biometric-authentication-failed";
72
+ AuthErrorCode["UNSUPPORTED_PROVIDER"] = "auth/unsupported-provider";
73
+ AuthErrorCode["MISSING_CONFIGURATION"] = "auth/missing-configuration";
74
+ AuthErrorCode["POPUP_BLOCKED"] = "auth/popup-blocked";
75
+ AuthErrorCode["POPUP_CLOSED_BY_USER"] = "auth/popup-closed-by-user";
76
+ AuthErrorCode["REDIRECT_CANCELLED_BY_USER"] = "auth/redirect-cancelled-by-user";
77
+ AuthErrorCode["MISSING_REDIRECT_URL"] = "auth/missing-redirect-url";
78
+ AuthErrorCode["INVALID_STATE"] = "auth/invalid-state";
79
+ AuthErrorCode["MISSING_CODE_VERIFIER"] = "auth/missing-code-verifier";
80
+ AuthErrorCode["INVALID_CODE_VERIFIER"] = "auth/invalid-code-verifier";
81
+ AuthErrorCode["MISSING_NONCE"] = "auth/missing-nonce";
82
+ AuthErrorCode["INVALID_NONCE"] = "auth/invalid-nonce";
83
+ AuthErrorCode["UNAUTHORIZED_DOMAIN"] = "auth/unauthorized-domain";
84
+ AuthErrorCode["INVALID_CONTINUE_URL"] = "auth/invalid-continue-url";
85
+ AuthErrorCode["MISSING_CONTINUE_URL"] = "auth/missing-continue-url";
86
+ AuthErrorCode["INVALID_DYNAMIC_LINK_DOMAIN"] = "auth/invalid-dynamic-link-domain";
87
+ AuthErrorCode["REJECTED_CREDENTIAL"] = "auth/rejected-credential";
88
+ AuthErrorCode["PHONE_NUMBER_ALREADY_EXISTS"] = "auth/phone-number-already-exists";
89
+ AuthErrorCode["QUOTA_EXCEEDED"] = "auth/quota-exceeded";
90
+ AuthErrorCode["CAPTCHA_CHECK_FAILED"] = "auth/captcha-check-failed";
91
+ AuthErrorCode["MISSING_CAPTCHA_TOKEN"] = "auth/missing-captcha-token";
92
+ AuthErrorCode["INVALID_CAPTCHA_TOKEN"] = "auth/invalid-captcha-token";
93
+ AuthErrorCode["MISSING_CLIENT_IDENTIFIER"] = "auth/missing-client-identifier";
94
+ AuthErrorCode["MISSING_OR_INVALID_NONCE"] = "auth/missing-or-invalid-nonce";
95
+ AuthErrorCode["INTERACTION_REQUIRED"] = "auth/interaction-required";
96
+ AuthErrorCode["LOGIN_REQUIRED"] = "auth/login-required";
97
+ AuthErrorCode["CONSENT_REQUIRED"] = "auth/consent-required";
98
+ AuthErrorCode["INVALID_GRANT"] = "auth/invalid-grant";
99
+ AuthErrorCode["UNSUPPORTED_GRANT_TYPE"] = "auth/unsupported-grant-type";
100
+ AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
101
+ AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
102
+ AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
103
+ AuthErrorCode["ACCESS_DENIED"] = "auth/access-denied";
104
+ AuthErrorCode["SERVER_ERROR"] = "auth/server-error";
105
+ AuthErrorCode["TEMPORARILY_UNAVAILABLE"] = "auth/temporarily-unavailable";
106
+ })(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
4
107
 
108
+ const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
109
+ web: () => Promise.resolve().then(function () { return web; }).then(m => new m.CapacitorAuthManagerWeb()),
110
+ });
5
111
 
6
- })();
112
+ class AuthError extends Error {
113
+ constructor(code, message, provider, details) {
114
+ super(message);
115
+ this.name = 'AuthError';
116
+ this.code = code;
117
+ this.provider = provider;
118
+ this.details = details;
119
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
120
+ if (Error.captureStackTrace) {
121
+ Error.captureStackTrace(this, AuthError);
122
+ }
123
+ }
124
+ static fromError(error, provider) {
125
+ if (error instanceof AuthError) {
126
+ return error;
127
+ }
128
+ let code = exports.AuthErrorCode.INTERNAL_ERROR;
129
+ let message = 'An unknown error occurred';
130
+ let details = error;
131
+ if (error instanceof Error) {
132
+ message = error.message;
133
+ // Try to map common error patterns to specific error codes
134
+ if (error.message.includes('network')) {
135
+ code = exports.AuthErrorCode.NETWORK_ERROR;
136
+ }
137
+ else if (error.message.includes('cancelled') || error.message.includes('canceled')) {
138
+ code = exports.AuthErrorCode.USER_CANCELLED;
139
+ }
140
+ else if (error.message.includes('timeout')) {
141
+ code = exports.AuthErrorCode.NETWORK_ERROR;
142
+ }
143
+ }
144
+ // Handle provider-specific error codes
145
+ if (error === null || error === void 0 ? void 0 : error.code) {
146
+ code = error.code;
147
+ }
148
+ return new AuthError(code, message, provider, details);
149
+ }
150
+ toJSON() {
151
+ return {
152
+ name: this.name,
153
+ code: this.code,
154
+ message: this.message,
155
+ provider: this.provider,
156
+ details: this.details,
157
+ };
158
+ }
159
+ }
160
+
161
+ class EventEmitter {
162
+ constructor() {
163
+ this.listeners = new Set();
164
+ }
165
+ emit(data) {
166
+ this.listeners.forEach(listener => {
167
+ try {
168
+ listener(data);
169
+ }
170
+ catch (error) {
171
+ console.error('Error in event listener:', error);
172
+ }
173
+ });
174
+ }
175
+ subscribe(listener) {
176
+ this.listeners.add(listener);
177
+ return () => {
178
+ this.listeners.delete(listener);
179
+ };
180
+ }
181
+ clear() {
182
+ this.listeners.clear();
183
+ }
184
+ get listenerCount() {
185
+ return this.listeners.size;
186
+ }
187
+ }
188
+
189
+ class WebStorage {
190
+ constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_') {
191
+ this.prefix = prefix;
192
+ switch (persistence) {
193
+ case exports.AuthPersistence.SESSION:
194
+ this.storage = window.sessionStorage;
195
+ break;
196
+ case exports.AuthPersistence.LOCAL:
197
+ this.storage = window.localStorage;
198
+ break;
199
+ case exports.AuthPersistence.NONE:
200
+ // Use in-memory storage
201
+ this.storage = new InMemoryStorage();
202
+ break;
203
+ default:
204
+ this.storage = window.localStorage;
205
+ }
206
+ }
207
+ async get(key) {
208
+ try {
209
+ return this.storage.getItem(this.prefix + key);
210
+ }
211
+ catch (error) {
212
+ console.error('Storage get error:', error);
213
+ return null;
214
+ }
215
+ }
216
+ async set(key, value) {
217
+ try {
218
+ this.storage.setItem(this.prefix + key, value);
219
+ }
220
+ catch (error) {
221
+ console.error('Storage set error:', error);
222
+ throw error;
223
+ }
224
+ }
225
+ async remove(key) {
226
+ try {
227
+ this.storage.removeItem(this.prefix + key);
228
+ }
229
+ catch (error) {
230
+ console.error('Storage remove error:', error);
231
+ }
232
+ }
233
+ async clear() {
234
+ try {
235
+ const keys = [];
236
+ for (let i = 0; i < this.storage.length; i++) {
237
+ const key = this.storage.key(i);
238
+ if (key && key.startsWith(this.prefix)) {
239
+ keys.push(key);
240
+ }
241
+ }
242
+ keys.forEach(key => this.storage.removeItem(key));
243
+ }
244
+ catch (error) {
245
+ console.error('Storage clear error:', error);
246
+ }
247
+ }
248
+ }
249
+ class InMemoryStorage {
250
+ constructor() {
251
+ this.data = new Map();
252
+ }
253
+ get length() {
254
+ return this.data.size;
255
+ }
256
+ clear() {
257
+ this.data.clear();
258
+ }
259
+ getItem(key) {
260
+ return this.data.get(key) || null;
261
+ }
262
+ key(index) {
263
+ const keys = Array.from(this.data.keys());
264
+ return keys[index] || null;
265
+ }
266
+ removeItem(key) {
267
+ this.data.delete(key);
268
+ }
269
+ setItem(key, value) {
270
+ this.data.set(key, value);
271
+ }
272
+ }
273
+
274
+ class Logger {
275
+ constructor(config) {
276
+ this.logLevels = {
277
+ debug: 0,
278
+ info: 1,
279
+ warn: 2,
280
+ error: 3,
281
+ };
282
+ this.config = config;
283
+ }
284
+ shouldLog(level) {
285
+ if (!this.config.enableLogging)
286
+ return false;
287
+ return this.logLevels[level] >= this.logLevels[this.config.logLevel];
288
+ }
289
+ formatMessage(level, message) {
290
+ const timestamp = new Date().toISOString();
291
+ const prefix = this.config.prefix || 'CapacitorAuthManager';
292
+ return `[${timestamp}] [${prefix}] [${level.toUpperCase()}] ${message}`;
293
+ }
294
+ debug(message, ...args) {
295
+ if (this.shouldLog('debug')) {
296
+ console.debug(this.formatMessage('debug', message), ...args);
297
+ }
298
+ }
299
+ info(message, ...args) {
300
+ if (this.shouldLog('info')) {
301
+ console.info(this.formatMessage('info', message), ...args);
302
+ }
303
+ }
304
+ warn(message, ...args) {
305
+ if (this.shouldLog('warn')) {
306
+ console.warn(this.formatMessage('warn', message), ...args);
307
+ }
308
+ }
309
+ error(message, error) {
310
+ if (this.shouldLog('error')) {
311
+ console.error(this.formatMessage('error', message), error);
312
+ }
313
+ }
314
+ setLogLevel(level) {
315
+ this.config.logLevel = level;
316
+ }
317
+ setEnabled(enabled) {
318
+ this.config.enableLogging = enabled;
319
+ }
320
+ }
321
+
322
+ class BaseAuthProvider {
323
+ constructor(config) {
324
+ this.currentUser = null;
325
+ this.isInitialized = false;
326
+ this.provider = config.provider;
327
+ this.options = config.options;
328
+ this.storage = config.storage;
329
+ this.logger = config.logger;
330
+ this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
331
+ this.authStateEmitter = new EventEmitter();
332
+ }
333
+ async getCurrentUser() {
334
+ if (!this.isInitialized) {
335
+ await this.initialize();
336
+ }
337
+ return this.currentUser;
338
+ }
339
+ addAuthStateListener(callback) {
340
+ return this.authStateEmitter.subscribe(callback);
341
+ }
342
+ async setCurrentUser(user) {
343
+ this.currentUser = user;
344
+ // Persist user to storage
345
+ const storageKey = `${this.provider}_current_user`;
346
+ if (user) {
347
+ await this.storage.set(storageKey, JSON.stringify(user));
348
+ }
349
+ else {
350
+ await this.storage.remove(storageKey);
351
+ }
352
+ // Emit auth state change
353
+ this.authStateEmitter.emit(user);
354
+ }
355
+ async loadCurrentUser() {
356
+ try {
357
+ const storageKey = `${this.provider}_current_user`;
358
+ const userData = await this.storage.get(storageKey);
359
+ if (userData) {
360
+ this.currentUser = JSON.parse(userData);
361
+ this.logger.debug(`Loaded user from storage for provider ${this.provider}`);
362
+ }
363
+ }
364
+ catch (error) {
365
+ this.logger.error('Failed to load user from storage', error);
366
+ }
367
+ }
368
+ async saveCredential(credential) {
369
+ const storageKey = `${this.provider}_credential`;
370
+ await this.storage.set(storageKey, JSON.stringify(credential));
371
+ }
372
+ async loadCredential() {
373
+ try {
374
+ const storageKey = `${this.provider}_credential`;
375
+ const credentialData = await this.storage.get(storageKey);
376
+ if (credentialData) {
377
+ return JSON.parse(credentialData);
378
+ }
379
+ }
380
+ catch (error) {
381
+ this.logger.error('Failed to load credential from storage', error);
382
+ }
383
+ return null;
384
+ }
385
+ async clearStoredData() {
386
+ const userKey = `${this.provider}_current_user`;
387
+ const credentialKey = `${this.provider}_credential`;
388
+ await Promise.all([
389
+ this.storage.remove(userKey),
390
+ this.storage.remove(credentialKey),
391
+ ]);
392
+ }
393
+ validateInitialized() {
394
+ if (!this.isInitialized) {
395
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Provider ${this.provider} is not initialized`, this.provider);
396
+ }
397
+ }
398
+ createAuthResult(user, credential, isNewUser = false, operationType = 'signIn') {
399
+ return {
400
+ user,
401
+ credential,
402
+ additionalUserInfo: {
403
+ isNewUser,
404
+ providerId: this.provider,
405
+ },
406
+ operationType,
407
+ };
408
+ }
409
+ generateUniqueId() {
410
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
411
+ }
412
+ isTokenExpired(expiresAt) {
413
+ if (!expiresAt)
414
+ return false;
415
+ return Date.now() >= expiresAt;
416
+ }
417
+ calculateTokenExpiry(expiresIn) {
418
+ if (!expiresIn) {
419
+ // Default to 1 hour
420
+ expiresIn = 3600;
421
+ }
422
+ return Date.now() + (expiresIn * 1000);
423
+ }
424
+ dispose() {
425
+ this.authStateEmitter.clear();
426
+ this.currentUser = null;
427
+ this.isInitialized = false;
428
+ }
429
+ }
430
+
431
+ class OAuthProvider extends BaseAuthProvider {
432
+ async performOAuthFlow(options) {
433
+ const config = this.getOAuthConfig();
434
+ try {
435
+ // Generate state and nonce for security
436
+ const state = this.generateSecureRandomString();
437
+ const nonce = this.generateSecureRandomString();
438
+ // Store state and nonce for validation
439
+ await this.storage.set(`${this.provider}_oauth_state`, state);
440
+ await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
441
+ // Build authorization URL
442
+ const authUrl = this.buildAuthorizationUrl(config, state, nonce, options);
443
+ // Perform the OAuth flow (platform-specific implementation)
444
+ const authResponse = await this.openAuthorizationUrl(authUrl);
445
+ // Validate response
446
+ await this.validateOAuthResponse(authResponse, state, nonce);
447
+ // Exchange authorization code for tokens
448
+ const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
449
+ // Parse user information
450
+ const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
451
+ // Create AuthUser and AuthCredential
452
+ const user = this.createAuthUser(userInfo, tokenResponse);
453
+ const credential = this.createOAuthCredential(tokenResponse);
454
+ // Save user and credential
455
+ await this.setCurrentUser(user);
456
+ await this.saveCredential(credential);
457
+ return this.createAuthResult(user, credential, userInfo.isNewUser);
458
+ }
459
+ catch (error) {
460
+ this.logger.error(`OAuth flow failed for ${this.provider}`, error);
461
+ throw AuthError.fromError(error, this.provider);
462
+ }
463
+ finally {
464
+ // Clean up temporary storage
465
+ await this.storage.remove(`${this.provider}_oauth_state`);
466
+ await this.storage.remove(`${this.provider}_oauth_nonce`);
467
+ }
468
+ }
469
+ buildAuthorizationUrl(config, state, nonce, options) {
470
+ var _a, _b, _c, _d;
471
+ const params = new URLSearchParams(Object.assign({ client_id: config.clientId, redirect_uri: config.redirectUri, response_type: config.responseType || 'code', state,
472
+ nonce }, config.additionalParams));
473
+ // Add scopes
474
+ const scopes = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) || config.scopes || [];
475
+ if (scopes.length > 0) {
476
+ params.set('scope', scopes.join(' '));
477
+ }
478
+ // Add custom parameters
479
+ if ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.customParameters) {
480
+ Object.entries(options.options.customParameters).forEach(([key, value]) => {
481
+ params.set(key, value);
482
+ });
483
+ }
484
+ // Add login hint if provided
485
+ if ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) {
486
+ params.set('login_hint', options.options.loginHint);
487
+ }
488
+ // Add prompt if provided
489
+ if ((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) {
490
+ params.set('prompt', options.options.prompt);
491
+ }
492
+ return `${config.authorizationEndpoint}?${params.toString()}`;
493
+ }
494
+ async validateOAuthResponse(response, expectedState, _expectedNonce) {
495
+ if (response.error) {
496
+ throw new AuthError(this.mapOAuthError(response.error), response.error_description || response.error, this.provider);
497
+ }
498
+ if (response.state !== expectedState) {
499
+ throw new AuthError(exports.AuthErrorCode.INVALID_STATE, 'OAuth state mismatch', this.provider);
500
+ }
501
+ // Nonce validation is done after ID token is received
502
+ }
503
+ async exchangeCodeForTokens(code, config) {
504
+ const params = new URLSearchParams({
505
+ grant_type: config.grantType || 'authorization_code',
506
+ code,
507
+ redirect_uri: config.redirectUri,
508
+ client_id: config.clientId,
509
+ });
510
+ if (config.clientSecret) {
511
+ params.set('client_secret', config.clientSecret);
512
+ }
513
+ try {
514
+ const response = await fetch(config.tokenEndpoint, {
515
+ method: 'POST',
516
+ headers: {
517
+ 'Content-Type': 'application/x-www-form-urlencoded',
518
+ },
519
+ body: params.toString(),
520
+ });
521
+ const data = await response.json();
522
+ if (!response.ok) {
523
+ throw new AuthError(this.mapOAuthError(data.error), data.error_description || 'Token exchange failed', this.provider, data);
524
+ }
525
+ return data;
526
+ }
527
+ catch (error) {
528
+ if (error instanceof AuthError) {
529
+ throw error;
530
+ }
531
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to exchange authorization code for tokens', this.provider, error);
532
+ }
533
+ }
534
+ async refreshToken(_options) {
535
+ this.validateInitialized();
536
+ const credential = await this.loadCredential();
537
+ if (!credential || !credential.refreshToken) {
538
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'No refresh token available', this.provider);
539
+ }
540
+ const config = this.getOAuthConfig();
541
+ try {
542
+ const params = new URLSearchParams({
543
+ grant_type: 'refresh_token',
544
+ refresh_token: credential.refreshToken,
545
+ client_id: config.clientId,
546
+ });
547
+ if (config.clientSecret) {
548
+ params.set('client_secret', config.clientSecret);
549
+ }
550
+ const response = await fetch(config.tokenEndpoint, {
551
+ method: 'POST',
552
+ headers: {
553
+ 'Content-Type': 'application/x-www-form-urlencoded',
554
+ },
555
+ body: params.toString(),
556
+ });
557
+ const data = await response.json();
558
+ if (!response.ok) {
559
+ throw new AuthError(this.mapOAuthError(data.error), data.error_description || 'Token refresh failed', this.provider, data);
560
+ }
561
+ // Update credential with new tokens
562
+ const newCredential = this.createOAuthCredential(data);
563
+ await this.saveCredential(newCredential);
564
+ // Update user if needed
565
+ if (this.currentUser) {
566
+ this.currentUser.refreshToken = newCredential.refreshToken;
567
+ await this.setCurrentUser(this.currentUser);
568
+ }
569
+ return this.createAuthResult(this.currentUser, newCredential);
570
+ }
571
+ catch (error) {
572
+ if (error instanceof AuthError) {
573
+ throw error;
574
+ }
575
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to refresh token', this.provider, error);
576
+ }
577
+ }
578
+ async revokeAccess(token) {
579
+ const config = this.getOAuthConfig();
580
+ if (!config.revokeEndpoint) {
581
+ this.logger.warn(`Revoke endpoint not configured for ${this.provider}`);
582
+ return;
583
+ }
584
+ try {
585
+ const credential = await this.loadCredential();
586
+ const tokenToRevoke = token || (credential === null || credential === void 0 ? void 0 : credential.accessToken);
587
+ if (!tokenToRevoke) {
588
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'No token to revoke', this.provider);
589
+ }
590
+ const params = new URLSearchParams({
591
+ token: tokenToRevoke,
592
+ client_id: config.clientId,
593
+ });
594
+ if (config.clientSecret) {
595
+ params.set('client_secret', config.clientSecret);
596
+ }
597
+ await fetch(config.revokeEndpoint, {
598
+ method: 'POST',
599
+ headers: {
600
+ 'Content-Type': 'application/x-www-form-urlencoded',
601
+ },
602
+ body: params.toString(),
603
+ });
604
+ // Clear stored data regardless of response
605
+ await this.clearStoredData();
606
+ await this.setCurrentUser(null);
607
+ }
608
+ catch (error) {
609
+ this.logger.error('Failed to revoke token', error);
610
+ // Still clear local data even if revocation fails
611
+ await this.clearStoredData();
612
+ await this.setCurrentUser(null);
613
+ }
614
+ }
615
+ createOAuthCredential(tokenResponse) {
616
+ return {
617
+ providerId: this.provider,
618
+ signInMethod: 'oauth',
619
+ accessToken: tokenResponse.access_token,
620
+ idToken: tokenResponse.id_token,
621
+ refreshToken: tokenResponse.refresh_token,
622
+ expiresAt: tokenResponse.expires_in
623
+ ? this.calculateTokenExpiry(tokenResponse.expires_in)
624
+ : undefined,
625
+ tokenType: tokenResponse.token_type,
626
+ scope: tokenResponse.scope,
627
+ };
628
+ }
629
+ createAuthUser(userInfo, tokenResponse) {
630
+ return {
631
+ uid: userInfo.id || userInfo.sub || this.generateUniqueId(),
632
+ email: userInfo.email,
633
+ emailVerified: userInfo.email_verified || false,
634
+ displayName: userInfo.name || userInfo.displayName,
635
+ photoURL: userInfo.picture || userInfo.photoURL,
636
+ phoneNumber: userInfo.phone_number,
637
+ isAnonymous: false,
638
+ tenantId: null,
639
+ providerData: [{
640
+ providerId: this.provider,
641
+ uid: userInfo.id || userInfo.sub,
642
+ displayName: userInfo.name,
643
+ email: userInfo.email,
644
+ phoneNumber: userInfo.phone_number,
645
+ photoURL: userInfo.picture,
646
+ }],
647
+ metadata: {
648
+ creationTime: new Date().toISOString(),
649
+ lastSignInTime: new Date().toISOString(),
650
+ },
651
+ refreshToken: tokenResponse.refresh_token,
652
+ };
653
+ }
654
+ mapOAuthError(error) {
655
+ const errorMap = {
656
+ 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
657
+ 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
658
+ 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
659
+ 'unsupported_response_type': exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
660
+ 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
661
+ 'server_error': exports.AuthErrorCode.SERVER_ERROR,
662
+ 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
663
+ 'invalid_grant': exports.AuthErrorCode.INVALID_GRANT,
664
+ 'invalid_client': exports.AuthErrorCode.CLIENT_NOT_FOUND,
665
+ 'interaction_required': exports.AuthErrorCode.INTERACTION_REQUIRED,
666
+ 'login_required': exports.AuthErrorCode.LOGIN_REQUIRED,
667
+ 'consent_required': exports.AuthErrorCode.CONSENT_REQUIRED,
668
+ };
669
+ return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
670
+ }
671
+ generateSecureRandomString(length = 32) {
672
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
673
+ let result = '';
674
+ const randomValues = new Uint8Array(length);
675
+ crypto.getRandomValues(randomValues);
676
+ for (let i = 0; i < length; i++) {
677
+ result += chars[randomValues[i] % chars.length];
678
+ }
679
+ return result;
680
+ }
681
+ }
682
+
683
+ class GoogleAuthProviderWeb extends OAuthProvider {
684
+ constructor(config) {
685
+ super(config);
686
+ this.initPromise = null;
687
+ }
688
+ getOAuthConfig() {
689
+ const options = this.options;
690
+ return {
691
+ clientId: options.clientId,
692
+ clientSecret: options.clientSecret,
693
+ redirectUri: window.location.origin,
694
+ authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
695
+ tokenEndpoint: 'https://oauth2.googleapis.com/token',
696
+ revokeEndpoint: 'https://oauth2.googleapis.com/revoke',
697
+ userInfoEndpoint: 'https://www.googleapis.com/oauth2/v3/userinfo',
698
+ scopes: options.scopes || ['openid', 'email', 'profile'],
699
+ responseType: 'code',
700
+ additionalParams: {
701
+ access_type: options.offlineAccess ? 'offline' : 'online',
702
+ include_granted_scopes: options.includeGrantedScopes ? 'true' : 'false',
703
+ },
704
+ };
705
+ }
706
+ async initialize() {
707
+ if (this.isInitialized) {
708
+ return;
709
+ }
710
+ if (this.initPromise) {
711
+ return this.initPromise;
712
+ }
713
+ this.initPromise = this._initialize();
714
+ try {
715
+ await this.initPromise;
716
+ }
717
+ finally {
718
+ this.initPromise = null;
719
+ }
720
+ }
721
+ async _initialize() {
722
+ const options = this.options;
723
+ try {
724
+ // Load Google Identity Services library
725
+ await this.loadGoogleIdentityServices();
726
+ // Initialize Google client
727
+ window.google.accounts.oauth2.initCodeClient({
728
+ client_id: options.clientId,
729
+ scope: (options.scopes || ['openid', 'email', 'profile']).join(' '),
730
+ ux_mode: 'popup',
731
+ callback: (_response) => {
732
+ // This callback will be overridden per sign-in
733
+ },
734
+ });
735
+ // Load previously authenticated user
736
+ await this.loadCurrentUser();
737
+ this.isInitialized = true;
738
+ this.logger.info('Google Auth provider initialized');
739
+ }
740
+ catch (error) {
741
+ this.logger.error('Failed to initialize Google Auth', error);
742
+ throw AuthError.fromError(error, this.provider);
743
+ }
744
+ }
745
+ async signIn(options) {
746
+ this.validateInitialized();
747
+ return new Promise((resolve, reject) => {
748
+ var _a, _b, _c;
749
+ try {
750
+ const googleOptions = this.options;
751
+ // Configure sign-in options
752
+ const signInConfig = {
753
+ client_id: googleOptions.clientId,
754
+ scope: (((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) || googleOptions.scopes || ['openid', 'email', 'profile']).join(' '),
755
+ callback: async (response) => {
756
+ if (response.error) {
757
+ reject(new AuthError(this.mapGoogleError(response.error), response.error_description || response.error, this.provider));
758
+ return;
759
+ }
760
+ try {
761
+ // Exchange authorization code for tokens
762
+ const tokenResponse = await this.exchangeCodeForTokens(response.code, this.getOAuthConfig());
763
+ // Get user info
764
+ const userInfo = await this.getUserInfo(tokenResponse.access_token);
765
+ // Create AuthUser and AuthCredential
766
+ const user = this.createAuthUser(userInfo, tokenResponse);
767
+ const credential = this.createOAuthCredential(tokenResponse);
768
+ // Save user and credential
769
+ await this.setCurrentUser(user);
770
+ await this.saveCredential(credential);
771
+ resolve(this.createAuthResult(user, credential, false));
772
+ }
773
+ catch (error) {
774
+ reject(AuthError.fromError(error, this.provider));
775
+ }
776
+ },
777
+ };
778
+ // Add login hint if provided
779
+ if (((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.loginHint) || googleOptions.loginHint) {
780
+ signInConfig.login_hint = ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) || googleOptions.loginHint;
781
+ }
782
+ // Add hosted domain if provided
783
+ if (googleOptions.hostedDomain) {
784
+ signInConfig.hd = googleOptions.hostedDomain;
785
+ }
786
+ // Create new client with callback
787
+ const client = window.google.accounts.oauth2.initCodeClient(signInConfig);
788
+ // Request authorization code
789
+ client.requestCode();
790
+ }
791
+ catch (error) {
792
+ reject(AuthError.fromError(error, this.provider));
793
+ }
794
+ });
795
+ }
796
+ async signOut(options) {
797
+ var _a, _b;
798
+ this.validateInitialized();
799
+ try {
800
+ // Revoke token if requested
801
+ if (options === null || options === void 0 ? void 0 : options.revokeToken) {
802
+ const credential = await this.loadCredential();
803
+ if (credential === null || credential === void 0 ? void 0 : credential.accessToken) {
804
+ await this.revokeAccess(credential.accessToken);
805
+ }
806
+ }
807
+ // Clear stored data
808
+ await this.clearStoredData();
809
+ await this.setCurrentUser(null);
810
+ // Disconnect Google account if available
811
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
812
+ window.google.accounts.id.disableAutoSelect();
813
+ }
814
+ this.logger.info('Signed out from Google');
815
+ }
816
+ catch (error) {
817
+ this.logger.error('Failed to sign out from Google', error);
818
+ throw AuthError.fromError(error, this.provider);
819
+ }
820
+ }
821
+ async isSupported() {
822
+ // Check if we're in a browser environment
823
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
824
+ return false;
825
+ }
826
+ // Check if we can load Google Identity Services
827
+ try {
828
+ await this.loadGoogleIdentityServices();
829
+ return true;
830
+ }
831
+ catch (_a) {
832
+ return false;
833
+ }
834
+ }
835
+ async linkAccount(options) {
836
+ // For web, linking is the same as signing in
837
+ return this.signIn(options);
838
+ }
839
+ async unlinkAccount(_options) {
840
+ // For web, unlinking is the same as signing out
841
+ await this.signOut();
842
+ }
843
+ async openAuthorizationUrl(_url) {
844
+ // This method is not used in Google Identity Services flow
845
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Direct OAuth flow not supported for Google. Use signIn method instead.', this.provider);
846
+ }
847
+ async parseUserFromTokenResponse(response) {
848
+ // Get user info from the userinfo endpoint
849
+ if (response.access_token) {
850
+ return this.getUserInfo(response.access_token);
851
+ }
852
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'No access token in response', this.provider);
853
+ }
854
+ async getUserInfo(accessToken) {
855
+ try {
856
+ const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
857
+ headers: {
858
+ Authorization: `Bearer ${accessToken}`,
859
+ },
860
+ });
861
+ if (!response.ok) {
862
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to fetch user info', this.provider);
863
+ }
864
+ return await response.json();
865
+ }
866
+ catch (error) {
867
+ if (error instanceof AuthError) {
868
+ throw error;
869
+ }
870
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to fetch user info', this.provider, error);
871
+ }
872
+ }
873
+ async loadGoogleIdentityServices() {
874
+ var _a, _b;
875
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2) {
876
+ return;
877
+ }
878
+ return new Promise((resolve, reject) => {
879
+ const script = document.createElement('script');
880
+ script.src = 'https://accounts.google.com/gsi/client';
881
+ script.async = true;
882
+ script.defer = true;
883
+ script.onload = () => {
884
+ var _a, _b;
885
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2) {
886
+ resolve();
887
+ }
888
+ else {
889
+ reject(new Error('Google Identity Services failed to load'));
890
+ }
891
+ };
892
+ script.onerror = () => {
893
+ reject(new Error('Failed to load Google Identity Services'));
894
+ };
895
+ document.head.appendChild(script);
896
+ });
897
+ }
898
+ mapGoogleError(error) {
899
+ const errorMap = {
900
+ 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
901
+ 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
902
+ 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
903
+ 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
904
+ 'server_error': exports.AuthErrorCode.SERVER_ERROR,
905
+ 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
906
+ 'popup_closed_by_user': exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
907
+ 'popup_blocked': exports.AuthErrorCode.POPUP_BLOCKED,
908
+ };
909
+ return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
910
+ }
911
+ createAuthUser(userInfo, tokenResponse) {
912
+ return {
913
+ uid: userInfo.sub,
914
+ email: userInfo.email,
915
+ emailVerified: userInfo.email_verified || false,
916
+ displayName: userInfo.name,
917
+ photoURL: userInfo.picture,
918
+ phoneNumber: null,
919
+ isAnonymous: false,
920
+ tenantId: null,
921
+ providerData: [{
922
+ providerId: exports.AuthProvider.GOOGLE,
923
+ uid: userInfo.sub,
924
+ displayName: userInfo.name,
925
+ email: userInfo.email,
926
+ phoneNumber: null,
927
+ photoURL: userInfo.picture,
928
+ }],
929
+ metadata: {
930
+ creationTime: new Date().toISOString(),
931
+ lastSignInTime: new Date().toISOString(),
932
+ },
933
+ refreshToken: tokenResponse.refresh_token,
934
+ };
935
+ }
936
+ }
937
+
938
+ class AppleAuthProviderWeb extends OAuthProvider {
939
+ constructor(config) {
940
+ super(config);
941
+ this.initPromise = null;
942
+ }
943
+ getOAuthConfig() {
944
+ const options = this.options;
945
+ return {
946
+ clientId: options.clientId,
947
+ redirectUri: options.redirectUri,
948
+ authorizationEndpoint: 'https://appleid.apple.com/auth/authorize',
949
+ tokenEndpoint: 'https://appleid.apple.com/auth/token',
950
+ scopes: this.mapAppleScopes(options.scopes),
951
+ responseType: options.responseType || 'code id_token',
952
+ additionalParams: {
953
+ response_mode: options.responseMode || 'form_post',
954
+ },
955
+ };
956
+ }
957
+ async initialize() {
958
+ if (this.isInitialized) {
959
+ return;
960
+ }
961
+ if (this.initPromise) {
962
+ return this.initPromise;
963
+ }
964
+ this.initPromise = this._initialize();
965
+ try {
966
+ await this.initPromise;
967
+ }
968
+ finally {
969
+ this.initPromise = null;
970
+ }
971
+ }
972
+ async _initialize() {
973
+ const options = this.options;
974
+ try {
975
+ // Load Apple JS SDK
976
+ await this.loadAppleSDK();
977
+ // Initialize Apple ID auth
978
+ window.AppleID.auth.init({
979
+ clientId: options.clientId,
980
+ scope: this.mapAppleScopes(options.scopes).join(' '),
981
+ redirectURI: options.redirectUri,
982
+ state: options.state,
983
+ nonce: options.nonce,
984
+ usePopup: options.usePopup !== false, // Default to true
985
+ });
986
+ // Load previously authenticated user
987
+ await this.loadCurrentUser();
988
+ this.isInitialized = true;
989
+ this.logger.info('Apple Auth provider initialized');
990
+ }
991
+ catch (error) {
992
+ this.logger.error('Failed to initialize Apple Auth', error);
993
+ throw AuthError.fromError(error, this.provider);
994
+ }
995
+ }
996
+ async signIn(options) {
997
+ var _a, _b, _c;
998
+ this.validateInitialized();
999
+ try {
1000
+ const appleOptions = this.options;
1001
+ // Generate state and nonce for security
1002
+ const state = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.state) || this.generateSecureRandomString();
1003
+ const nonce = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.nonce) || this.generateSecureRandomString();
1004
+ // Store state and nonce for validation
1005
+ await this.storage.set(`${this.provider}_oauth_state`, state);
1006
+ await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
1007
+ // Configure sign-in options
1008
+ const signInConfig = {
1009
+ clientId: appleOptions.clientId,
1010
+ scope: this.mapAppleScopes(((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.scopes) || appleOptions.scopes).join(' '),
1011
+ redirectURI: appleOptions.redirectUri,
1012
+ state,
1013
+ nonce,
1014
+ usePopup: appleOptions.usePopup !== false,
1015
+ };
1016
+ // Perform sign in
1017
+ const response = await window.AppleID.auth.signIn(signInConfig);
1018
+ // Validate response
1019
+ await this.validateAppleResponse(response, state, nonce);
1020
+ // Parse user information from response
1021
+ const user = this.createAppleAuthUser(response);
1022
+ const credential = this.createAppleCredential(response);
1023
+ // Save user and credential
1024
+ await this.setCurrentUser(user);
1025
+ await this.saveCredential(credential);
1026
+ return this.createAuthResult(user, credential, response.user ? true : false);
1027
+ }
1028
+ catch (error) {
1029
+ this.logger.error('Apple sign in failed', error);
1030
+ if (error && typeof error === 'object' && 'error' in error) {
1031
+ throw new AuthError(this.mapAppleError(error.error), error.error, this.provider);
1032
+ }
1033
+ throw AuthError.fromError(error, this.provider);
1034
+ }
1035
+ finally {
1036
+ // Clean up temporary storage
1037
+ await this.storage.remove(`${this.provider}_oauth_state`);
1038
+ await this.storage.remove(`${this.provider}_oauth_nonce`);
1039
+ }
1040
+ }
1041
+ async signOut(_options) {
1042
+ this.validateInitialized();
1043
+ try {
1044
+ // Apple doesn't provide a sign-out method in their JS SDK
1045
+ // Just clear local data
1046
+ await this.clearStoredData();
1047
+ await this.setCurrentUser(null);
1048
+ this.logger.info('Signed out from Apple');
1049
+ }
1050
+ catch (error) {
1051
+ this.logger.error('Failed to sign out from Apple', error);
1052
+ throw AuthError.fromError(error, this.provider);
1053
+ }
1054
+ }
1055
+ async isSupported() {
1056
+ // Check if we're in a browser environment
1057
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
1058
+ return false;
1059
+ }
1060
+ // Check if we're on HTTPS (required for Apple Sign In)
1061
+ if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost') {
1062
+ return false;
1063
+ }
1064
+ return true;
1065
+ }
1066
+ async linkAccount(options) {
1067
+ // For web, linking is the same as signing in
1068
+ return this.signIn(options);
1069
+ }
1070
+ async unlinkAccount(_options) {
1071
+ // For web, unlinking is the same as signing out
1072
+ await this.signOut();
1073
+ }
1074
+ async openAuthorizationUrl(_url) {
1075
+ // This method is not used in Apple JS SDK flow
1076
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Direct OAuth flow not supported for Apple. Use signIn method instead.', this.provider);
1077
+ }
1078
+ async parseUserFromTokenResponse(response) {
1079
+ // Apple provides user info directly in the authorization response
1080
+ return response.user || {};
1081
+ }
1082
+ async loadAppleSDK() {
1083
+ var _a;
1084
+ if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
1085
+ return;
1086
+ }
1087
+ return new Promise((resolve, reject) => {
1088
+ const script = document.createElement('script');
1089
+ script.src = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
1090
+ script.async = true;
1091
+ script.defer = true;
1092
+ script.onload = () => {
1093
+ var _a;
1094
+ if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
1095
+ resolve();
1096
+ }
1097
+ else {
1098
+ reject(new Error('Apple ID SDK failed to load'));
1099
+ }
1100
+ };
1101
+ script.onerror = () => {
1102
+ reject(new Error('Failed to load Apple ID SDK'));
1103
+ };
1104
+ document.head.appendChild(script);
1105
+ });
1106
+ }
1107
+ mapAppleScopes(scopes) {
1108
+ if (!scopes || scopes.length === 0) {
1109
+ return [];
1110
+ }
1111
+ return scopes.map(scope => {
1112
+ switch (scope) {
1113
+ case exports.AppleAuthScope.EMAIL:
1114
+ return 'email';
1115
+ case exports.AppleAuthScope.NAME:
1116
+ return 'name';
1117
+ default:
1118
+ return scope;
1119
+ }
1120
+ });
1121
+ }
1122
+ async validateAppleResponse(response, expectedState, _expectedNonce) {
1123
+ if (response.error) {
1124
+ throw new AuthError(this.mapAppleError(response.error), response.error, this.provider);
1125
+ }
1126
+ if (response.state !== expectedState) {
1127
+ throw new AuthError(exports.AuthErrorCode.INVALID_STATE, 'OAuth state mismatch', this.provider);
1128
+ }
1129
+ // ID token validation with nonce would be done here
1130
+ // For production, you should validate the ID token on your backend
1131
+ }
1132
+ createAppleAuthUser(response) {
1133
+ var _a, _b, _c, _d;
1134
+ const user = response.user || {};
1135
+ const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
1136
+ // Parse ID token claims (in production, do this on backend)
1137
+ let claims = {};
1138
+ if (idToken) {
1139
+ try {
1140
+ const payload = idToken.split('.')[1];
1141
+ claims = JSON.parse(atob(payload));
1142
+ }
1143
+ catch (error) {
1144
+ this.logger.error('Failed to parse ID token', error);
1145
+ }
1146
+ }
1147
+ return {
1148
+ uid: claims.sub || ((_b = response.authorization) === null || _b === void 0 ? void 0 : _b.code) || this.generateUniqueId(),
1149
+ email: user.email || claims.email || null,
1150
+ emailVerified: claims.email_verified || false,
1151
+ displayName: user.name ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim() : null,
1152
+ photoURL: null, // Apple doesn't provide profile photos
1153
+ phoneNumber: null,
1154
+ isAnonymous: false,
1155
+ tenantId: null,
1156
+ providerData: [{
1157
+ providerId: exports.AuthProvider.APPLE,
1158
+ uid: claims.sub || ((_c = response.authorization) === null || _c === void 0 ? void 0 : _c.code),
1159
+ displayName: user.name ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim() : null,
1160
+ email: user.email || claims.email || null,
1161
+ phoneNumber: null,
1162
+ photoURL: null,
1163
+ }],
1164
+ metadata: {
1165
+ creationTime: new Date().toISOString(),
1166
+ lastSignInTime: new Date().toISOString(),
1167
+ },
1168
+ refreshToken: (_d = response.authorization) === null || _d === void 0 ? void 0 : _d.refresh_token,
1169
+ };
1170
+ }
1171
+ createAppleCredential(response) {
1172
+ var _a, _b, _c, _d, _e;
1173
+ return {
1174
+ providerId: exports.AuthProvider.APPLE,
1175
+ signInMethod: 'oauth',
1176
+ accessToken: (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.access_token,
1177
+ idToken: (_b = response.authorization) === null || _b === void 0 ? void 0 : _b.id_token,
1178
+ refreshToken: (_c = response.authorization) === null || _c === void 0 ? void 0 : _c.refresh_token,
1179
+ expiresAt: ((_d = response.authorization) === null || _d === void 0 ? void 0 : _d.expires_in)
1180
+ ? this.calculateTokenExpiry(response.authorization.expires_in)
1181
+ : undefined,
1182
+ tokenType: 'Bearer',
1183
+ scope: (_e = response.authorization) === null || _e === void 0 ? void 0 : _e.scope,
1184
+ rawNonce: response.nonce,
1185
+ };
1186
+ }
1187
+ mapAppleError(error) {
1188
+ const errorMap = {
1189
+ 'user_cancelled_authorize': exports.AuthErrorCode.USER_CANCELLED,
1190
+ 'popup_closed_by_user': exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
1191
+ 'popup_blocked': exports.AuthErrorCode.POPUP_BLOCKED,
1192
+ 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
1193
+ 'invalid_client': exports.AuthErrorCode.CLIENT_NOT_FOUND,
1194
+ 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
1195
+ 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
1196
+ 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
1197
+ 'unsupported_response_type': exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
1198
+ 'server_error': exports.AuthErrorCode.SERVER_ERROR,
1199
+ 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
1200
+ };
1201
+ return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
1202
+ }
1203
+ }
1204
+
1205
+ class ProviderFactory {
1206
+ static async createProvider(config, storage, logger, persistence) {
1207
+ const providerConfig = {
1208
+ provider: config.provider,
1209
+ options: config.options,
1210
+ storage,
1211
+ logger,
1212
+ persistence,
1213
+ };
1214
+ switch (config.provider) {
1215
+ case exports.AuthProvider.GOOGLE:
1216
+ return new GoogleAuthProviderWeb(providerConfig);
1217
+ case exports.AuthProvider.APPLE:
1218
+ return new AppleAuthProviderWeb(providerConfig);
1219
+ case exports.AuthProvider.MICROSOFT:
1220
+ // TODO: Implement Microsoft provider
1221
+ logger.warn('Microsoft provider not yet implemented');
1222
+ return null;
1223
+ case exports.AuthProvider.FACEBOOK:
1224
+ // TODO: Implement Facebook provider
1225
+ logger.warn('Facebook provider not yet implemented');
1226
+ return null;
1227
+ case exports.AuthProvider.GITHUB:
1228
+ // TODO: Implement GitHub provider
1229
+ logger.warn('GitHub provider not yet implemented');
1230
+ return null;
1231
+ case exports.AuthProvider.SLACK:
1232
+ // TODO: Implement Slack provider
1233
+ logger.warn('Slack provider not yet implemented');
1234
+ return null;
1235
+ case exports.AuthProvider.LINKEDIN:
1236
+ // TODO: Implement LinkedIn provider
1237
+ logger.warn('LinkedIn provider not yet implemented');
1238
+ return null;
1239
+ case exports.AuthProvider.FIREBASE:
1240
+ // TODO: Implement Firebase provider
1241
+ logger.warn('Firebase provider not yet implemented');
1242
+ return null;
1243
+ case exports.AuthProvider.EMAIL_MAGIC_LINK:
1244
+ // TODO: Implement Email Magic Link provider
1245
+ logger.warn('Email Magic Link provider not yet implemented');
1246
+ return null;
1247
+ case exports.AuthProvider.SMS:
1248
+ // TODO: Implement SMS provider
1249
+ logger.warn('SMS provider not yet implemented');
1250
+ return null;
1251
+ case exports.AuthProvider.EMAIL_PASSWORD:
1252
+ // TODO: Implement Email/Password provider
1253
+ logger.warn('Email/Password provider not yet implemented');
1254
+ return null;
1255
+ case exports.AuthProvider.PHONE_PASSWORD:
1256
+ // TODO: Implement Phone/Password provider
1257
+ logger.warn('Phone/Password provider not yet implemented');
1258
+ return null;
1259
+ case exports.AuthProvider.USERNAME_PASSWORD:
1260
+ // TODO: Implement Username/Password provider
1261
+ logger.warn('Username/Password provider not yet implemented');
1262
+ return null;
1263
+ case exports.AuthProvider.EMAIL_CODE:
1264
+ // TODO: Implement Email Code provider
1265
+ logger.warn('Email Code provider not yet implemented');
1266
+ return null;
1267
+ case exports.AuthProvider.BIOMETRIC:
1268
+ // TODO: Implement Biometric provider
1269
+ logger.warn('Biometric provider not yet implemented');
1270
+ return null;
1271
+ default:
1272
+ logger.error(`Unknown provider: ${config.provider}`);
1273
+ return null;
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ class CapacitorAuthManagerWeb extends core.WebPlugin {
1279
+ constructor() {
1280
+ super();
1281
+ this.providers = new Map();
1282
+ this.isInitialized = false;
1283
+ this.currentProvider = null;
1284
+ this.tokenRefreshTimers = new Map();
1285
+ this.autoRefreshToken = true;
1286
+ this.tokenRefreshBuffer = 300000; // 5 minutes before expiry
1287
+ this.authStateEmitter = new EventEmitter();
1288
+ this.storage = new WebStorage(exports.AuthPersistence.LOCAL);
1289
+ this.logger = new Logger({
1290
+ enableLogging: false,
1291
+ logLevel: 'info',
1292
+ prefix: 'CapAuthManager',
1293
+ });
1294
+ }
1295
+ async initialize(options) {
1296
+ var _a, _b;
1297
+ if (this.isInitialized) {
1298
+ this.logger.warn('Auth manager already initialized');
1299
+ return;
1300
+ }
1301
+ try {
1302
+ // Configure logger
1303
+ if (options.enableLogging !== undefined) {
1304
+ this.logger.setEnabled(options.enableLogging);
1305
+ }
1306
+ if (options.logLevel) {
1307
+ this.logger.setLogLevel(options.logLevel);
1308
+ }
1309
+ // Configure persistence
1310
+ if (options.persistence) {
1311
+ this.storage = new WebStorage(options.persistence);
1312
+ }
1313
+ // Configure auto refresh
1314
+ this.autoRefreshToken = (_a = options.autoRefreshToken) !== null && _a !== void 0 ? _a : true;
1315
+ this.tokenRefreshBuffer = (_b = options.tokenRefreshBuffer) !== null && _b !== void 0 ? _b : 300000;
1316
+ // Initialize providers
1317
+ for (const providerConfig of options.providers) {
1318
+ await this.initializeProvider(providerConfig);
1319
+ }
1320
+ // Load last used provider
1321
+ const lastProvider = await this.storage.get('last_auth_provider');
1322
+ if (lastProvider) {
1323
+ this.currentProvider = lastProvider;
1324
+ }
1325
+ this.isInitialized = true;
1326
+ this.logger.info('Auth manager initialized successfully');
1327
+ }
1328
+ catch (error) {
1329
+ this.logger.error('Failed to initialize auth manager', error);
1330
+ throw AuthError.fromError(error);
1331
+ }
1332
+ }
1333
+ async signIn(options) {
1334
+ this.validateInitialized();
1335
+ const provider = this.getProvider(options.provider);
1336
+ try {
1337
+ this.logger.info(`Signing in with ${options.provider}`);
1338
+ const result = await provider.signIn(options);
1339
+ // Set as current provider
1340
+ this.currentProvider = options.provider;
1341
+ await this.storage.set('last_auth_provider', options.provider);
1342
+ // Setup token refresh if needed
1343
+ if (this.autoRefreshToken && result.credential.refreshToken) {
1344
+ this.setupTokenRefresh(options.provider, result.credential);
1345
+ }
1346
+ // Forward auth state change
1347
+ this.authStateEmitter.emit(result.user);
1348
+ return result;
1349
+ }
1350
+ catch (error) {
1351
+ this.logger.error(`Sign in failed for ${options.provider}`, error);
1352
+ throw AuthError.fromError(error, options.provider);
1353
+ }
1354
+ }
1355
+ async signOut(options) {
1356
+ this.validateInitialized();
1357
+ try {
1358
+ if (options === null || options === void 0 ? void 0 : options.provider) {
1359
+ // Sign out from specific provider
1360
+ const provider = this.getProvider(options.provider);
1361
+ await provider.signOut(options);
1362
+ // Cancel token refresh
1363
+ this.cancelTokenRefresh(options.provider);
1364
+ }
1365
+ else if (this.currentProvider) {
1366
+ // Sign out from current provider
1367
+ const provider = this.getProvider(this.currentProvider);
1368
+ await provider.signOut(options);
1369
+ // Cancel token refresh
1370
+ this.cancelTokenRefresh(this.currentProvider);
1371
+ // Clear current provider
1372
+ this.currentProvider = null;
1373
+ await this.storage.remove('last_auth_provider');
1374
+ }
1375
+ else {
1376
+ // Sign out from all providers
1377
+ for (const [providerId, provider] of this.providers) {
1378
+ try {
1379
+ await provider.signOut(options);
1380
+ this.cancelTokenRefresh(providerId);
1381
+ }
1382
+ catch (error) {
1383
+ this.logger.error(`Failed to sign out from ${providerId}`, error);
1384
+ }
1385
+ }
1386
+ this.currentProvider = null;
1387
+ await this.storage.remove('last_auth_provider');
1388
+ }
1389
+ // Emit null user
1390
+ this.authStateEmitter.emit(null);
1391
+ }
1392
+ catch (error) {
1393
+ this.logger.error('Sign out failed', error);
1394
+ throw AuthError.fromError(error);
1395
+ }
1396
+ }
1397
+ async getCurrentUser() {
1398
+ this.validateInitialized();
1399
+ if (this.currentProvider) {
1400
+ const provider = this.getProvider(this.currentProvider);
1401
+ return provider.getCurrentUser();
1402
+ }
1403
+ // Try to get user from any provider
1404
+ for (const provider of this.providers.values()) {
1405
+ const user = await provider.getCurrentUser();
1406
+ if (user) {
1407
+ return user;
1408
+ }
1409
+ }
1410
+ return null;
1411
+ }
1412
+ async refreshToken(options) {
1413
+ this.validateInitialized();
1414
+ const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
1415
+ if (!providerId) {
1416
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for token refresh');
1417
+ }
1418
+ const provider = this.getProvider(providerId);
1419
+ try {
1420
+ const result = await provider.refreshToken(options);
1421
+ // Setup new token refresh
1422
+ if (this.autoRefreshToken && result.credential.refreshToken) {
1423
+ this.setupTokenRefresh(providerId, result.credential);
1424
+ }
1425
+ return result;
1426
+ }
1427
+ catch (error) {
1428
+ this.logger.error(`Token refresh failed for ${providerId}`, error);
1429
+ throw AuthError.fromError(error, providerId);
1430
+ }
1431
+ }
1432
+ async addAuthStateListener(callback) {
1433
+ const unsubscribe = this.authStateEmitter.subscribe(callback);
1434
+ // Create a Capacitor-compatible listener handle
1435
+ const handle = {
1436
+ remove: async () => {
1437
+ unsubscribe();
1438
+ }
1439
+ };
1440
+ // Emit current user state
1441
+ const currentUser = await this.getCurrentUser();
1442
+ callback(currentUser);
1443
+ return handle;
1444
+ }
1445
+ async removeAllListeners() {
1446
+ this.authStateEmitter.clear();
1447
+ // Also clear provider listeners
1448
+ for (const provider of this.providers.values()) {
1449
+ provider.dispose();
1450
+ }
1451
+ }
1452
+ async isSupported(options) {
1453
+ try {
1454
+ if (!this.providers.has(options.provider)) {
1455
+ return {
1456
+ isSupported: false,
1457
+ reason: 'Provider not configured',
1458
+ availableProviders: Array.from(this.providers.keys()),
1459
+ };
1460
+ }
1461
+ const provider = this.getProvider(options.provider);
1462
+ const isSupported = await provider.isSupported();
1463
+ return {
1464
+ isSupported,
1465
+ reason: isSupported ? undefined : 'Provider not supported on this platform',
1466
+ availableProviders: Array.from(this.providers.keys()),
1467
+ };
1468
+ }
1469
+ catch (error) {
1470
+ return {
1471
+ isSupported: false,
1472
+ reason: error instanceof Error ? error.message : 'Unknown error',
1473
+ availableProviders: Array.from(this.providers.keys()),
1474
+ };
1475
+ }
1476
+ }
1477
+ async configure(options) {
1478
+ this.validateInitialized();
1479
+ const providerConfig = {
1480
+ provider: options.provider,
1481
+ options: options.options,
1482
+ };
1483
+ await this.initializeProvider(providerConfig);
1484
+ }
1485
+ async linkAccount(options) {
1486
+ this.validateInitialized();
1487
+ const provider = this.getProvider(options.provider);
1488
+ try {
1489
+ return await provider.linkAccount(options);
1490
+ }
1491
+ catch (error) {
1492
+ this.logger.error(`Account linking failed for ${options.provider}`, error);
1493
+ throw AuthError.fromError(error, options.provider);
1494
+ }
1495
+ }
1496
+ async unlinkAccount(options) {
1497
+ this.validateInitialized();
1498
+ const provider = this.getProvider(options.provider);
1499
+ try {
1500
+ await provider.unlinkAccount(options);
1501
+ }
1502
+ catch (error) {
1503
+ this.logger.error(`Account unlinking failed for ${options.provider}`, error);
1504
+ throw AuthError.fromError(error, options.provider);
1505
+ }
1506
+ }
1507
+ async sendPasswordResetEmail(_options) {
1508
+ this.validateInitialized();
1509
+ // This would typically be implemented by specific providers
1510
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Password reset not implemented for current provider');
1511
+ }
1512
+ async sendEmailVerification(_options) {
1513
+ this.validateInitialized();
1514
+ // This would typically be implemented by specific providers
1515
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email verification not implemented for current provider');
1516
+ }
1517
+ async sendSmsCode(_options) {
1518
+ this.validateInitialized();
1519
+ // This would typically be implemented by SMS provider
1520
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication not implemented');
1521
+ }
1522
+ async verifySmsCode(_options) {
1523
+ this.validateInitialized();
1524
+ // This would typically be implemented by SMS provider
1525
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication not implemented');
1526
+ }
1527
+ async sendEmailCode(_options) {
1528
+ this.validateInitialized();
1529
+ // This would typically be implemented by email code provider
1530
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication not implemented');
1531
+ }
1532
+ async verifyEmailCode(_options) {
1533
+ this.validateInitialized();
1534
+ // This would typically be implemented by email code provider
1535
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication not implemented');
1536
+ }
1537
+ async updateProfile(_options) {
1538
+ this.validateInitialized();
1539
+ if (!this.currentProvider) {
1540
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No authenticated user found');
1541
+ }
1542
+ // This would typically be implemented by specific providers
1543
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Profile update not implemented for current provider');
1544
+ }
1545
+ async deleteAccount(_options) {
1546
+ this.validateInitialized();
1547
+ if (!this.currentProvider) {
1548
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No authenticated user found');
1549
+ }
1550
+ // This would typically be implemented by specific providers
1551
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account deletion not implemented for current provider');
1552
+ }
1553
+ async getIdToken(options) {
1554
+ this.validateInitialized();
1555
+ const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
1556
+ if (!providerId) {
1557
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for ID token');
1558
+ }
1559
+ // This would typically be implemented by specific providers
1560
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'ID token retrieval not implemented for current provider');
1561
+ }
1562
+ async setCustomParameters(options) {
1563
+ this.validateInitialized();
1564
+ // Store custom parameters for the provider
1565
+ await this.storage.set(`${options.provider}_custom_params`, JSON.stringify(options.parameters));
1566
+ }
1567
+ async revokeAccess(options) {
1568
+ this.validateInitialized();
1569
+ const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
1570
+ if (!providerId) {
1571
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for access revocation');
1572
+ }
1573
+ const provider = this.getProvider(providerId);
1574
+ try {
1575
+ await provider.revokeAccess(options === null || options === void 0 ? void 0 : options.token);
1576
+ }
1577
+ catch (error) {
1578
+ this.logger.error(`Access revocation failed for ${providerId}`, error);
1579
+ throw AuthError.fromError(error, providerId);
1580
+ }
1581
+ }
1582
+ validateInitialized() {
1583
+ if (!this.isInitialized) {
1584
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Auth manager not initialized. Call initialize() first.');
1585
+ }
1586
+ }
1587
+ getProvider(providerId) {
1588
+ const provider = this.providers.get(providerId);
1589
+ if (!provider) {
1590
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, `Provider ${providerId} not configured`);
1591
+ }
1592
+ return provider;
1593
+ }
1594
+ async initializeProvider(config) {
1595
+ try {
1596
+ // Dynamically import provider implementation
1597
+ const provider = await this.createProvider(config);
1598
+ if (provider) {
1599
+ await provider.initialize();
1600
+ // Forward auth state changes
1601
+ provider.addAuthStateListener((user) => {
1602
+ if (user) {
1603
+ this.authStateEmitter.emit(user);
1604
+ }
1605
+ });
1606
+ this.providers.set(config.provider, provider);
1607
+ this.logger.info(`Provider ${config.provider} initialized`);
1608
+ }
1609
+ }
1610
+ catch (error) {
1611
+ this.logger.error(`Failed to initialize provider ${config.provider}`, error);
1612
+ throw error;
1613
+ }
1614
+ }
1615
+ async createProvider(config) {
1616
+ return ProviderFactory.createProvider(config, this.storage, this.logger, this.storage instanceof WebStorage ? exports.AuthPersistence.LOCAL : exports.AuthPersistence.NONE);
1617
+ }
1618
+ setupTokenRefresh(provider, credential) {
1619
+ // Cancel existing refresh timer
1620
+ this.cancelTokenRefresh(provider);
1621
+ if (!credential.expiresAt || !credential.refreshToken) {
1622
+ return;
1623
+ }
1624
+ const refreshTime = credential.expiresAt - this.tokenRefreshBuffer - Date.now();
1625
+ if (refreshTime > 0) {
1626
+ const timer = setTimeout(async () => {
1627
+ try {
1628
+ await this.refreshToken({ provider });
1629
+ }
1630
+ catch (error) {
1631
+ this.logger.error(`Auto token refresh failed for ${provider}`, error);
1632
+ }
1633
+ }, refreshTime);
1634
+ this.tokenRefreshTimers.set(provider, timer);
1635
+ }
1636
+ }
1637
+ cancelTokenRefresh(provider) {
1638
+ const timer = this.tokenRefreshTimers.get(provider);
1639
+ if (timer) {
1640
+ clearTimeout(timer);
1641
+ this.tokenRefreshTimers.delete(provider);
1642
+ }
1643
+ }
1644
+ }
1645
+
1646
+ var web = /*#__PURE__*/Object.freeze({
1647
+ __proto__: null,
1648
+ CapacitorAuthManagerWeb: CapacitorAuthManagerWeb
1649
+ });
1650
+
1651
+ exports.CapacitorAuthManager = CapacitorAuthManager;
1652
+
1653
+ return exports;
1654
+
1655
+ })({}, capacitorExports);
7
1656
  //# sourceMappingURL=plugin.js.map