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