capacitor-auth-manager 2.4.4 → 3.1.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 (86) hide show
  1. package/AI-INTEGRATION-GUIDE.md +176 -0
  2. package/CHANGELOG.md +143 -0
  3. package/CapacitorAuthManager.podspec +3 -3
  4. package/README.md +99 -76
  5. package/android/build.gradle +23 -25
  6. package/android/consumer-rules.pro +14 -0
  7. package/android/proguard-rules.pro +5 -30
  8. package/android/src/main/AndroidManifest.xml +4 -9
  9. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ActivityLauncher.java +26 -0
  10. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthErrorCodes.java +32 -0
  11. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthException.java +34 -0
  12. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +46 -25
  13. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +62 -40
  14. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +124 -66
  15. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +225 -374
  16. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleCredentialManagerSignIn.java +175 -0
  17. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleLegacySignIn.java +133 -0
  18. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleProfileCallback.java +8 -0
  19. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleResultMapper.java +158 -0
  20. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +11 -3
  21. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/SigningDiagnostics.java +76 -0
  22. package/dist/angular.cjs.js +421 -3376
  23. package/dist/core.cjs.js +589 -149
  24. package/dist/esm/angular/auth.guard.d.ts +1 -1
  25. package/dist/esm/angular/auth.module.d.ts +1 -1
  26. package/dist/esm/angular/auth.module.js +1 -1
  27. package/dist/esm/angular/auth.service.d.ts +2 -2
  28. package/dist/esm/angular/auth.service.js +1 -1
  29. package/dist/esm/angular/index.d.ts +4 -4
  30. package/dist/esm/angular/index.js +4 -4
  31. package/dist/esm/capacitor-plugin.d.ts +2 -3
  32. package/dist/esm/capacitor-plugin.js +14 -4
  33. package/dist/esm/core/auth-manager.d.ts +20 -2
  34. package/dist/esm/core/auth-manager.js +68 -12
  35. package/dist/esm/core/index.d.ts +5 -4
  36. package/dist/esm/core/index.js +5 -4
  37. package/dist/esm/core/provider-manifests.d.ts +1 -1
  38. package/dist/esm/core/provider-manifests.js +12 -13
  39. package/dist/esm/core/provider-registry.d.ts +8 -5
  40. package/dist/esm/core/provider-registry.js +41 -10
  41. package/dist/esm/core/types.d.ts +2 -2
  42. package/dist/esm/definitions.d.ts +29 -0
  43. package/dist/esm/index.d.ts +12 -12
  44. package/dist/esm/index.js +7 -7
  45. package/dist/esm/package.json +1 -0
  46. package/dist/esm/providers/base-provider.d.ts +7 -8
  47. package/dist/esm/providers/base-provider.js +7 -8
  48. package/dist/esm/providers/native/google-native-provider.d.ts +13 -2
  49. package/dist/esm/providers/native/google-native-provider.js +50 -6
  50. package/dist/esm/providers/oauth-provider.d.ts +2 -2
  51. package/dist/esm/providers/oauth-provider.js +3 -3
  52. package/dist/esm/providers/provider-factory.d.ts +5 -5
  53. package/dist/esm/providers/provider-factory.js +2 -2
  54. package/dist/esm/providers/web/google-provider.d.ts +74 -18
  55. package/dist/esm/providers/web/google-provider.js +391 -117
  56. package/dist/esm/providers/web/index.d.ts +1 -1
  57. package/dist/esm/providers/web/index.js +1 -1
  58. package/dist/esm/react/hooks.d.ts +2 -2
  59. package/dist/esm/react/hooks.js +2 -2
  60. package/dist/esm/react/index.d.ts +3 -3
  61. package/dist/esm/react/index.js +3 -3
  62. package/dist/esm/react/types.d.ts +1 -1
  63. package/dist/esm/utils/auth-error.d.ts +1 -1
  64. package/dist/esm/utils/auth-error.js +1 -1
  65. package/dist/esm/utils/event-emitter.d.ts +1 -1
  66. package/dist/esm/utils/event-emitter.js +1 -1
  67. package/dist/esm/utils/pending-verification-store.js +1 -1
  68. package/dist/esm/utils/storage.d.ts +2 -2
  69. package/dist/esm/utils/storage.js +31 -7
  70. package/dist/esm/vue/composables.d.ts +2 -2
  71. package/dist/esm/vue/composables.js +1 -1
  72. package/dist/esm/vue/index.d.ts +2 -2
  73. package/dist/esm/vue/index.js +2 -2
  74. package/dist/esm/web.d.ts +1 -1
  75. package/dist/esm/web.js +6 -6
  76. package/dist/plugin.cjs.js +291 -2771
  77. package/dist/plugin.js +585 -147
  78. package/dist/providers-web.cjs.js +1317 -0
  79. package/dist/react.cjs.js +310 -3265
  80. package/dist/vue.cjs.js +266 -3221
  81. package/ios/Plugin/AuthStorage.swift +3 -1
  82. package/ios/Plugin/GoogleAuthProvider.swift +7 -4
  83. package/ios/Plugin/Models.swift +28 -0
  84. package/ios/Plugin/Plugin.swift +64 -40
  85. package/package.json +54 -32
  86. package/scripts/configure.js +71 -325
@@ -1,8 +1,258 @@
1
1
  'use strict';
2
2
 
3
- var core = require('@capacitor/core');
3
+ var core = require('capacitor-auth-manager/core');
4
4
 
5
5
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
6
+ exports.AuthProvider = void 0;
7
+ (function (AuthProvider) {
8
+ AuthProvider["GOOGLE"] = "google";
9
+ AuthProvider["APPLE"] = "apple";
10
+ AuthProvider["MICROSOFT"] = "microsoft";
11
+ AuthProvider["FACEBOOK"] = "facebook";
12
+ AuthProvider["GITHUB"] = "github";
13
+ AuthProvider["SLACK"] = "slack";
14
+ AuthProvider["LINKEDIN"] = "linkedin";
15
+ AuthProvider["FIREBASE"] = "firebase";
16
+ AuthProvider["EMAIL_MAGIC_LINK"] = "email_magic_link";
17
+ AuthProvider["MAGIC_LINK"] = "magic-link";
18
+ AuthProvider["SMS"] = "sms";
19
+ AuthProvider["EMAIL_PASSWORD"] = "email-password";
20
+ AuthProvider["PHONE_PASSWORD"] = "phone_password";
21
+ AuthProvider["USERNAME_PASSWORD"] = "username_password";
22
+ AuthProvider["EMAIL_CODE"] = "email_code";
23
+ AuthProvider["BIOMETRIC"] = "biometric";
24
+ })(exports.AuthProvider || (exports.AuthProvider = {}));
25
+ // Additional provider values for backward compatibility
26
+ Object.assign(Object.assign({}, exports.AuthProvider), { 'magic-link': exports.AuthProvider.MAGIC_LINK, 'email-password': exports.AuthProvider.EMAIL_PASSWORD, sms: exports.AuthProvider.SMS, biometric: exports.AuthProvider.BIOMETRIC });
27
+ exports.AppleAuthScope = void 0;
28
+ (function (AppleAuthScope) {
29
+ AppleAuthScope["EMAIL"] = "email";
30
+ AppleAuthScope["NAME"] = "name";
31
+ })(exports.AppleAuthScope || (exports.AppleAuthScope = {}));
32
+ exports.BiometricType = void 0;
33
+ (function (BiometricType) {
34
+ BiometricType["FINGERPRINT"] = "fingerprint";
35
+ BiometricType["FACE_ID"] = "faceId";
36
+ BiometricType["TOUCH_ID"] = "touchId";
37
+ BiometricType["IRIS"] = "iris";
38
+ BiometricType["VOICE"] = "voice";
39
+ })(exports.BiometricType || (exports.BiometricType = {}));
40
+ exports.AuthPersistence = void 0;
41
+ (function (AuthPersistence) {
42
+ AuthPersistence["LOCAL"] = "local";
43
+ AuthPersistence["SESSION"] = "session";
44
+ AuthPersistence["NONE"] = "none";
45
+ })(exports.AuthPersistence || (exports.AuthPersistence = {}));
46
+ exports.AuthErrorCode = void 0;
47
+ (function (AuthErrorCode) {
48
+ AuthErrorCode["INVALID_CREDENTIALS"] = "auth/invalid-credentials";
49
+ AuthErrorCode["USER_NOT_FOUND"] = "auth/user-not-found";
50
+ AuthErrorCode["WRONG_PASSWORD"] = "auth/wrong-password";
51
+ AuthErrorCode["EMAIL_ALREADY_IN_USE"] = "auth/email-already-in-use";
52
+ AuthErrorCode["WEAK_PASSWORD"] = "auth/weak-password";
53
+ AuthErrorCode["NETWORK_ERROR"] = "auth/network-error";
54
+ AuthErrorCode["TOO_MANY_REQUESTS"] = "auth/too-many-requests";
55
+ AuthErrorCode["USER_DISABLED"] = "auth/user-disabled";
56
+ AuthErrorCode["OPERATION_NOT_ALLOWED"] = "auth/operation-not-allowed";
57
+ AuthErrorCode["INVALID_EMAIL"] = "auth/invalid-email";
58
+ AuthErrorCode["INVALID_PHONE_NUMBER"] = "auth/invalid-phone-number";
59
+ AuthErrorCode["INVALID_VERIFICATION_CODE"] = "auth/invalid-verification-code";
60
+ AuthErrorCode["EXPIRED_ACTION_CODE"] = "auth/expired-action-code";
61
+ AuthErrorCode["CREDENTIAL_ALREADY_IN_USE"] = "auth/credential-already-in-use";
62
+ AuthErrorCode["ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"] = "auth/account-exists-with-different-credential";
63
+ AuthErrorCode["REQUIRES_RECENT_LOGIN"] = "auth/requires-recent-login";
64
+ AuthErrorCode["PROVIDER_ALREADY_LINKED"] = "auth/provider-already-linked";
65
+ AuthErrorCode["NO_SUCH_PROVIDER"] = "auth/no-such-provider";
66
+ AuthErrorCode["INVALID_USER_TOKEN"] = "auth/invalid-user-token";
67
+ AuthErrorCode["TOKEN_EXPIRED"] = "auth/token-expired";
68
+ AuthErrorCode["USER_TOKEN_EXPIRED"] = "auth/user-token-expired";
69
+ AuthErrorCode["INVALID_API_KEY"] = "auth/invalid-api-key";
70
+ AuthErrorCode["USER_CANCELLED"] = "auth/user-cancelled";
71
+ AuthErrorCode["APP_NOT_AUTHORIZED"] = "auth/app-not-authorized";
72
+ AuthErrorCode["KEYCHAIN_ERROR"] = "auth/keychain-error";
73
+ AuthErrorCode["INTERNAL_ERROR"] = "auth/internal-error";
74
+ AuthErrorCode["BIOMETRIC_NOT_AVAILABLE"] = "auth/biometric-not-available";
75
+ AuthErrorCode["BIOMETRIC_NOT_ENROLLED"] = "auth/biometric-not-enrolled";
76
+ AuthErrorCode["BIOMETRIC_AUTHENTICATION_FAILED"] = "auth/biometric-authentication-failed";
77
+ AuthErrorCode["UNSUPPORTED_PROVIDER"] = "auth/unsupported-provider";
78
+ AuthErrorCode["MISSING_CONFIGURATION"] = "auth/missing-configuration";
79
+ AuthErrorCode["POPUP_BLOCKED"] = "auth/popup-blocked";
80
+ AuthErrorCode["POPUP_CLOSED_BY_USER"] = "auth/popup-closed-by-user";
81
+ AuthErrorCode["REDIRECT_CANCELLED_BY_USER"] = "auth/redirect-cancelled-by-user";
82
+ AuthErrorCode["MISSING_REDIRECT_URL"] = "auth/missing-redirect-url";
83
+ AuthErrorCode["INVALID_STATE"] = "auth/invalid-state";
84
+ AuthErrorCode["MISSING_CODE_VERIFIER"] = "auth/missing-code-verifier";
85
+ AuthErrorCode["INVALID_CODE_VERIFIER"] = "auth/invalid-code-verifier";
86
+ AuthErrorCode["MISSING_NONCE"] = "auth/missing-nonce";
87
+ AuthErrorCode["INVALID_NONCE"] = "auth/invalid-nonce";
88
+ AuthErrorCode["UNAUTHORIZED_DOMAIN"] = "auth/unauthorized-domain";
89
+ AuthErrorCode["INVALID_CONTINUE_URL"] = "auth/invalid-continue-url";
90
+ AuthErrorCode["MISSING_CONTINUE_URL"] = "auth/missing-continue-url";
91
+ AuthErrorCode["INVALID_DYNAMIC_LINK_DOMAIN"] = "auth/invalid-dynamic-link-domain";
92
+ AuthErrorCode["REJECTED_CREDENTIAL"] = "auth/rejected-credential";
93
+ AuthErrorCode["PHONE_NUMBER_ALREADY_EXISTS"] = "auth/phone-number-already-exists";
94
+ AuthErrorCode["QUOTA_EXCEEDED"] = "auth/quota-exceeded";
95
+ AuthErrorCode["CAPTCHA_CHECK_FAILED"] = "auth/captcha-check-failed";
96
+ AuthErrorCode["MISSING_CAPTCHA_TOKEN"] = "auth/missing-captcha-token";
97
+ AuthErrorCode["INVALID_CAPTCHA_TOKEN"] = "auth/invalid-captcha-token";
98
+ AuthErrorCode["MISSING_CLIENT_IDENTIFIER"] = "auth/missing-client-identifier";
99
+ AuthErrorCode["MISSING_OR_INVALID_NONCE"] = "auth/missing-or-invalid-nonce";
100
+ AuthErrorCode["INTERACTION_REQUIRED"] = "auth/interaction-required";
101
+ AuthErrorCode["LOGIN_REQUIRED"] = "auth/login-required";
102
+ AuthErrorCode["CONSENT_REQUIRED"] = "auth/consent-required";
103
+ AuthErrorCode["INVALID_GRANT"] = "auth/invalid-grant";
104
+ AuthErrorCode["UNSUPPORTED_GRANT_TYPE"] = "auth/unsupported-grant-type";
105
+ AuthErrorCode["PROVIDER_INIT_FAILED"] = "auth/provider-init-failed";
106
+ AuthErrorCode["SIGN_IN_FAILED"] = "auth/sign-in-failed";
107
+ AuthErrorCode["SIGN_OUT_FAILED"] = "auth/sign-out-failed";
108
+ AuthErrorCode["NO_AUTH_SESSION"] = "auth/no-auth-session";
109
+ AuthErrorCode["TOKEN_REFRESH_FAILED"] = "auth/token-refresh-failed";
110
+ AuthErrorCode["ACCESS_DENIED"] = "auth/access-denied";
111
+ AuthErrorCode["SERVER_ERROR"] = "auth/server-error";
112
+ AuthErrorCode["TEMPORARILY_UNAVAILABLE"] = "auth/temporarily-unavailable";
113
+ AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
114
+ AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
115
+ AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
116
+ AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
117
+ AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
118
+ // --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
119
+ // magic-link / biometric / email-password / username-password / phone-password) throw enum
120
+ // codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
121
+ AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
122
+ AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
123
+ AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
124
+ AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
125
+ AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
126
+ AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
127
+ AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
128
+ AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
129
+ AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
130
+ AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
131
+ AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
132
+ AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
133
+ AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
134
+ AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
135
+ AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
136
+ AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
137
+ AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
138
+ AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
139
+ AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
140
+ AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
141
+ AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
142
+ AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
143
+ AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
144
+ AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
145
+ AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
146
+ // The active provider does not implement an optional capability (e.g. token refresh).
147
+ // Same string the manager previously threw as a bare literal — now an enum member so
148
+ // consumers can switch on `AuthErrorCode.OPERATION_NOT_SUPPORTED` reliably.
149
+ AuthErrorCode["OPERATION_NOT_SUPPORTED"] = "auth/operation-not-supported";
150
+ // The provider is recognized but not yet enabled in this release. As of 2.4.1 the package ships
151
+ // a hardened Google provider and re-enables the remaining providers one at a time. Switch on this
152
+ // to detect a "coming soon" provider distinctly from an unknown one.
153
+ AuthErrorCode["PROVIDER_NOT_ENABLED"] = "auth/provider-not-enabled";
154
+ })(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
155
+
156
+ function getPlatformWindow() {
157
+ return typeof window !== 'undefined'
158
+ ? window
159
+ : undefined;
160
+ }
161
+ class PlatformDetector {
162
+ static getPlatform() {
163
+ // A cached NON-web result is final (native/electron never reverts to web). But a cached
164
+ // 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
165
+ // module first runs (the native bridge initializes asynchronously), so re-evaluate while
166
+ // the last verdict was 'web' to pick up a late native environment. See F-26.
167
+ if (this.platformInfo && this.platformInfo.platform !== 'web') {
168
+ return this.platformInfo;
169
+ }
170
+ const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
171
+ const platform = this.detectPlatform(userAgent);
172
+ this.platformInfo = {
173
+ platform,
174
+ isNative: platform === 'ios' || platform === 'android',
175
+ isWeb: platform === 'web',
176
+ isMobile: platform === 'ios' ||
177
+ platform === 'android' ||
178
+ this.isMobileWeb(userAgent),
179
+ isDesktop: platform === 'electron' ||
180
+ (platform === 'web' && !this.isMobileWeb(userAgent)),
181
+ userAgent,
182
+ };
183
+ return this.platformInfo;
184
+ }
185
+ /**
186
+ * Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
187
+ * result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
188
+ * initializes late). Most callers can rely on the automatic re-check while the cached value is
189
+ * still 'web'.
190
+ */
191
+ static reset() {
192
+ this.platformInfo = null;
193
+ }
194
+ static detectPlatform(userAgent) {
195
+ var _a, _b;
196
+ const win = getPlatformWindow();
197
+ // Check if running in Capacitor
198
+ if (win === null || win === void 0 ? void 0 : win.Capacitor) {
199
+ const capacitor = win.Capacitor;
200
+ if (capacitor.getPlatform) {
201
+ const platform = capacitor.getPlatform();
202
+ if (platform === 'ios' || platform === 'android') {
203
+ return platform;
204
+ }
205
+ }
206
+ }
207
+ // Check if running in Electron
208
+ if ((_b = (_a = win === null || win === void 0 ? void 0 : win.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron) {
209
+ return 'electron';
210
+ }
211
+ // Check for React Native
212
+ if (typeof navigator !== 'undefined' &&
213
+ navigator.product === 'ReactNative') {
214
+ if (/iPhone|iPad|iPod/i.test(userAgent)) {
215
+ return 'ios';
216
+ }
217
+ if (/Android/i.test(userAgent)) {
218
+ return 'android';
219
+ }
220
+ }
221
+ // Check for native iOS/Android webviews
222
+ if (/iPhone|iPad|iPod/i.test(userAgent) &&
223
+ /WebKit/i.test(userAgent) &&
224
+ !/Safari/i.test(userAgent)) {
225
+ return 'ios';
226
+ }
227
+ if (/Android/i.test(userAgent) && /wv/i.test(userAgent)) {
228
+ return 'android';
229
+ }
230
+ // Default to web
231
+ return 'web';
232
+ }
233
+ static isMobileWeb(userAgent) {
234
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
235
+ }
236
+ static isCapacitorAvailable() {
237
+ var _a;
238
+ return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
239
+ }
240
+ static async checkCapacitorPlugin(pluginName) {
241
+ var _a;
242
+ const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
243
+ if (!capacitor) {
244
+ return false;
245
+ }
246
+ try {
247
+ return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
248
+ }
249
+ catch (_b) {
250
+ return false;
251
+ }
252
+ }
253
+ }
254
+ PlatformDetector.platformInfo = null;
255
+
6
256
  /**
7
257
  * Reads a default log level from the build/runtime environment WITHOUT assuming a particular
8
258
  * bundler or host. Checked defensively (each access wrapped) so it is safe in:
@@ -165,212 +415,27 @@ const defaultLogger = new Logger({
165
415
  prefix: 'CapacitorAuthManager',
166
416
  });
167
417
 
168
- class EventEmitter {
418
+ class WebStorage {
169
419
  /**
170
- * @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
171
- * so emitter errors honour the package log level instead of writing to `console` directly.
172
- */
173
- constructor(logger = defaultLogger) {
174
- this.listeners = new Set();
175
- this.logger = logger;
176
- }
177
- emit(data) {
178
- this.listeners.forEach((listener) => {
179
- try {
180
- listener(data);
181
- }
182
- catch (error) {
183
- this.logger.error('Error in event listener:', error);
184
- }
185
- });
186
- }
187
- subscribe(listener) {
188
- this.listeners.add(listener);
189
- return () => {
190
- this.listeners.delete(listener);
191
- };
192
- }
193
- clear() {
194
- this.listeners.clear();
195
- }
196
- get listenerCount() {
197
- return this.listeners.size;
198
- }
199
- }
200
-
201
- exports.AuthProvider = void 0;
202
- (function (AuthProvider) {
203
- AuthProvider["GOOGLE"] = "google";
204
- AuthProvider["APPLE"] = "apple";
205
- AuthProvider["MICROSOFT"] = "microsoft";
206
- AuthProvider["FACEBOOK"] = "facebook";
207
- AuthProvider["GITHUB"] = "github";
208
- AuthProvider["SLACK"] = "slack";
209
- AuthProvider["LINKEDIN"] = "linkedin";
210
- AuthProvider["FIREBASE"] = "firebase";
211
- AuthProvider["EMAIL_MAGIC_LINK"] = "email_magic_link";
212
- AuthProvider["MAGIC_LINK"] = "magic-link";
213
- AuthProvider["SMS"] = "sms";
214
- AuthProvider["EMAIL_PASSWORD"] = "email-password";
215
- AuthProvider["PHONE_PASSWORD"] = "phone_password";
216
- AuthProvider["USERNAME_PASSWORD"] = "username_password";
217
- AuthProvider["EMAIL_CODE"] = "email_code";
218
- AuthProvider["BIOMETRIC"] = "biometric";
219
- })(exports.AuthProvider || (exports.AuthProvider = {}));
220
- // Additional provider values for backward compatibility
221
- Object.assign(Object.assign({}, exports.AuthProvider), { 'magic-link': exports.AuthProvider.MAGIC_LINK, 'email-password': exports.AuthProvider.EMAIL_PASSWORD, sms: exports.AuthProvider.SMS, biometric: exports.AuthProvider.BIOMETRIC });
222
- exports.AppleAuthScope = void 0;
223
- (function (AppleAuthScope) {
224
- AppleAuthScope["EMAIL"] = "email";
225
- AppleAuthScope["NAME"] = "name";
226
- })(exports.AppleAuthScope || (exports.AppleAuthScope = {}));
227
- exports.BiometricType = void 0;
228
- (function (BiometricType) {
229
- BiometricType["FINGERPRINT"] = "fingerprint";
230
- BiometricType["FACE_ID"] = "faceId";
231
- BiometricType["TOUCH_ID"] = "touchId";
232
- BiometricType["IRIS"] = "iris";
233
- BiometricType["VOICE"] = "voice";
234
- })(exports.BiometricType || (exports.BiometricType = {}));
235
- exports.AuthPersistence = void 0;
236
- (function (AuthPersistence) {
237
- AuthPersistence["LOCAL"] = "local";
238
- AuthPersistence["SESSION"] = "session";
239
- AuthPersistence["NONE"] = "none";
240
- })(exports.AuthPersistence || (exports.AuthPersistence = {}));
241
- exports.AuthErrorCode = void 0;
242
- (function (AuthErrorCode) {
243
- AuthErrorCode["INVALID_CREDENTIALS"] = "auth/invalid-credentials";
244
- AuthErrorCode["USER_NOT_FOUND"] = "auth/user-not-found";
245
- AuthErrorCode["WRONG_PASSWORD"] = "auth/wrong-password";
246
- AuthErrorCode["EMAIL_ALREADY_IN_USE"] = "auth/email-already-in-use";
247
- AuthErrorCode["WEAK_PASSWORD"] = "auth/weak-password";
248
- AuthErrorCode["NETWORK_ERROR"] = "auth/network-error";
249
- AuthErrorCode["TOO_MANY_REQUESTS"] = "auth/too-many-requests";
250
- AuthErrorCode["USER_DISABLED"] = "auth/user-disabled";
251
- AuthErrorCode["OPERATION_NOT_ALLOWED"] = "auth/operation-not-allowed";
252
- AuthErrorCode["INVALID_EMAIL"] = "auth/invalid-email";
253
- AuthErrorCode["INVALID_PHONE_NUMBER"] = "auth/invalid-phone-number";
254
- AuthErrorCode["INVALID_VERIFICATION_CODE"] = "auth/invalid-verification-code";
255
- AuthErrorCode["EXPIRED_ACTION_CODE"] = "auth/expired-action-code";
256
- AuthErrorCode["CREDENTIAL_ALREADY_IN_USE"] = "auth/credential-already-in-use";
257
- AuthErrorCode["ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"] = "auth/account-exists-with-different-credential";
258
- AuthErrorCode["REQUIRES_RECENT_LOGIN"] = "auth/requires-recent-login";
259
- AuthErrorCode["PROVIDER_ALREADY_LINKED"] = "auth/provider-already-linked";
260
- AuthErrorCode["NO_SUCH_PROVIDER"] = "auth/no-such-provider";
261
- AuthErrorCode["INVALID_USER_TOKEN"] = "auth/invalid-user-token";
262
- AuthErrorCode["TOKEN_EXPIRED"] = "auth/token-expired";
263
- AuthErrorCode["USER_TOKEN_EXPIRED"] = "auth/user-token-expired";
264
- AuthErrorCode["INVALID_API_KEY"] = "auth/invalid-api-key";
265
- AuthErrorCode["USER_CANCELLED"] = "auth/user-cancelled";
266
- AuthErrorCode["APP_NOT_AUTHORIZED"] = "auth/app-not-authorized";
267
- AuthErrorCode["KEYCHAIN_ERROR"] = "auth/keychain-error";
268
- AuthErrorCode["INTERNAL_ERROR"] = "auth/internal-error";
269
- AuthErrorCode["BIOMETRIC_NOT_AVAILABLE"] = "auth/biometric-not-available";
270
- AuthErrorCode["BIOMETRIC_NOT_ENROLLED"] = "auth/biometric-not-enrolled";
271
- AuthErrorCode["BIOMETRIC_AUTHENTICATION_FAILED"] = "auth/biometric-authentication-failed";
272
- AuthErrorCode["UNSUPPORTED_PROVIDER"] = "auth/unsupported-provider";
273
- AuthErrorCode["MISSING_CONFIGURATION"] = "auth/missing-configuration";
274
- AuthErrorCode["POPUP_BLOCKED"] = "auth/popup-blocked";
275
- AuthErrorCode["POPUP_CLOSED_BY_USER"] = "auth/popup-closed-by-user";
276
- AuthErrorCode["REDIRECT_CANCELLED_BY_USER"] = "auth/redirect-cancelled-by-user";
277
- AuthErrorCode["MISSING_REDIRECT_URL"] = "auth/missing-redirect-url";
278
- AuthErrorCode["INVALID_STATE"] = "auth/invalid-state";
279
- AuthErrorCode["MISSING_CODE_VERIFIER"] = "auth/missing-code-verifier";
280
- AuthErrorCode["INVALID_CODE_VERIFIER"] = "auth/invalid-code-verifier";
281
- AuthErrorCode["MISSING_NONCE"] = "auth/missing-nonce";
282
- AuthErrorCode["INVALID_NONCE"] = "auth/invalid-nonce";
283
- AuthErrorCode["UNAUTHORIZED_DOMAIN"] = "auth/unauthorized-domain";
284
- AuthErrorCode["INVALID_CONTINUE_URL"] = "auth/invalid-continue-url";
285
- AuthErrorCode["MISSING_CONTINUE_URL"] = "auth/missing-continue-url";
286
- AuthErrorCode["INVALID_DYNAMIC_LINK_DOMAIN"] = "auth/invalid-dynamic-link-domain";
287
- AuthErrorCode["REJECTED_CREDENTIAL"] = "auth/rejected-credential";
288
- AuthErrorCode["PHONE_NUMBER_ALREADY_EXISTS"] = "auth/phone-number-already-exists";
289
- AuthErrorCode["QUOTA_EXCEEDED"] = "auth/quota-exceeded";
290
- AuthErrorCode["CAPTCHA_CHECK_FAILED"] = "auth/captcha-check-failed";
291
- AuthErrorCode["MISSING_CAPTCHA_TOKEN"] = "auth/missing-captcha-token";
292
- AuthErrorCode["INVALID_CAPTCHA_TOKEN"] = "auth/invalid-captcha-token";
293
- AuthErrorCode["MISSING_CLIENT_IDENTIFIER"] = "auth/missing-client-identifier";
294
- AuthErrorCode["MISSING_OR_INVALID_NONCE"] = "auth/missing-or-invalid-nonce";
295
- AuthErrorCode["INTERACTION_REQUIRED"] = "auth/interaction-required";
296
- AuthErrorCode["LOGIN_REQUIRED"] = "auth/login-required";
297
- AuthErrorCode["CONSENT_REQUIRED"] = "auth/consent-required";
298
- AuthErrorCode["INVALID_GRANT"] = "auth/invalid-grant";
299
- AuthErrorCode["UNSUPPORTED_GRANT_TYPE"] = "auth/unsupported-grant-type";
300
- AuthErrorCode["PROVIDER_INIT_FAILED"] = "auth/provider-init-failed";
301
- AuthErrorCode["SIGN_IN_FAILED"] = "auth/sign-in-failed";
302
- AuthErrorCode["SIGN_OUT_FAILED"] = "auth/sign-out-failed";
303
- AuthErrorCode["NO_AUTH_SESSION"] = "auth/no-auth-session";
304
- AuthErrorCode["TOKEN_REFRESH_FAILED"] = "auth/token-refresh-failed";
305
- AuthErrorCode["ACCESS_DENIED"] = "auth/access-denied";
306
- AuthErrorCode["SERVER_ERROR"] = "auth/server-error";
307
- AuthErrorCode["TEMPORARILY_UNAVAILABLE"] = "auth/temporarily-unavailable";
308
- AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
309
- AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
310
- AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
311
- AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
312
- AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
313
- // --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
314
- // magic-link / biometric / email-password / username-password / phone-password) throw enum
315
- // codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
316
- AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
317
- AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
318
- AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
319
- AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
320
- AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
321
- AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
322
- AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
323
- AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
324
- AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
325
- AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
326
- AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
327
- AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
328
- AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
329
- AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
330
- AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
331
- AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
332
- AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
333
- AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
334
- AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
335
- AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
336
- AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
337
- AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
338
- AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
339
- AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
340
- AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
341
- // The active provider does not implement an optional capability (e.g. token refresh).
342
- // Same string the manager previously threw as a bare literal — now an enum member so
343
- // consumers can switch on `AuthErrorCode.OPERATION_NOT_SUPPORTED` reliably.
344
- AuthErrorCode["OPERATION_NOT_SUPPORTED"] = "auth/operation-not-supported";
345
- // The provider is recognized but not yet enabled in this release. As of 2.4.1 the package ships
346
- // a hardened Google provider and re-enables the remaining providers one at a time. Switch on this
347
- // to detect a "coming soon" provider distinctly from an unknown one.
348
- AuthErrorCode["PROVIDER_NOT_ENABLED"] = "auth/provider-not-enabled";
349
- })(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
350
-
351
- class WebStorage {
352
- /**
353
- * @param persistence Where to persist values (local / session / in-memory).
354
- * @param prefix Key prefix to namespace this package's storage.
355
- * @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
356
- * so storage failures honour the package log level instead of writing to `console` directly.
420
+ * @param persistence Where to persist values (local / session / in-memory).
421
+ * @param prefix Key prefix to namespace this package's storage.
422
+ * @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
423
+ * so storage failures honour the package log level instead of writing to `console` directly.
357
424
  */
358
425
  constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
359
426
  this.prefix = prefix;
360
427
  this.logger = logger;
361
428
  switch (persistence) {
362
429
  case exports.AuthPersistence.SESSION:
363
- this.storage = window.sessionStorage;
364
- break;
365
- case exports.AuthPersistence.LOCAL:
366
- this.storage = window.localStorage;
430
+ this.storage = resolveBrowserStorage('sessionStorage');
367
431
  break;
368
432
  case exports.AuthPersistence.NONE:
369
433
  // Use in-memory storage
370
434
  this.storage = new InMemoryStorage();
371
435
  break;
436
+ case exports.AuthPersistence.LOCAL:
372
437
  default:
373
- this.storage = window.localStorage;
438
+ this.storage = resolveBrowserStorage('localStorage');
374
439
  }
375
440
  }
376
441
  async get(key) {
@@ -478,6 +543,32 @@ class CapacitorPreferencesStorage {
478
543
  .map((k) => prefs.remove({ key: k })));
479
544
  }
480
545
  }
546
+ /**
547
+ * Returns the requested browser storage when it exists AND is usable, otherwise an in-memory
548
+ * fallback. Two environments make the fallback necessary:
549
+ * - Node / SSR / test runners: `window` is undefined, so the old unguarded `window.localStorage`
550
+ * read threw `ReferenceError: window is not defined` at import time (ISSUE-002).
551
+ * - Browsers that expose the API but refuse it (Safari private mode, cookies disabled, sandboxed
552
+ * iframes): `getItem`/`setItem` throw, so the probe below catches that and degrades gracefully.
553
+ */
554
+ function resolveBrowserStorage(kind) {
555
+ if (typeof window === 'undefined') {
556
+ return new InMemoryStorage();
557
+ }
558
+ try {
559
+ const candidate = window[kind];
560
+ if (!candidate) {
561
+ return new InMemoryStorage();
562
+ }
563
+ const probeKey = '__cap_auth_probe__';
564
+ candidate.setItem(probeKey, '1');
565
+ candidate.removeItem(probeKey);
566
+ return candidate;
567
+ }
568
+ catch (_a) {
569
+ return new InMemoryStorage();
570
+ }
571
+ }
481
572
  class InMemoryStorage {
482
573
  constructor() {
483
574
  this.data = new Map();
@@ -590,2589 +681,18 @@ function isAuthError(error) {
590
681
  error.code !== undefined));
591
682
  }
592
683
 
593
- function getPlatformWindow() {
594
- return typeof window !== 'undefined'
595
- ? window
596
- : undefined;
597
- }
598
- class PlatformDetector {
599
- static getPlatform() {
600
- // A cached NON-web result is final (native/electron never reverts to web). But a cached
601
- // 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
602
- // module first runs (the native bridge initializes asynchronously), so re-evaluate while
603
- // the last verdict was 'web' to pick up a late native environment. See F-26.
604
- if (this.platformInfo && this.platformInfo.platform !== 'web') {
605
- return this.platformInfo;
606
- }
607
- const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
608
- const platform = this.detectPlatform(userAgent);
609
- this.platformInfo = {
610
- platform,
611
- isNative: platform === 'ios' || platform === 'android',
612
- isWeb: platform === 'web',
613
- isMobile: platform === 'ios' ||
614
- platform === 'android' ||
615
- this.isMobileWeb(userAgent),
616
- isDesktop: platform === 'electron' ||
617
- (platform === 'web' && !this.isMobileWeb(userAgent)),
618
- userAgent,
619
- };
620
- return this.platformInfo;
621
- }
622
- /**
623
- * Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
624
- * result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
625
- * initializes late). Most callers can rely on the automatic re-check while the cached value is
626
- * still 'web'.
627
- */
628
- static reset() {
629
- this.platformInfo = null;
630
- }
631
- static detectPlatform(userAgent) {
632
- var _a, _b;
633
- const win = getPlatformWindow();
634
- // Check if running in Capacitor
635
- if (win === null || win === void 0 ? void 0 : win.Capacitor) {
636
- const capacitor = win.Capacitor;
637
- if (capacitor.getPlatform) {
638
- const platform = capacitor.getPlatform();
639
- if (platform === 'ios' || platform === 'android') {
640
- return platform;
641
- }
642
- }
643
- }
644
- // Check if running in Electron
645
- if ((_b = (_a = win === null || win === void 0 ? void 0 : win.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron) {
646
- return 'electron';
647
- }
648
- // Check for React Native
649
- if (typeof navigator !== 'undefined' &&
650
- navigator.product === 'ReactNative') {
651
- if (/iPhone|iPad|iPod/i.test(userAgent)) {
652
- return 'ios';
653
- }
654
- if (/Android/i.test(userAgent)) {
655
- return 'android';
656
- }
657
- }
658
- // Check for native iOS/Android webviews
659
- if (/iPhone|iPad|iPod/i.test(userAgent) &&
660
- /WebKit/i.test(userAgent) &&
661
- !/Safari/i.test(userAgent)) {
662
- return 'ios';
663
- }
664
- if (/Android/i.test(userAgent) && /wv/i.test(userAgent)) {
665
- return 'android';
666
- }
667
- // Default to web
668
- return 'web';
669
- }
670
- static isMobileWeb(userAgent) {
671
- return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
672
- }
673
- static isCapacitorAvailable() {
674
- var _a;
675
- return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
676
- }
677
- static async checkCapacitorPlugin(pluginName) {
678
- var _a;
679
- const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
680
- if (!capacitor) {
681
- return false;
682
- }
683
- try {
684
- return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
685
- }
686
- catch (_b) {
687
- return false;
688
- }
689
- }
690
- }
691
- PlatformDetector.platformInfo = null;
692
-
693
- /**
694
- * Safely extract a human-readable message from an unknown thrown value.
695
- *
696
- * `catch` clauses receive `unknown` (the honest type — anything can be thrown), so reach for this
697
- * instead of typing the binding as `any`. Returns `undefined` when no message can be derived, so
698
- * callers can fall back to their own default text: `getErrorMessage(error) || 'Default message'`.
699
- */
700
- function getErrorMessage(error) {
701
- if (error instanceof Error) {
702
- return error.message;
703
- }
704
- if (typeof error === 'object' && error !== null && 'message' in error) {
705
- const message = error.message;
706
- return typeof message === 'string' ? message : undefined;
707
- }
708
- if (typeof error === 'string') {
709
- return error;
710
- }
711
- return undefined;
712
- }
713
-
714
- /**
715
- * Built-in provider manifests (display metadata + human-readable setup instructions).
716
- *
717
- * Extracted from `provider-registry.ts` as a pure data module (zero logic) so the registry stays
718
- * under the project's file-size guideline. `ProviderRegistry` imports this array and registers each
719
- * entry in its static initializer — behaviour is unchanged (see F-40).
720
- */
721
- const BUILT_IN_PROVIDER_MANIFESTS = [
722
- {
723
- name: 'google',
724
- displayName: 'Google',
725
- packageName: '@google/gsi',
726
- setupInstructions: `
727
- To use Google authentication, you need to:
728
-
729
- 1. Install the Google Sign-In SDK:
730
- npm install @google/gsi
731
-
732
- 2. Configure your Google OAuth client:
733
- - Go to https://console.cloud.google.com/
734
- - Create or select a project
735
- - Enable Google Sign-In API
736
- - Create OAuth 2.0 credentials
737
- - Add authorized JavaScript origins
738
-
739
- 3. Configure the provider:
740
- auth.configure({
741
- providers: {
742
- google: {
743
- clientId: 'YOUR_CLIENT_ID'
744
- }
745
- }
746
- })
747
- `,
748
- platforms: ['web', 'ios', 'android'],
749
- configSchema: {
750
- clientId: { type: 'string', required: true },
751
- scopes: { type: 'array', items: 'string' },
752
- hostedDomain: { type: 'string' },
753
- },
754
- },
755
- {
756
- name: 'apple',
757
- displayName: 'Apple',
758
- setupInstructions: `
759
- To use Apple authentication:
760
-
761
- 1. Configure Sign in with Apple:
762
- - Go to https://developer.apple.com/
763
- - Configure your app for Sign in with Apple
764
- - Create a Services ID for web
765
- - Configure return URLs
766
-
767
- 2. Configure the provider:
768
- auth.configure({
769
- providers: {
770
- apple: {
771
- clientId: 'YOUR_SERVICE_ID',
772
- redirectUri: 'YOUR_REDIRECT_URI'
773
- }
774
- }
775
- })
776
- `,
777
- platforms: ['web', 'ios'],
778
- configSchema: {
779
- clientId: { type: 'string', required: true },
780
- redirectUri: { type: 'string', required: true },
781
- scopes: { type: 'array', items: 'string' },
782
- },
783
- },
784
- {
785
- name: 'firebase',
786
- displayName: 'Firebase Auth',
787
- packageName: 'firebase',
788
- setupInstructions: `
789
- To use Firebase authentication:
790
-
791
- 1. Install Firebase SDK:
792
- npm install firebase
793
-
794
- 2. Configure Firebase:
795
- - Go to https://console.firebase.google.com/
796
- - Create or select a project
797
- - Add your app (Web/iOS/Android)
798
- - Copy the configuration
799
-
800
- 3. Configure the provider:
801
- auth.configure({
802
- providers: {
803
- firebase: {
804
- apiKey: 'YOUR_API_KEY',
805
- authDomain: 'YOUR_AUTH_DOMAIN',
806
- projectId: 'YOUR_PROJECT_ID',
807
- // ... other Firebase config
808
- }
809
- }
810
- })
811
- `,
812
- platforms: ['web', 'ios', 'android'],
813
- configSchema: {
814
- apiKey: { type: 'string', required: true },
815
- authDomain: { type: 'string', required: true },
816
- projectId: { type: 'string', required: true },
817
- },
818
- },
819
- {
820
- name: 'microsoft',
821
- displayName: 'Microsoft',
822
- packageName: '@azure/msal-browser',
823
- setupInstructions: `
824
- To use Microsoft authentication:
825
-
826
- 1. Install the Microsoft Authentication Library:
827
- npm install @azure/msal-browser
828
-
829
- 2. Configure your Azure AD app:
830
- - Go to https://portal.azure.com/
831
- - Create or select an app registration
832
- - Add platform configuration for SPA
833
- - Add redirect URIs
834
-
835
- 3. Configure the provider:
836
- auth.configure({
837
- providers: {
838
- microsoft: {
839
- clientId: 'YOUR_CLIENT_ID',
840
- authority: 'YOUR_AUTHORITY', // optional
841
- redirectUri: 'YOUR_REDIRECT_URI' // optional
842
- }
843
- }
844
- })
845
- `,
846
- platforms: ['web'],
847
- configSchema: {
848
- clientId: { type: 'string', required: true },
849
- authority: { type: 'string' },
850
- redirectUri: { type: 'string' },
851
- scopes: { type: 'array', items: 'string' },
852
- },
853
- },
854
- {
855
- name: 'facebook',
856
- displayName: 'Facebook',
857
- setupInstructions: `
858
- To use Facebook authentication:
859
-
860
- 1. Configure your Facebook app:
861
- - Go to https://developers.facebook.com/
862
- - Create or select an app
863
- - Add Facebook Login product
864
- - Configure OAuth redirect URIs
865
-
866
- 2. Add Facebook SDK to your HTML:
867
- <script async defer crossorigin="anonymous"
868
- src="https://connect.facebook.net/en_US/sdk.js"></script>
869
-
870
- 3. Configure the provider:
871
- auth.configure({
872
- providers: {
873
- facebook: {
874
- appId: 'YOUR_APP_ID',
875
- version: 'v18.0' // optional
876
- }
877
- }
878
- })
879
- `,
880
- platforms: ['web'],
881
- configSchema: {
882
- appId: { type: 'string', required: true },
883
- version: { type: 'string' },
884
- scopes: { type: 'array', items: 'string' },
885
- },
886
- },
887
- {
888
- name: 'github',
889
- displayName: 'GitHub',
890
- setupInstructions: `
891
- To use GitHub authentication:
892
-
893
- 1. Configure your GitHub OAuth app:
894
- - Go to https://github.com/settings/developers
895
- - Create a new OAuth App
896
- - Set authorization callback URL
897
-
898
- 2. Configure the provider:
899
- auth.configure({
900
- providers: {
901
- github: {
902
- clientId: 'YOUR_CLIENT_ID',
903
- redirectUri: 'YOUR_REDIRECT_URI'
904
- }
905
- }
906
- })
907
-
908
- Note: You'll need a backend service to exchange the authorization code for an access token.
909
- `,
910
- platforms: ['web'],
911
- configSchema: {
912
- clientId: { type: 'string', required: true },
913
- redirectUri: { type: 'string' },
914
- scopes: { type: 'array', items: 'string' },
915
- },
916
- },
917
- {
918
- name: 'magic-link',
919
- displayName: 'Email Magic Link',
920
- setupInstructions: `
921
- To use Email Magic Link authentication:
922
-
923
- 1. Set up a backend endpoint to send emails:
924
- - Endpoint should accept POST requests with email and magic link
925
- - Send email with the magic link to the user
926
-
927
- 2. Configure the provider:
928
- auth.configure({
929
- providers: {
930
- 'magic-link': {
931
- sendLinkUrl: 'https://your-api.com/send-magic-link',
932
- verifyUrl: 'https://your-api.com/verify-magic-link', // Optional
933
- redirectUrl: window.location.origin + '/auth-callback'
934
- }
935
- }
936
- })
937
- `,
938
- platforms: ['web'],
939
- configSchema: {
940
- sendLinkUrl: { type: 'string', required: true },
941
- verifyUrl: { type: 'string' },
942
- redirectUrl: { type: 'string' },
943
- },
944
- },
945
- {
946
- name: 'sms',
947
- displayName: 'SMS Authentication',
948
- setupInstructions: `
949
- To use SMS authentication:
950
-
951
- 1. Set up backend endpoints:
952
- - Send code endpoint: POST request to send SMS
953
- - Verify code endpoint: POST request to verify SMS code
954
-
955
- 2. Configure the provider:
956
- auth.configure({
957
- providers: {
958
- sms: {
959
- sendCodeUrl: 'https://your-api.com/sms/send',
960
- verifyCodeUrl: 'https://your-api.com/sms/verify',
961
- countryCode: '+1', // Default country code
962
- codeLength: 6 // SMS code length
963
- }
964
- }
965
- })
966
- `,
967
- platforms: ['web', 'ios', 'android'],
968
- configSchema: {
969
- sendCodeUrl: { type: 'string', required: true },
970
- verifyCodeUrl: { type: 'string', required: true },
971
- countryCode: { type: 'string' },
972
- codeLength: { type: 'number' },
973
- },
974
- },
975
- {
976
- name: 'email-password',
977
- displayName: 'Email & Password',
978
- setupInstructions: `
979
- To use Email/Password authentication:
980
-
981
- 1. Set up backend API endpoints for authentication
982
-
983
- 2. Configure the provider:
984
- auth.configure({
985
- providers: {
986
- 'email-password': {
987
- apiUrl: 'https://your-api.com',
988
- passwordRequirements: {
989
- minLength: 8,
990
- requireUppercase: true,
991
- requireNumbers: true
992
- }
993
- }
994
- }
995
- })
996
- `,
997
- platforms: ['web', 'ios', 'android'],
998
- configSchema: {
999
- apiUrl: { type: 'string', required: true },
1000
- passwordRequirements: { type: 'object' },
1001
- },
1002
- },
1003
- {
1004
- name: 'biometric',
1005
- displayName: 'Biometric Authentication',
1006
- packageName: 'capacitor-biometric-authentication',
1007
- setupInstructions: `
1008
- To use Biometric authentication:
1009
-
1010
- 1. Install the capacitor-biometric-authentication plugin:
1011
- npm install capacitor-biometric-authentication
1012
- npx cap sync
1013
-
1014
- 2. Configure the provider:
1015
- auth.configure({
1016
- providers: {
1017
- biometric: {
1018
- reason: 'Authenticate to access your account',
1019
- title: 'Authentication Required'
1020
- }
1021
- }
1022
- })
1023
-
1024
- Note: Users must first authenticate with another method before enabling biometric authentication.
1025
- `,
1026
- platforms: ['ios', 'android'],
1027
- configSchema: {
1028
- reason: { type: 'string' },
1029
- title: { type: 'string' },
1030
- subtitle: { type: 'string' },
1031
- },
1032
- },
1033
- {
1034
- name: 'slack',
1035
- displayName: 'Slack',
1036
- setupInstructions: `
1037
- To use Slack authentication:
1038
-
1039
- 1. Create a Slack App:
1040
- - Go to https://api.slack.com/apps
1041
- - Click "Create New App" > "From scratch"
1042
- - Name your app and select workspace
1043
-
1044
- 2. Configure OAuth & Permissions:
1045
- - Add redirect URL: https://your-app.com/auth/slack/callback
1046
- - Add required scopes:
1047
- - openid
1048
- - profile
1049
- - email
1050
-
1051
- 3. Get your credentials:
1052
- - Go to "Basic Information"
1053
- - Copy Client ID and Client Secret
1054
-
1055
- 4. Configure the provider:
1056
- auth.configure({
1057
- providers: {
1058
- slack: {
1059
- clientId: 'YOUR_CLIENT_ID',
1060
- redirectUri: 'https://your-app.com/auth/slack/callback',
1061
- scopes: ['openid', 'profile', 'email'],
1062
- teamId: 'OPTIONAL_TEAM_ID' // Restrict to specific workspace
1063
- }
1064
- }
1065
- })
1066
-
1067
- Note: Slack OAuth requires a backend service to exchange the authorization code for access tokens.
1068
- `,
1069
- platforms: ['web'],
1070
- configSchema: {
1071
- clientId: { type: 'string', required: true },
1072
- redirectUri: { type: 'string', required: true },
1073
- scopes: { type: 'array', items: 'string' },
1074
- teamId: { type: 'string' },
1075
- },
1076
- },
1077
- {
1078
- name: 'linkedin',
1079
- displayName: 'LinkedIn',
1080
- setupInstructions: `
1081
- To use LinkedIn authentication:
1082
-
1083
- 1. Create a LinkedIn App:
1084
- - Go to https://www.linkedin.com/developers/apps
1085
- - Click "Create app"
1086
- - Fill in required information
1087
- - Verify your app
1088
-
1089
- 2. Configure OAuth 2.0:
1090
- - Go to the "Auth" tab
1091
- - Add authorized redirect URLs:
1092
- - https://your-app.com/auth/linkedin/callback
1093
- - Note your Client ID and Client Secret
1094
-
1095
- 3. Configure scopes:
1096
- - Under "OAuth 2.0 scopes", select:
1097
- - openid
1098
- - profile
1099
- - email
1100
-
1101
- 4. Configure the provider:
1102
- auth.configure({
1103
- providers: {
1104
- linkedin: {
1105
- clientId: 'YOUR_CLIENT_ID',
1106
- redirectUri: 'https://your-app.com/auth/linkedin/callback',
1107
- scopes: ['openid', 'profile', 'email']
1108
- }
1109
- }
1110
- })
1111
-
1112
- Note: LinkedIn OAuth requires a backend service to exchange the authorization code for access tokens.
1113
- The redirect URI must be HTTPS in production (LinkedIn requirement).
1114
- `,
1115
- platforms: ['web'],
1116
- configSchema: {
1117
- clientId: { type: 'string', required: true },
1118
- redirectUri: { type: 'string', required: true },
1119
- scopes: { type: 'array', items: 'string' },
1120
- },
1121
- },
1122
- {
1123
- name: 'username-password',
1124
- displayName: 'Username & Password',
1125
- setupInstructions: `
1126
- To use Username/Password authentication:
1127
-
1128
- 1. Set up backend API endpoints:
1129
- - /auth/signin - Sign in with username/password
1130
- - /auth/signup - Create new account
1131
- - /auth/signout - Sign out user
1132
- - /auth/refresh - Refresh access token
1133
- - /auth/update-password - Update password
1134
- - /auth/check-username - Check username availability
1135
-
1136
- 2. Configure the provider:
1137
- auth.configure({
1138
- providers: {
1139
- 'username-password': {
1140
- apiUrl: 'https://your-api.com',
1141
- usernameRequirements: {
1142
- minLength: 3,
1143
- maxLength: 20,
1144
- allowedCharacters: /^[a-zA-Z0-9_-]+$/,
1145
- reservedUsernames: ['admin', 'root', 'system']
1146
- },
1147
- passwordRequirements: {
1148
- minLength: 8,
1149
- requireUppercase: true,
1150
- requireLowercase: true,
1151
- requireNumbers: true,
1152
- requireSpecialChars: false
1153
- },
1154
- allowSignUp: true
1155
- }
1156
- }
1157
- })
1158
-
1159
- 3. Sign in:
1160
- await auth.signIn('username-password', {
1161
- username: 'johndoe',
1162
- password: 'password123'
1163
- });
1164
-
1165
- 4. Sign up:
1166
- await auth.signUp({
1167
- username: 'johndoe',
1168
- password: 'password123',
1169
- email: 'john@example.com', // optional
1170
- displayName: 'John Doe' // optional
1171
- });
1172
-
1173
- Note: This provider requires a backend service to handle authentication.
1174
- `,
1175
- platforms: ['web', 'ios', 'android'],
1176
- configSchema: {
1177
- apiUrl: { type: 'string', required: true },
1178
- usernameRequirements: { type: 'object' },
1179
- passwordRequirements: { type: 'object' },
1180
- allowSignUp: { type: 'boolean' },
1181
- },
1182
- },
1183
- ];
1184
-
1185
- var _a;
1186
- class ProviderRegistry {
1187
- static registerManifest(manifest) {
1188
- this.manifests.set(manifest.name, manifest);
1189
- }
1190
- static registerLoader(name, loader) {
1191
- this.loaders.set(name, loader);
1192
- }
1193
- static getManifest(name) {
1194
- return this.manifests.get(name);
1195
- }
1196
- static canonicalName(name) {
1197
- var _b;
1198
- return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
1199
- }
1200
- static async getProvider(name, options, deps) {
1201
- var _b, _c;
1202
- const key = this.canonicalName(name);
1203
- // Check if already loaded
1204
- const existing = this.providers.get(key);
1205
- if (existing) {
1206
- return existing;
1207
- }
1208
- // Check if loader exists. As of 2.4.1 only Google has a registered loader; a recognized provider
1209
- // without one is "not enabled yet" (distinct from an unknown provider) so consumers can branch on
1210
- // AuthErrorCode.PROVIDER_NOT_ENABLED.
1211
- const loader = this.loaders.get(key);
1212
- if (!loader) {
1213
- if (this.RECOGNIZED_PROVIDERS.has(key)) {
1214
- throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_ENABLED, `Provider '${name}' is not enabled yet. capacitor-auth-manager currently ships a hardened ` +
1215
- `Google provider; the remaining providers are being re-enabled one at a time. ` +
1216
- `Use AuthProvider.GOOGLE for now, and track progress at ` +
1217
- `https://github.com/aoneahsan/capacitor-auth-manager.`);
1218
- }
1219
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, `Unknown provider: ${name}`);
1220
- }
1221
- // Check platform support
1222
- const manifest = this.manifests.get(key);
1223
- if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
1224
- const platform = PlatformDetector.getPlatform();
1225
- if (!manifest.platforms.includes(platform.platform)) {
1226
- throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
1227
- }
1228
- }
1229
- try {
1230
- // Load the provider class. Every loader resolves to `{ default: <ProviderConstructor> }`
1231
- // (see registerLoader calls above); narrow `default` to that constructor shape so the
1232
- // `new ProviderClass(...)` below type-checks without resorting to `any`.
1233
- const module = await loader();
1234
- const ProviderClass = module.default;
1235
- // Build the constructor argument. BaseAuthProvider subclasses need a full
1236
- // BaseProviderConfig ({ provider, options, storage, logger, persistence });
1237
- // standalone providers take their options object directly.
1238
- const storage = (_b = deps === null || deps === void 0 ? void 0 : deps.storage) !== null && _b !== void 0 ? _b : new WebStorage(exports.AuthPersistence.LOCAL);
1239
- const logger = (_c = deps === null || deps === void 0 ? void 0 : deps.logger) !== null && _c !== void 0 ? _c : new Logger({
1240
- enableLogging: false,
1241
- logLevel: 'warn',
1242
- prefix: 'AuthManager',
1243
- });
1244
- const constructorArg = this.STANDALONE_PROVIDERS.has(key)
1245
- ? (options !== null && options !== void 0 ? options : {})
1246
- : {
1247
- provider: key,
1248
- options: (options !== null && options !== void 0 ? options : {}),
1249
- storage,
1250
- logger,
1251
- persistence: deps === null || deps === void 0 ? void 0 : deps.persistence,
1252
- };
1253
- // Create instance
1254
- const provider = new ProviderClass(constructorArg);
1255
- // Initialize if supported (BaseAuthProvider.initialize takes no arguments)
1256
- if (provider.initialize) {
1257
- await provider.initialize();
1258
- }
1259
- // Cache the provider under its canonical key
1260
- this.providers.set(key, provider);
1261
- return provider;
1262
- }
1263
- catch (error) {
1264
- // Check if it's a missing dependency error
1265
- const message = getErrorMessage(error);
1266
- if ((message === null || message === void 0 ? void 0 : message.includes('Cannot find module')) ||
1267
- (message === null || message === void 0 ? void 0 : message.includes('Failed to resolve module'))) {
1268
- const manifest = this.manifests.get(this.canonicalName(name));
1269
- if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
1270
- throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
1271
- `Install the required package:\n` +
1272
- `npm install ${manifest.packageName}\n\n` +
1273
- `Then try again.`);
1274
- }
1275
- }
1276
- throw error;
1277
- }
1278
- }
1279
- static clearProvider(name) {
1280
- const key = this.canonicalName(name);
1281
- const provider = this.providers.get(key);
1282
- if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
1283
- provider.dispose();
1284
- }
1285
- this.providers.delete(key);
1286
- }
1287
- static clearAll() {
1288
- for (const [, provider] of this.providers) {
1289
- if (provider.dispose) {
1290
- provider.dispose();
1291
- }
1292
- }
1293
- this.providers.clear();
1294
- }
1295
- static getAvailableProviders() {
1296
- return Array.from(this.manifests.keys());
1297
- }
1298
- static getSupportedProviders() {
1299
- const platform = PlatformDetector.getPlatform();
1300
- const supported = [];
1301
- for (const [name, manifest] of this.manifests) {
1302
- if (!manifest.platforms ||
1303
- manifest.platforms.includes(platform.platform)) {
1304
- supported.push(name);
1305
- }
1306
- }
1307
- return Promise.resolve(supported);
1308
- }
1309
- }
1310
- _a = ProviderRegistry;
1311
- ProviderRegistry.providers = new Map();
1312
- ProviderRegistry.loaders = new Map();
1313
- ProviderRegistry.manifests = new Map();
1314
- /** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
1315
- ProviderRegistry.STANDALONE_PROVIDERS = new Set([
1316
- 'magic-link',
1317
- 'sms',
1318
- 'email-password',
1319
- 'username-password',
1320
- 'biometric',
1321
- 'phone-password',
1322
- 'email-code',
1323
- ]);
1324
- /** Maps AuthProvider enum values (some underscored) to the registered hyphenated loader keys. */
1325
- ProviderRegistry.NAME_ALIASES = {
1326
- email_magic_link: 'magic-link',
1327
- username_password: 'username-password',
1328
- phone_password: 'phone-password',
1329
- email_code: 'email-code',
1330
- };
1331
- /**
1332
- * Every provider this package knows about (canonical loader keys). Used to distinguish a
1333
- * recognized-but-not-yet-enabled provider (→ PROVIDER_NOT_ENABLED) from a genuinely unknown one
1334
- * (→ UNSUPPORTED_PROVIDER). As of 2.4.1 only `google` has a registered loader; the rest are
1335
- * re-enabled one at a time (see docs/features/google-provider-production-v3).
1336
- */
1337
- ProviderRegistry.RECOGNIZED_PROVIDERS = new Set([
1338
- 'google',
1339
- 'apple',
1340
- 'microsoft',
1341
- 'facebook',
1342
- 'github',
1343
- 'slack',
1344
- 'linkedin',
1345
- 'firebase',
1346
- 'magic-link',
1347
- 'sms',
1348
- 'email-password',
1349
- 'phone-password',
1350
- 'username-password',
1351
- 'email-code',
1352
- 'biometric',
1353
- ]);
1354
- (() => {
1355
- // Register built-in provider manifests (data lives in provider-manifests.ts — F-40).
1356
- for (const manifest of BUILT_IN_PROVIDER_MANIFESTS) {
1357
- _a.registerManifest(manifest);
1358
- }
1359
- // --- Provider loaders -----------------------------------------------------------------
1360
- // WIP: providers are enabled ONE AT A TIME (see docs/features/google-provider-production-v3).
1361
- // As of 2.4.1 only Google is enabled. The Google loader is PLATFORM-AWARE: native (iOS/Android)
1362
- // routes to the native Google SDK through the Capacitor plugin bridge; web/electron uses Google
1363
- // Identity Services in the browser — same `auth.signIn(AuthProvider.GOOGLE)` call on every platform.
1364
- _a.registerLoader('google', () => {
1365
- const { platform } = PlatformDetector.getPlatform();
1366
- return platform === 'ios' || platform === 'android'
1367
- ? Promise.resolve().then(function () { return googleNativeProvider; }).then((m) => ({
1368
- default: m.GoogleNativeProvider,
1369
- }))
1370
- : Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
1371
- default: m.GoogleAuthProviderWeb,
1372
- }));
1373
- });
1374
- // The remaining providers (apple, microsoft, facebook, github, slack, linkedin, firebase,
1375
- // magic-link, sms, email-password, phone-password, username-password, email-code, biometric)
1376
- // are intentionally NOT registered yet. Their web implementations still live under
1377
- // src/providers/web/ but are excluded from the published build (tsconfig.build.json). Re-enable
1378
- // each by restoring its loader here (and removing its tsconfig.build exclude) once it has been
1379
- // hardened and verified on device. signIn() for any of them throws PROVIDER_NOT_ENABLED below.
1380
- })();
1381
-
1382
- /**
1383
- * Maps the config's persistence literal to the {@link AuthPersistence} enum WebStorage expects.
1384
- * Critically, `'memory'` maps to {@link AuthPersistence.NONE} (`'none'`) — previously the literal
1385
- * was cast via `as any` and fell through WebStorage's switch to localStorage, silently breaking
1386
- * in-memory persistence.
1387
- */
1388
- function toAuthPersistence(persistence) {
1389
- switch (persistence) {
1390
- case 'session':
1391
- return exports.AuthPersistence.SESSION;
1392
- case 'memory':
1393
- return exports.AuthPersistence.NONE;
1394
- case 'local':
1395
- default:
1396
- return exports.AuthPersistence.LOCAL;
1397
- }
1398
- }
1399
- class AuthManagerCore {
1400
- constructor() {
1401
- this.state = {
1402
- user: null,
1403
- isLoading: false,
1404
- isAuthenticated: false,
1405
- provider: null,
1406
- };
1407
- this.stateEmitter = new EventEmitter();
1408
- this.config = {};
1409
- this.isInitialized = false;
1410
- this.tokenRefreshTimers = new Map();
1411
- this.initPromise = null;
1412
- this.logger = new Logger({
1413
- enableLogging: false,
1414
- logLevel: 'info',
1415
- prefix: 'AuthManager',
1416
- });
1417
- this.storage = new WebStorage(exports.AuthPersistence.LOCAL, undefined, this.logger);
1418
- this.currentPersistence = 'local';
1419
- // Auto-initialize on first use
1420
- if (typeof window !== 'undefined') {
1421
- this.initialize().catch((err) => {
1422
- this.logger.error('Auto-initialization failed:', err);
1423
- });
1424
- }
1425
- }
1426
- async initialize(config) {
1427
- if (this.isInitialized && !config) {
1428
- return;
1429
- }
1430
- // Coalesce concurrent first-time initialization (e.g. the constructor's auto-init
1431
- // racing with an explicit initialize()) so restoreAuthState does not run twice.
1432
- if (this.initPromise && !config) {
1433
- return this.initPromise;
1434
- }
1435
- if (config) {
1436
- this.config = Object.assign(Object.assign({}, this.config), config);
1437
- }
1438
- // Configure logger
1439
- if (this.config.enableLogging !== undefined) {
1440
- this.logger.setEnabled(this.config.enableLogging);
1441
- }
1442
- if (this.config.logLevel) {
1443
- this.logger.setLogLevel(this.config.logLevel);
1444
- }
1445
- // A custom storage backend (e.g. secure native storage) takes precedence. Otherwise only
1446
- // recreate storage when persistence actually changes (don't discard in-memory state on a
1447
- // no-op re-initialize).
1448
- if (this.config.storage) {
1449
- this.storage = this.config.storage;
1450
- this.currentPersistence = 'custom';
1451
- }
1452
- else if (this.config.persistence &&
1453
- this.config.persistence !== this.currentPersistence) {
1454
- this.storage = new WebStorage(toAuthPersistence(this.config.persistence), undefined, this.logger);
1455
- this.currentPersistence = this.config.persistence;
1456
- }
1457
- // Restore auth state
1458
- this.initPromise = this.restoreAuthState();
1459
- await this.initPromise;
1460
- this.isInitialized = true;
1461
- this.logger.info('Auth manager initialized');
1462
- }
1463
- configure(config) {
1464
- this.config = Object.assign(Object.assign({}, this.config), config);
1465
- if (config.enableLogging !== undefined) {
1466
- this.logger.setEnabled(config.enableLogging);
1467
- }
1468
- if (config.logLevel) {
1469
- this.logger.setLogLevel(config.logLevel);
1470
- }
1471
- if (config.storage) {
1472
- this.storage = config.storage;
1473
- this.currentPersistence = 'custom';
1474
- }
1475
- else if (config.persistence &&
1476
- config.persistence !== this.currentPersistence) {
1477
- this.storage = new WebStorage(toAuthPersistence(config.persistence), undefined, this.logger);
1478
- this.currentPersistence = config.persistence;
1479
- }
1480
- // Now that providers may be configured, (re)attempt session restore so a persisted
1481
- // session is rehydrated even when the singleton auto-initialized before configure().
1482
- if (config.providers && Object.keys(config.providers).length > 0) {
1483
- void this.restoreAuthState();
1484
- }
1485
- }
1486
- async signIn(providerOrOptions) {
1487
- var _a, _b, _c;
1488
- await this.ensureInitialized();
1489
- let providerName;
1490
- let signInOptions = {};
1491
- if (typeof providerOrOptions === 'string') {
1492
- providerName = providerOrOptions;
1493
- }
1494
- else {
1495
- // Convert AuthProvider enum to string if needed
1496
- providerName =
1497
- typeof providerOrOptions.provider === 'string'
1498
- ? providerOrOptions.provider
1499
- : exports.AuthProvider[providerOrOptions.provider];
1500
- signInOptions = {
1501
- credentials: providerOrOptions.credentials,
1502
- options: providerOrOptions.options,
1503
- };
1504
- }
1505
- this.updateState({ isLoading: true });
1506
- try {
1507
- // Get provider configuration
1508
- const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[providerName];
1509
- if (!providerConfig) {
1510
- throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
1511
- }
1512
- // Get provider instance
1513
- const provider = await ProviderRegistry.getProvider(providerName, providerConfig, this.getProviderDeps());
1514
- // Sign in. Credentials are spread to the top level (where credential providers read
1515
- // email/password/phoneNumber/username) AND kept nested under `credentials` for
1516
- // providers that read them there.
1517
- this.logger.info(`Signing in with ${providerName}`);
1518
- // The provider reads credentials/options from this merged shape; `provider` is supplied via
1519
- // construction, not here, so we assert to SignInOptions (whose `provider` is required).
1520
- const result = await provider.signIn(Object.assign(Object.assign(Object.assign({}, signInOptions.options), ((_b = signInOptions.credentials) !== null && _b !== void 0 ? _b : {})), { credentials: signInOptions.credentials }));
1521
- // Update state
1522
- this.updateState({
1523
- user: result.user,
1524
- isAuthenticated: true,
1525
- provider: providerName,
1526
- isLoading: false,
1527
- });
1528
- // Store a NON-SECRET session snapshot. We deliberately do NOT persist idToken / accessToken /
1529
- // refreshToken / serverAuthCode to the default storage (localStorage on web, Preferences on
1530
- // native — neither hardware-encrypted). Short-lived tokens are re-derived via the provider's
1531
- // silent restore (getCurrentUser) / refreshToken(); persisting them at rest is a needless secret
1532
- // exposure. Consumers who need token persistence can inject a secure storage adapter and read
1533
- // tokens from the live AuthResult.
1534
- await this.storage.set('auth_state', {
1535
- user: result.user,
1536
- provider: providerName,
1537
- credential: this.sanitizeCredentialForStorage(result.credential),
1538
- });
1539
- // Setup token refresh
1540
- if (this.config.autoRefreshToken && ((_c = result.credential) === null || _c === void 0 ? void 0 : _c.refreshToken)) {
1541
- this.setupTokenRefresh(providerName, result.credential);
1542
- }
1543
- return result;
1544
- }
1545
- catch (error) {
1546
- this.updateState({ isLoading: false });
1547
- this.logger.error(`Sign in failed for ${providerName}`, error);
1548
- throw AuthError.fromError(error);
1549
- }
1550
- }
1551
- async signOut(options) {
1552
- var _a;
1553
- await this.ensureInitialized();
1554
- const provider = (options === null || options === void 0 ? void 0 : options.provider) || this.state.provider;
1555
- if (!provider) {
1556
- this.logger.warn('No active auth session to sign out from');
1557
- return;
1558
- }
1559
- this.updateState({ isLoading: true });
1560
- try {
1561
- // Get provider instance
1562
- const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
1563
- const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig, this.getProviderDeps());
1564
- // Sign out
1565
- await providerInstance.signOut(options);
1566
- // Clear token refresh. When no specific provider was targeted, clear ALL refresh timers
1567
- // (not just the active provider's) so a global sign-out leaves no orphaned timers behind.
1568
- if (options === null || options === void 0 ? void 0 : options.provider) {
1569
- this.clearTokenRefresh(provider);
1570
- }
1571
- else {
1572
- this.clearAllTokenRefresh();
1573
- }
1574
- // Clear state
1575
- this.updateState({
1576
- user: null,
1577
- isAuthenticated: false,
1578
- provider: null,
1579
- isLoading: false,
1580
- });
1581
- // Clear storage
1582
- await this.storage.remove('auth_state');
1583
- this.logger.info(`Signed out from ${provider}`);
1584
- }
1585
- catch (error) {
1586
- this.updateState({ isLoading: false });
1587
- this.logger.error(`Sign out failed for ${provider}`, error);
1588
- throw AuthError.fromError(error);
1589
- }
1590
- }
1591
- getCurrentUser() {
1592
- return this.state.user;
1593
- }
1594
- getAuthState() {
1595
- return Object.assign({}, this.state);
1596
- }
1597
- isAuthenticated() {
1598
- return this.state.isAuthenticated;
1599
- }
1600
- getCurrentProvider() {
1601
- return this.state.provider;
1602
- }
1603
- async refreshToken(provider) {
1604
- var _a, _b;
1605
- await this.ensureInitialized();
1606
- const targetProvider = provider || this.state.provider;
1607
- if (!targetProvider) {
1608
- throw new AuthError('auth/no-auth-session', 'No active auth session to refresh');
1609
- }
1610
- try {
1611
- const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
1612
- const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig, this.getProviderDeps());
1613
- if (!providerInstance.refreshToken) {
1614
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_SUPPORTED, `Provider '${targetProvider}' does not support token refresh`);
1615
- }
1616
- const result = await providerInstance.refreshToken();
1617
- // Update user
1618
- this.updateState({ user: result.user });
1619
- // Setup new token refresh
1620
- if (this.config.autoRefreshToken && ((_b = result.credential) === null || _b === void 0 ? void 0 : _b.refreshToken)) {
1621
- this.setupTokenRefresh(targetProvider, result.credential);
1622
- }
1623
- return result;
1624
- }
1625
- catch (error) {
1626
- this.logger.error(`Token refresh failed for ${targetProvider}`, error);
1627
- throw AuthError.fromError(error);
1628
- }
1629
- }
1630
- /**
1631
- * Links an additional auth credential to the current account, delegating to the resolved
1632
- * provider's optional `linkAccount`. Throws `OPERATION_NOT_ALLOWED` if the provider doesn't
1633
- * implement it. Mirrors `CapacitorAuthManagerWeb.linkAccount` so React/Vue/Angular consumers
1634
- * reach the same capability through the `auth` singleton.
1635
- */
1636
- async linkAccount(options) {
1637
- await this.ensureInitialized();
1638
- const providerName = typeof options.provider === 'string'
1639
- ? options.provider
1640
- : exports.AuthProvider[options.provider];
1641
- const provider = await this.resolveProvider(providerName);
1642
- if (typeof provider.linkAccount !== 'function') {
1643
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `linkAccount not supported for ${providerName}`);
1644
- }
1645
- try {
1646
- const result = await provider.linkAccount(options);
1647
- this.updateState({ user: result.user });
1648
- return result;
1649
- }
1650
- catch (error) {
1651
- this.logger.error(`Account linking failed for ${providerName}`, error);
1652
- throw AuthError.fromError(error);
1653
- }
1654
- }
1655
- /**
1656
- * Unlinks a provider credential from the current account via the resolved provider's optional
1657
- * `unlinkAccount`. Throws `OPERATION_NOT_ALLOWED` if unsupported.
1658
- */
1659
- async unlinkAccount(options) {
1660
- await this.ensureInitialized();
1661
- const providerName = typeof options.provider === 'string'
1662
- ? options.provider
1663
- : exports.AuthProvider[options.provider];
1664
- const provider = await this.resolveProvider(providerName);
1665
- if (typeof provider.unlinkAccount !== 'function') {
1666
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `unlinkAccount not supported for ${providerName}`);
1667
- }
1668
- try {
1669
- await provider.unlinkAccount(options);
1670
- }
1671
- catch (error) {
1672
- this.logger.error(`Account unlinking failed for ${providerName}`, error);
1673
- throw AuthError.fromError(error);
1674
- }
1675
- }
1676
- /**
1677
- * Revokes the access/refresh token for a provider (current provider when `provider` is omitted),
1678
- * delegating to the provider's optional `revokeAccess`. Throws `OPERATION_NOT_ALLOWED` if
1679
- * unsupported.
1680
- */
1681
- async revokeAccess(token, provider) {
1682
- await this.ensureInitialized();
1683
- const targetProvider = provider || this.state.provider;
1684
- if (!targetProvider) {
1685
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to revoke access for');
1686
- }
1687
- const providerInstance = await this.resolveProvider(targetProvider);
1688
- if (typeof providerInstance.revokeAccess !== 'function') {
1689
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `revokeAccess not supported for ${targetProvider}`);
1690
- }
1691
- try {
1692
- await providerInstance.revokeAccess(token);
1693
- }
1694
- catch (error) {
1695
- this.logger.error(`Access revocation failed for ${targetProvider}`, error);
1696
- throw AuthError.fromError(error);
1697
- }
1698
- }
1699
- /**
1700
- * Returns the current ID token for a provider (current provider when `provider` is omitted) by
1701
- * delegating to the provider's optional `getIdToken`. Throws `OPERATION_NOT_ALLOWED` if the
1702
- * provider doesn't issue/expose ID tokens.
1703
- */
1704
- async getIdToken(options) {
1705
- var _a;
1706
- await this.ensureInitialized();
1707
- const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1708
- ? typeof options.provider === 'string'
1709
- ? options.provider
1710
- : exports.AuthProvider[options.provider]
1711
- : undefined) || this.state.provider;
1712
- if (!targetProvider) {
1713
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to get an ID token for');
1714
- }
1715
- const provider = await this.resolveProvider(targetProvider);
1716
- const getIdTokenFn = provider.getIdToken;
1717
- if (typeof getIdTokenFn !== 'function') {
1718
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `getIdToken not supported for ${targetProvider}`);
1719
- }
1720
- try {
1721
- return await getIdTokenFn.call(provider, (_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
1722
- }
1723
- catch (error) {
1724
- this.logger.error(`getIdToken failed for ${targetProvider}`, error);
1725
- throw AuthError.fromError(error);
1726
- }
1727
- }
1728
- /**
1729
- * Updates the signed-in user's profile via the current provider's optional `updateProfile`.
1730
- * Throws `OPERATION_NOT_ALLOWED` if the provider doesn't implement it.
1731
- */
1732
- async updateProfile(options) {
1733
- await this.ensureInitialized();
1734
- const targetProvider = this.state.provider;
1735
- if (!targetProvider) {
1736
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
1737
- }
1738
- const provider = await this.resolveProvider(targetProvider);
1739
- const updateFn = provider.updateProfile;
1740
- if (typeof updateFn !== 'function') {
1741
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `updateProfile not supported for ${targetProvider}`);
1742
- }
1743
- try {
1744
- const updatedUser = await updateFn.call(provider, options);
1745
- this.updateState({ user: updatedUser });
1746
- return updatedUser;
1747
- }
1748
- catch (error) {
1749
- this.logger.error(`updateProfile failed for ${targetProvider}`, error);
1750
- throw AuthError.fromError(error);
1751
- }
1752
- }
1753
- /**
1754
- * Deletes the current account via the provider's optional `deleteAccount` (current provider when
1755
- * `provider` is omitted), then clears local state. Throws `OPERATION_NOT_ALLOWED` if the provider
1756
- * doesn't implement it.
1757
- */
1758
- async deleteAccount(options) {
1759
- await this.ensureInitialized();
1760
- const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1761
- ? typeof options.provider === 'string'
1762
- ? options.provider
1763
- : exports.AuthProvider[options.provider]
1764
- : undefined) || this.state.provider;
1765
- if (!targetProvider) {
1766
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
1767
- }
1768
- const provider = await this.resolveProvider(targetProvider);
1769
- const deleteFn = provider.deleteAccount;
1770
- if (typeof deleteFn !== 'function') {
1771
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
1772
- }
1773
- try {
1774
- await deleteFn.call(provider);
1775
- // Account deleted server-side: clear local session + timers.
1776
- this.clearTokenRefresh(targetProvider);
1777
- this.updateState({
1778
- user: null,
1779
- isAuthenticated: false,
1780
- provider: null,
1781
- });
1782
- await this.storage.remove('auth_state');
1783
- }
1784
- catch (error) {
1785
- this.logger.error(`deleteAccount failed for ${targetProvider}`, error);
1786
- throw AuthError.fromError(error);
1787
- }
1788
- }
1789
- /**
1790
- * Whether a provider has been supplied to `configure()`/`initialize()`. Public accessor so
1791
- * adapters (React/Vue/Angular) no longer reach into the private `config` via `as any`.
1792
- */
1793
- isProviderConfigured(name) {
1794
- var _a;
1795
- return !!((_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name]);
1796
- }
1797
- /** Names of every provider supplied to `configure()`/`initialize()`. */
1798
- getConfiguredProviders() {
1799
- return this.config.providers ? Object.keys(this.config.providers) : [];
1800
- }
1801
- onAuthStateChange(listener) {
1802
- // Immediately call with current state
1803
- listener(this.getAuthState());
1804
- // Subscribe to future changes
1805
- return this.stateEmitter.subscribe(listener);
1806
- }
1807
- async getAvailableProviders() {
1808
- return ProviderRegistry.getAvailableProviders();
1809
- }
1810
- async getSupportedProviders() {
1811
- return ProviderRegistry.getSupportedProviders();
1812
- }
1813
- async isProviderSupported(provider) {
1814
- const supported = await this.getSupportedProviders();
1815
- return supported.includes(provider);
1816
- }
1817
- async ensureInitialized() {
1818
- if (!this.isInitialized) {
1819
- await this.initialize();
1820
- }
1821
- }
1822
- getProviderDeps() {
1823
- return { storage: this.storage, logger: this.logger };
1824
- }
1825
- /**
1826
- * Resolves a provider instance through the registry, threading the configured options and the
1827
- * manager's shared storage/logger. Shared by the capability methods (link/unlink/revoke/
1828
- * getIdToken/updateProfile/deleteAccount).
1829
- */
1830
- async resolveProvider(name) {
1831
- var _a;
1832
- return ProviderRegistry.getProvider(name, (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name], this.getProviderDeps());
1833
- }
1834
- updateState(partial) {
1835
- this.state = Object.assign(Object.assign({}, this.state), partial);
1836
- this.stateEmitter.emit(this.state);
1837
- }
1838
- /**
1839
- * Strips secret token material from a credential before it reaches the default (unencrypted)
1840
- * storage. Only non-secret session metadata is kept; tokens are re-derived from the provider's
1841
- * silent restore. See the persist site in {@link signIn} for the rationale.
1842
- */
1843
- sanitizeCredentialForStorage(credential) {
1844
- if (!credential) {
1845
- return undefined;
1846
- }
1847
- return {
1848
- providerId: credential.providerId,
1849
- signInMethod: credential.signInMethod,
1850
- expiresAt: credential.expiresAt,
1851
- tokenType: credential.tokenType,
1852
- scope: credential.scope,
1853
- };
1854
- }
1855
- async restoreAuthState() {
1856
- var _a, _b;
1857
- try {
1858
- const stored = await this.storage.get('auth_state');
1859
- if ((stored === null || stored === void 0 ? void 0 : stored.user) && (stored === null || stored === void 0 ? void 0 : stored.provider)) {
1860
- // Verify the session is still valid
1861
- const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
1862
- if (providerConfig) {
1863
- try {
1864
- const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
1865
- const currentUser = await provider.getCurrentUser();
1866
- if (currentUser) {
1867
- this.updateState({
1868
- user: currentUser,
1869
- isAuthenticated: true,
1870
- provider: stored.provider,
1871
- });
1872
- // Setup token refresh if needed
1873
- if (((_b = stored.credential) === null || _b === void 0 ? void 0 : _b.refreshToken) &&
1874
- this.config.autoRefreshToken) {
1875
- this.setupTokenRefresh(stored.provider, stored.credential);
1876
- }
1877
- }
1878
- }
1879
- catch (error) {
1880
- this.logger.warn('Failed to restore auth session:', error);
1881
- await this.storage.remove('auth_state');
1882
- }
1883
- }
1884
- }
1885
- }
1886
- catch (error) {
1887
- this.logger.error('Failed to restore auth state:', error);
1888
- }
1889
- }
1890
- setupTokenRefresh(provider, credential) {
1891
- this.clearTokenRefresh(provider);
1892
- if (!credential.expiresAt || !credential.refreshToken) {
1893
- return;
1894
- }
1895
- const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
1896
- const refreshTime = credential.expiresAt - buffer - Date.now();
1897
- if (refreshTime > 0) {
1898
- this.scheduleRefresh(provider, refreshTime, credential);
1899
- }
1900
- }
1901
- /**
1902
- * Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
1903
- * (2,147,483,647 ms ≈ 24.8 days). Without clamping, a far-future `expiresAt` overflows the
1904
- * timer and fires almost immediately, causing a refresh storm. When clamped, the timer simply
1905
- * re-schedules the remaining wait on fire instead of refreshing early.
1906
- */
1907
- scheduleRefresh(provider, delayMs, credential) {
1908
- const MAX_TIMEOUT = 2147483647;
1909
- const clamped = Math.min(delayMs, MAX_TIMEOUT);
1910
- const timer = setTimeout(() => {
1911
- const remaining = delayMs - clamped;
1912
- if (remaining > 0) {
1913
- // We hit the clamp ceiling — reschedule the rest rather than refreshing prematurely.
1914
- this.scheduleRefresh(provider, remaining, credential);
1915
- return;
1916
- }
1917
- void (async () => {
1918
- try {
1919
- await this.refreshToken(provider);
1920
- }
1921
- catch (error) {
1922
- this.logger.error(`Auto token refresh failed for ${provider}`, error);
1923
- }
1924
- })();
1925
- }, clamped);
1926
- this.tokenRefreshTimers.set(provider, timer);
1927
- }
1928
- clearTokenRefresh(provider) {
1929
- const timer = this.tokenRefreshTimers.get(provider);
1930
- if (timer) {
1931
- clearTimeout(timer);
1932
- this.tokenRefreshTimers.delete(provider);
1933
- }
1934
- }
1935
- /** Clears every active refresh timer (used on a global, untargeted sign-out). */
1936
- clearAllTokenRefresh() {
1937
- for (const timer of this.tokenRefreshTimers.values()) {
1938
- clearTimeout(timer);
1939
- }
1940
- this.tokenRefreshTimers.clear();
1941
- }
1942
- dispose() {
1943
- // Clear all timers
1944
- for (const timer of this.tokenRefreshTimers.values()) {
1945
- clearTimeout(timer);
1946
- }
1947
- this.tokenRefreshTimers.clear();
1948
- // Clear providers
1949
- ProviderRegistry.clearAll();
1950
- // Clear listeners
1951
- this.stateEmitter.clear();
1952
- }
1953
- }
1954
- // Create singleton instance
1955
- const auth = new AuthManagerCore();
1956
-
1957
- // This provides backward compatibility for users who still want to use the Capacitor plugin interface
1958
- const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
1959
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
1960
- });
1961
-
1962
- /**
1963
- * Normalize a provider constructor argument into a full {@link BaseProviderConfig}.
1964
- *
1965
- * The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
1966
- * get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
1967
- * tests and direct consumers pass the provider's own bare options object. This helper accepts
1968
- * either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`, so it never
1969
- * touches `window` and stays safe under SSR / Node test environments) plus the shared
1970
- * {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
1971
- */
1972
- function resolveProviderConfig(provider, input) {
1973
- if (typeof input === 'object' &&
1974
- input !== null &&
1975
- 'storage' in input &&
1976
- 'logger' in input &&
1977
- 'options' in input) {
1978
- return input;
1979
- }
1980
- return {
1981
- provider,
1982
- options: (input !== null && input !== void 0 ? input : {}),
1983
- storage: new WebStorage(exports.AuthPersistence.NONE),
1984
- logger: defaultLogger,
1985
- };
1986
- }
1987
- class BaseAuthProvider {
1988
- get name() {
1989
- return this.provider;
1990
- }
1991
- constructor(config) {
1992
- this.currentUser = null;
1993
- this.isInitialized = false;
1994
- this.provider = config.provider;
1995
- this.options = config.options;
1996
- this.storage = config.storage;
1997
- this.logger = config.logger;
1998
- this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
1999
- this.authStateEmitter = new EventEmitter();
2000
- }
2001
- // Capability methods with concrete defaults: providers that support these operations override
2002
- // them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
2003
- // across every provider (see AuthProviderInterface, where they are optional). Marking them
2004
- // abstract previously forced every subclass to re-implement them just to throw.
2005
- async linkAccount(_options) {
2006
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking is not supported by provider ${this.provider}`, this.provider);
2007
- }
2008
- async unlinkAccount(_options) {
2009
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking is not supported by provider ${this.provider}`, this.provider);
2010
- }
2011
- async revokeAccess(_token) {
2012
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation is not supported by provider ${this.provider}`, this.provider);
2013
- }
2014
- async getCurrentUser() {
2015
- if (!this.isInitialized) {
2016
- await this.initialize();
2017
- }
2018
- return this.currentUser;
2019
- }
2020
- addAuthStateListener(callback) {
2021
- return this.authStateEmitter.subscribe(callback);
2022
- }
2023
- async setCurrentUser(user) {
2024
- this.currentUser = user;
2025
- // Persist user to storage
2026
- const storageKey = `${this.provider}_current_user`;
2027
- if (user) {
2028
- await this.storage.set(storageKey, user);
2029
- }
2030
- else {
2031
- await this.storage.remove(storageKey);
2032
- }
2033
- // Emit auth state change
2034
- this.authStateEmitter.emit(user);
2035
- }
2036
- async loadCurrentUser() {
2037
- try {
2038
- const storageKey = `${this.provider}_current_user`;
2039
- const userData = await this.storage.get(storageKey);
2040
- if (userData) {
2041
- this.currentUser = userData;
2042
- this.logger.debug(`Loaded user from storage for provider ${this.provider}`);
2043
- }
2044
- }
2045
- catch (error) {
2046
- this.logger.error('Failed to load user from storage', error);
2047
- }
2048
- }
2049
- async saveCredential(credential) {
2050
- const storageKey = `${this.provider}_credential`;
2051
- await this.storage.set(storageKey, credential);
2052
- }
2053
- async loadCredential() {
2054
- try {
2055
- const storageKey = `${this.provider}_credential`;
2056
- const credentialData = await this.storage.get(storageKey);
2057
- if (credentialData) {
2058
- return credentialData;
2059
- }
2060
- }
2061
- catch (error) {
2062
- this.logger.error('Failed to load credential from storage', error);
2063
- }
2064
- return null;
2065
- }
2066
- async clearStoredData() {
2067
- const userKey = `${this.provider}_current_user`;
2068
- const credentialKey = `${this.provider}_credential`;
2069
- await Promise.all([
2070
- this.storage.remove(userKey),
2071
- this.storage.remove(credentialKey),
2072
- ]);
2073
- }
2074
- validateInitialized() {
2075
- if (!this.isInitialized) {
2076
- throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Provider ${this.provider} is not initialized`, this.provider);
2077
- }
2078
- }
2079
- createAuthResult(user, credential, isNewUser = false, operationType = 'signIn') {
2080
- return {
2081
- user,
2082
- credential,
2083
- additionalUserInfo: {
2084
- isNewUser,
2085
- providerId: this.provider,
2086
- },
2087
- operationType,
2088
- };
2089
- }
2090
- generateUniqueId() {
2091
- // Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
2092
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
2093
- return crypto.randomUUID();
2094
- }
2095
- const bytes = new Uint8Array(16);
2096
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
2097
- crypto.getRandomValues(bytes);
2098
- }
2099
- let hex = '';
2100
- for (let i = 0; i < bytes.length; i++) {
2101
- hex += bytes[i].toString(16).padStart(2, '0');
2102
- }
2103
- return `${Date.now()}-${hex}`;
2104
- }
2105
- isTokenExpired(expiresAt) {
2106
- if (!expiresAt)
2107
- return false;
2108
- return Date.now() >= expiresAt;
2109
- }
2110
- calculateTokenExpiry(expiresIn) {
2111
- if (!expiresIn) {
2112
- // Default to 1 hour
2113
- expiresIn = 3600;
2114
- }
2115
- return Date.now() + expiresIn * 1000;
2116
- }
2117
- dispose() {
2118
- this.authStateEmitter.clear();
2119
- this.currentUser = null;
2120
- this.isInitialized = false;
2121
- }
2122
- }
2123
-
2124
- /**
2125
- * Native Google provider — the implementation the registry loads on **iOS / Android**.
2126
- *
2127
- * It is a thin bridge to the `CapacitorAuthManager` Capacitor plugin, whose native code runs the
2128
- * platform Google SDK (iOS: GoogleSignIn; Android: Credential Manager + Google Identity) and returns
2129
- * a **Firebase-agnostic** credential — `{ idToken, accessToken?, serverAuthCode?, user }`. The same
2130
- * `auth.signIn(AuthProvider.GOOGLE)` call routes here on a device and to `GoogleAuthProviderWeb` in
2131
- * the browser, so app code is identical across platforms. Consumers feed `result.credential.idToken`
2132
- * into their own `signInWithCredential(GoogleAuthProvider.credential(idToken))` (or anything else).
2133
- *
2134
- * This module is only ever dynamically imported on native platforms (see ProviderRegistry's
2135
- * platform-aware Google loader), so its top-level `@capacitor/core` import never reaches a web bundle.
2136
- */
2137
- class GoogleNativeProvider extends BaseAuthProvider {
2138
- constructor(config) {
2139
- super(resolveProviderConfig(exports.AuthProvider.GOOGLE, config));
2140
- }
2141
- get name() {
2142
- return exports.AuthProvider.GOOGLE;
2143
- }
2144
- async initialize() {
2145
- if (this.isInitialized) {
2146
- return;
2147
- }
2148
- try {
2149
- // Hand the Google config (clientId / serverClientId / iosClientId / scopes) to the native side
2150
- // once; subsequent signIn() calls only pass per-request SignInProviderOptions.
2151
- await CapacitorAuthManager.initialize({
2152
- providers: [
2153
- {
2154
- provider: exports.AuthProvider.GOOGLE,
2155
- options: this.options,
2156
- },
2157
- ],
2158
- });
2159
- await this.loadCurrentUser();
2160
- this.isInitialized = true;
2161
- }
2162
- catch (error) {
2163
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2164
- }
2165
- }
2166
- async signIn(options) {
2167
- if (!this.isInitialized) {
2168
- await this.initialize();
2169
- }
2170
- try {
2171
- const result = await CapacitorAuthManager.signIn({
2172
- provider: exports.AuthProvider.GOOGLE,
2173
- options: options === null || options === void 0 ? void 0 : options.options,
2174
- });
2175
- await this.setCurrentUser(result.user);
2176
- return result;
2177
- }
2178
- catch (error) {
2179
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2180
- }
2181
- }
2182
- async signOut(_options) {
2183
- try {
2184
- await CapacitorAuthManager.signOut({ provider: exports.AuthProvider.GOOGLE });
2185
- }
2186
- catch (error) {
2187
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2188
- }
2189
- finally {
2190
- await this.setCurrentUser(null);
2191
- }
2192
- }
2193
- async refreshToken(_options) {
2194
- try {
2195
- const result = await CapacitorAuthManager.refreshToken({
2196
- provider: exports.AuthProvider.GOOGLE,
2197
- });
2198
- if (result.user) {
2199
- await this.setCurrentUser(result.user);
2200
- }
2201
- return result;
2202
- }
2203
- catch (error) {
2204
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2205
- }
2206
- }
2207
- async getCurrentUser() {
2208
- try {
2209
- const user = await CapacitorAuthManager.getCurrentUser();
2210
- this.currentUser = user;
2211
- return user;
2212
- }
2213
- catch (_a) {
2214
- // Fall back to the last known user if the bridge call fails (e.g. plugin not yet ready).
2215
- return this.currentUser;
2216
- }
2217
- }
2218
- async revokeAccess(_token) {
2219
- try {
2220
- await CapacitorAuthManager.revokeAccess({ provider: exports.AuthProvider.GOOGLE });
2221
- }
2222
- catch (error) {
2223
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2224
- }
2225
- finally {
2226
- await this.setCurrentUser(null);
2227
- }
2228
- }
2229
- async isSupported() {
2230
- // Only loaded on native platforms (the registry routes web/electron to GoogleAuthProviderWeb).
2231
- return true;
2232
- }
2233
- }
2234
-
2235
- var googleNativeProvider = /*#__PURE__*/Object.freeze({
2236
- __proto__: null,
2237
- GoogleNativeProvider: GoogleNativeProvider
2238
- });
2239
-
2240
- const GSI_SRC = 'https://accounts.google.com/gsi/client';
2241
- /**
2242
- * Web Google provider — the implementation the registry loads on **web / electron**.
2243
- *
2244
- * Uses the **Google Identity Services ID-token flow** (`google.accounts.id`): no client secret, no
2245
- * backend, no popup-blocker problems. The browser returns a Google **ID token** (JWT) which is
2246
- * surfaced as `result.credential.idToken` — the SAME field the native providers populate — so the
2247
- * Firebase handoff is identical on every platform:
2248
- *
2249
- * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(result.credential.idToken));
2250
- *
2251
- * The id-token flow does NOT return an OAuth `accessToken` (use the GIS token client separately if you
2252
- * need to call Google APIs from the browser). Sign-in is triggered via One-Tap / FedCM `prompt()`; for a
2253
- * guaranteed button UX call {@link renderButton} to render Google's official button (same callback).
2254
- */
2255
- class GoogleAuthProviderWeb extends BaseAuthProvider {
2256
- constructor(config) {
2257
- super(config);
2258
- this.loadPromise = null;
2259
- /** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
2260
- this.pendingResolve = null;
2261
- this.pendingReject = null;
2262
- }
2263
- get name() {
2264
- return exports.AuthProvider.GOOGLE;
2265
- }
2266
- async initialize() {
2267
- if (this.isInitialized) {
2268
- return;
2269
- }
2270
- try {
2271
- await this.loadGsi();
2272
- this.configureIdClient();
2273
- await this.loadCurrentUser();
2274
- this.isInitialized = true;
2275
- this.logger.info('Google (web) provider initialized');
2276
- }
2277
- catch (error) {
2278
- throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2279
- }
2280
- }
2281
- async signIn(_options) {
2282
- if (!this.isInitialized) {
2283
- await this.initialize();
2284
- }
2285
- this.configureIdClient();
2286
- return new Promise((resolve, reject) => {
2287
- this.pendingResolve = resolve;
2288
- this.pendingReject = (e) => reject(e);
2289
- const api = this.requireIdApi();
2290
- try {
2291
- api.prompt((notification) => {
2292
- var _a, _b, _c, _d, _e, _f, _g, _h;
2293
- // One-Tap was suppressed (cooldown / dismissed / FedCM opt-out): fail clearly so the
2294
- // consumer can fall back to renderButton(). Wrapped in try/catch because these moment
2295
- // methods are deprecated under FedCM and may throw.
2296
- try {
2297
- const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
2298
- const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
2299
- if (notDisplayed || skipped) {
2300
- const reason = (_h = (_f = (_e = notification.getNotDisplayedReason) === null || _e === void 0 ? void 0 : _e.call(notification)) !== null && _f !== void 0 ? _f : (_g = notification.getSkippedReason) === null || _g === void 0 ? void 0 : _g.call(notification)) !== null && _h !== void 0 ? _h : 'suppressed';
2301
- this.rejectPending(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Render the Google button via ` +
2302
- `provider.renderButton(element) for a guaranteed sign-in UI, or sign in on web ` +
2303
- `with your own Firebase popup.`, exports.AuthProvider.GOOGLE));
2304
- }
2305
- }
2306
- catch (_j) {
2307
- // FedCM: moment methods unavailable — wait for the credential callback instead.
2308
- }
2309
- });
2310
- }
2311
- catch (error) {
2312
- this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2313
- }
2314
- });
2315
- }
2316
- /**
2317
- * Renders Google's official "Sign in with Google" button into `parent`. Use this when One-Tap is
2318
- * suppressed or you want a deterministic button. The button uses the SAME credential callback, so a
2319
- * click resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
2320
- */
2321
- async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
2322
- if (!this.isInitialized) {
2323
- await this.initialize();
2324
- }
2325
- this.configureIdClient();
2326
- this.requireIdApi().renderButton(parent, options);
2327
- }
2328
- async signOut(_options) {
2329
- var _a, _b, _c;
2330
- try {
2331
- (_c = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) === null || _c === void 0 ? void 0 : _c.disableAutoSelect();
2332
- }
2333
- catch (error) {
2334
- this.logger.warn('Google disableAutoSelect failed', error);
2335
- }
2336
- await this.clearStoredData();
2337
- await this.setCurrentUser(null);
2338
- }
2339
- /**
2340
- * Web ID tokens cannot be refreshed silently — re-running One-Tap (with auto-select) re-issues a
2341
- * fresh ID token for a returning user. Falls back to a normal prompt if auto-select can't.
2342
- */
2343
- async refreshToken(_options) {
2344
- return this.signIn();
2345
- }
2346
- async revokeAccess(token) {
2347
- var _a, _b;
2348
- const user = (_a = this.currentUser) !== null && _a !== void 0 ? _a : (await this.getCurrentUser());
2349
- const hint = (_b = user === null || user === void 0 ? void 0 : user.email) !== null && _b !== void 0 ? _b : token;
2350
- if (!hint) {
2351
- await this.signOut();
2352
- return;
2353
- }
2354
- await new Promise((resolve) => {
2355
- try {
2356
- this.requireIdApi().revoke(hint, () => resolve());
2357
- }
2358
- catch (_a) {
2359
- resolve();
2360
- }
2361
- });
2362
- await this.signOut();
2363
- }
2364
- async isSupported() {
2365
- if (typeof window === 'undefined' || typeof document === 'undefined') {
2366
- return false;
2367
- }
2368
- try {
2369
- await this.loadGsi();
2370
- return true;
2371
- }
2372
- catch (_a) {
2373
- return false;
2374
- }
2375
- }
2376
- // --- internals --------------------------------------------------------------------------------
2377
- requireIdApi() {
2378
- var _a, _b;
2379
- const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
2380
- if (!api) {
2381
- throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services not loaded', exports.AuthProvider.GOOGLE);
2382
- }
2383
- return api;
2384
- }
2385
- configureIdClient() {
2386
- var _a;
2387
- const options = this.options;
2388
- if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
2389
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', exports.AuthProvider.GOOGLE);
2390
- }
2391
- this.currentNonce = options.nonce;
2392
- const config = {
2393
- client_id: options.clientId,
2394
- callback: (response) => this.handleCredential(response),
2395
- auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
2396
- cancel_on_tap_outside: false,
2397
- context: 'signin',
2398
- use_fedcm_for_prompt: true,
2399
- itp_support: true,
2400
- };
2401
- if (options.nonce) {
2402
- config.nonce = options.nonce;
2403
- }
2404
- if (options.loginHint) {
2405
- config.login_hint = options.loginHint;
2406
- }
2407
- if (options.hostedDomain) {
2408
- config.hd = options.hostedDomain;
2409
- }
2410
- this.requireIdApi().initialize(config);
2411
- }
2412
- async handleCredential(response) {
2413
- if (response.error || !response.credential) {
2414
- this.rejectPending(new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
2415
- response.error ||
2416
- 'No Google ID token returned', exports.AuthProvider.GOOGLE));
2417
- return;
2418
- }
2419
- try {
2420
- const idToken = response.credential;
2421
- const claims = this.validateIdToken(idToken);
2422
- const user = this.buildUser(claims);
2423
- const credential = {
2424
- providerId: 'google.com',
2425
- signInMethod: 'google.com',
2426
- idToken,
2427
- tokenType: 'Bearer',
2428
- scope: 'openid email profile',
2429
- };
2430
- await this.setCurrentUser(user);
2431
- this.resolvePending(this.createAuthResult(user, credential, false));
2432
- }
2433
- catch (error) {
2434
- this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2435
- }
2436
- }
2437
- validateIdToken(idToken) {
2438
- const claims = decodeJwtPayload(idToken);
2439
- const options = this.options;
2440
- const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
2441
- if (!claims.iss || !validIssuers.includes(claims.iss)) {
2442
- throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, `Unexpected ID token issuer: ${claims.iss}`, exports.AuthProvider.GOOGLE);
2443
- }
2444
- if (claims.aud !== options.clientId) {
2445
- throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', exports.AuthProvider.GOOGLE);
2446
- }
2447
- if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
2448
- throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', exports.AuthProvider.GOOGLE);
2449
- }
2450
- // Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
2451
- if (this.currentNonce && claims.nonce && claims.nonce !== this.currentNonce) {
2452
- throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', exports.AuthProvider.GOOGLE);
2453
- }
2454
- return claims;
2455
- }
2456
- buildUser(claims) {
2457
- var _a, _b;
2458
- const uid = claims.sub || this.generateUniqueId();
2459
- const email = (_a = claims.email) !== null && _a !== void 0 ? _a : null;
2460
- const emailVerified = claims.email_verified === true || claims.email_verified === 'true';
2461
- const displayName = claims.name ||
2462
- [claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
2463
- null;
2464
- const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
2465
- return {
2466
- uid,
2467
- email,
2468
- emailVerified,
2469
- displayName,
2470
- photoURL,
2471
- phoneNumber: null,
2472
- isAnonymous: false,
2473
- tenantId: null,
2474
- providerData: [
2475
- {
2476
- providerId: 'google.com',
2477
- uid,
2478
- displayName,
2479
- email,
2480
- phoneNumber: null,
2481
- photoURL,
2482
- },
2483
- ],
2484
- metadata: {
2485
- creationTime: new Date().toISOString(),
2486
- lastSignInTime: new Date().toISOString(),
2487
- },
2488
- };
2489
- }
2490
- resolvePending(result) {
2491
- const resolve = this.pendingResolve;
2492
- this.pendingResolve = null;
2493
- this.pendingReject = null;
2494
- resolve === null || resolve === void 0 ? void 0 : resolve(result);
2495
- }
2496
- rejectPending(error) {
2497
- const reject = this.pendingReject;
2498
- this.pendingResolve = null;
2499
- this.pendingReject = null;
2500
- if (reject) {
2501
- reject(error);
2502
- }
2503
- else {
2504
- this.logger.error('Google sign-in error with no pending request', error);
2505
- }
2506
- }
2507
- loadGsi() {
2508
- var _a, _b;
2509
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
2510
- return Promise.resolve();
2511
- }
2512
- if (this.loadPromise) {
2513
- return this.loadPromise;
2514
- }
2515
- this.loadPromise = new Promise((resolve, reject) => {
2516
- var _a, _b;
2517
- const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
2518
- const onReady = () => {
2519
- var _a, _b;
2520
- return ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
2521
- ? resolve()
2522
- : reject(new Error('Google Identity Services failed to load'));
2523
- };
2524
- if (existing) {
2525
- existing.addEventListener('load', onReady, { once: true });
2526
- existing.addEventListener('error', () => reject(new Error('Failed to load Google Identity Services')), { once: true });
2527
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
2528
- resolve();
2529
- }
2530
- return;
2531
- }
2532
- const script = document.createElement('script');
2533
- script.src = GSI_SRC;
2534
- script.async = true;
2535
- script.defer = true;
2536
- script.onload = onReady;
2537
- script.onerror = () => reject(new Error('Failed to load Google Identity Services'));
2538
- document.head.appendChild(script);
2539
- }).finally(() => {
2540
- this.loadPromise = null;
2541
- });
2542
- return this.loadPromise;
2543
- }
2544
- }
2545
- /** Decodes a JWT payload (no signature verification — Google issues the token directly to this origin). */
2546
- function decodeJwtPayload(jwt) {
2547
- const parts = jwt.split('.');
2548
- if (parts.length !== 3) {
2549
- throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', exports.AuthProvider.GOOGLE);
2550
- }
2551
- if (typeof atob !== 'function') {
2552
- // This provider only runs in the browser (the registry routes native platforms to the native
2553
- // bridge); `atob` is always present there.
2554
- throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', exports.AuthProvider.GOOGLE);
2555
- }
2556
- const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
2557
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
2558
- const binary = atob(padded);
2559
- const bytes = new Uint8Array(binary.length);
2560
- for (let i = 0; i < binary.length; i++) {
2561
- bytes[i] = binary.charCodeAt(i);
2562
- }
2563
- const json = new TextDecoder().decode(bytes);
2564
- return JSON.parse(json);
2565
- }
2566
-
2567
- var googleProvider = /*#__PURE__*/Object.freeze({
2568
- __proto__: null,
2569
- GoogleAuthProviderWeb: GoogleAuthProviderWeb
684
+ Object.defineProperty(exports, "CapacitorAuthManager", {
685
+ enumerable: true,
686
+ get: function () { return core.CapacitorAuthManager; }
2570
687
  });
2571
-
2572
- /**
2573
- * Legacy web-bridge factory (used by `CapacitorAuthManagerWeb` in `src/web.ts`).
2574
- *
2575
- * WIP: as of 2.4.1 only Google is enabled. Every other provider returns `null` here — the web bridge
2576
- * then leaves it unconfigured, and the modern `auth` API reports `AuthErrorCode.PROVIDER_NOT_ENABLED`.
2577
- * Providers are re-added one at a time as each is hardened (see
2578
- * docs/features/google-provider-production-v3). Their implementations still live under `web/` but are
2579
- * excluded from the published build until then.
2580
- */
2581
- class ProviderFactory {
2582
- static async createProvider(config, storage, logger, persistence) {
2583
- if (config.provider === exports.AuthProvider.GOOGLE) {
2584
- return new GoogleAuthProviderWeb({
2585
- provider: config.provider,
2586
- options: config.options,
2587
- storage,
2588
- logger,
2589
- persistence,
2590
- });
2591
- }
2592
- logger.warn(`Provider '${config.provider}' is not enabled yet — capacitor-auth-manager currently ships a ` +
2593
- `hardened Google provider; the rest are re-enabled one at a time.`);
2594
- return null;
2595
- }
2596
- }
2597
-
2598
- class CapacitorAuthManagerWeb extends core.WebPlugin {
2599
- constructor() {
2600
- super();
2601
- this.providers = new Map();
2602
- this.isInitialized = false;
2603
- this.currentProvider = null;
2604
- this.tokenRefreshTimers = new Map();
2605
- this.autoRefreshToken = true;
2606
- this.tokenRefreshBuffer = 300000; // 5 minutes before expiry
2607
- this.authStateEmitter = new EventEmitter();
2608
- this.storage = new WebStorage(exports.AuthPersistence.LOCAL);
2609
- this.logger = new Logger({
2610
- enableLogging: false,
2611
- logLevel: 'info',
2612
- prefix: 'CapAuthManager',
2613
- });
2614
- }
2615
- async initialize(options) {
2616
- var _a, _b;
2617
- if (this.isInitialized) {
2618
- this.logger.warn('Auth manager already initialized');
2619
- return;
2620
- }
2621
- try {
2622
- // Configure logger
2623
- if (options.enableLogging !== undefined) {
2624
- this.logger.setEnabled(options.enableLogging);
2625
- }
2626
- if (options.logLevel) {
2627
- this.logger.setLogLevel(options.logLevel);
2628
- }
2629
- // Configure persistence
2630
- if (options.persistence) {
2631
- this.storage = new WebStorage(options.persistence);
2632
- }
2633
- // Configure auto refresh
2634
- this.autoRefreshToken = (_a = options.autoRefreshToken) !== null && _a !== void 0 ? _a : true;
2635
- this.tokenRefreshBuffer = (_b = options.tokenRefreshBuffer) !== null && _b !== void 0 ? _b : 300000;
2636
- // Initialize providers
2637
- for (const providerConfig of options.providers) {
2638
- await this.initializeProvider(providerConfig);
2639
- }
2640
- // Load last used provider
2641
- const lastProvider = await this.storage.get('last_auth_provider');
2642
- if (lastProvider) {
2643
- this.currentProvider = lastProvider;
2644
- }
2645
- this.isInitialized = true;
2646
- this.logger.info('Auth manager initialized successfully');
2647
- }
2648
- catch (error) {
2649
- this.logger.error('Failed to initialize auth manager', error);
2650
- throw AuthError.fromError(error);
2651
- }
2652
- }
2653
- async signIn(options) {
2654
- var _a;
2655
- this.validateInitialized();
2656
- const provider = this.getProvider(options.provider);
2657
- try {
2658
- this.logger.info(`Signing in with ${options.provider}`);
2659
- const result = await provider.signIn(options);
2660
- // Set as current provider
2661
- this.currentProvider = options.provider;
2662
- await this.storage.set('last_auth_provider', options.provider);
2663
- // Setup token refresh if needed
2664
- if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
2665
- this.setupTokenRefresh(options.provider, result.credential);
2666
- }
2667
- // Forward auth state change
2668
- this.authStateEmitter.emit(result.user);
2669
- return result;
2670
- }
2671
- catch (error) {
2672
- this.logger.error(`Sign in failed for ${options.provider}`, error);
2673
- throw AuthError.fromError(error, options.provider);
2674
- }
2675
- }
2676
- async signOut(options) {
2677
- this.validateInitialized();
2678
- try {
2679
- if (options === null || options === void 0 ? void 0 : options.provider) {
2680
- // Sign out from specific provider
2681
- const provider = this.getProvider(options.provider);
2682
- await provider.signOut(options);
2683
- // Cancel token refresh
2684
- this.cancelTokenRefresh(options.provider);
2685
- }
2686
- else if (this.currentProvider) {
2687
- // Sign out from current provider
2688
- const provider = this.getProvider(this.currentProvider);
2689
- await provider.signOut(options);
2690
- // Untargeted sign-out: clear ALL refresh timers, not just the current provider's, so
2691
- // no orphaned timers remain for previously-active providers (F-18).
2692
- this.cancelAllTokenRefresh();
2693
- // Clear current provider
2694
- this.currentProvider = null;
2695
- await this.storage.remove('last_auth_provider');
2696
- }
2697
- else {
2698
- // Sign out from all providers
2699
- for (const [providerId, provider] of this.providers) {
2700
- try {
2701
- await provider.signOut(options);
2702
- this.cancelTokenRefresh(providerId);
2703
- }
2704
- catch (error) {
2705
- this.logger.error(`Failed to sign out from ${providerId}`, error);
2706
- }
2707
- }
2708
- // Defensive: clear any remaining timers (e.g. for providers that errored above).
2709
- this.cancelAllTokenRefresh();
2710
- this.currentProvider = null;
2711
- await this.storage.remove('last_auth_provider');
2712
- }
2713
- // Emit null user
2714
- this.authStateEmitter.emit(null);
2715
- }
2716
- catch (error) {
2717
- this.logger.error('Sign out failed', error);
2718
- throw AuthError.fromError(error);
2719
- }
2720
- }
2721
- async getCurrentUser() {
2722
- this.validateInitialized();
2723
- if (this.currentProvider) {
2724
- const provider = this.getProvider(this.currentProvider);
2725
- return provider.getCurrentUser();
2726
- }
2727
- // Try to get user from any provider. A not-yet-initialized provider can throw from
2728
- // getCurrentUser() (it lazily initializes), so isolate each and skip failures.
2729
- for (const [providerId, provider] of this.providers.entries()) {
2730
- try {
2731
- const user = await provider.getCurrentUser();
2732
- if (user) {
2733
- // Remember which provider owns the active session for subsequent calls.
2734
- this.currentProvider = providerId;
2735
- return user;
2736
- }
2737
- }
2738
- catch (error) {
2739
- this.logger.debug(`getCurrentUser: provider ${providerId} threw; skipping`, error);
2740
- continue;
2741
- }
2742
- }
2743
- return null;
2744
- }
2745
- async refreshToken(options) {
2746
- var _a;
2747
- this.validateInitialized();
2748
- const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
2749
- if (!providerId) {
2750
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for token refresh');
2751
- }
2752
- const provider = this.getProvider(providerId);
2753
- if (!provider.refreshToken) {
2754
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Token refresh not supported for provider ${providerId}`);
2755
- }
2756
- try {
2757
- const result = await provider.refreshToken(options);
2758
- // Setup new token refresh
2759
- if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
2760
- this.setupTokenRefresh(providerId, result.credential);
2761
- }
2762
- return result;
2763
- }
2764
- catch (error) {
2765
- this.logger.error(`Token refresh failed for ${providerId}`, error);
2766
- throw AuthError.fromError(error, providerId);
2767
- }
2768
- }
2769
- async addAuthStateListener(callback) {
2770
- const unsubscribe = this.authStateEmitter.subscribe(callback);
2771
- // Create a Capacitor-compatible listener handle
2772
- const handle = {
2773
- remove: async () => {
2774
- unsubscribe();
2775
- },
2776
- };
2777
- // Emit current user state
2778
- const currentUser = await this.getCurrentUser();
2779
- callback(currentUser);
2780
- return handle;
2781
- }
2782
- async removeAllListeners() {
2783
- var _a;
2784
- this.authStateEmitter.clear();
2785
- // Also clear provider listeners
2786
- for (const provider of this.providers.values()) {
2787
- (_a = provider.dispose) === null || _a === void 0 ? void 0 : _a.call(provider);
2788
- }
2789
- }
2790
- async isSupported(options) {
2791
- try {
2792
- if (!this.providers.has(options.provider)) {
2793
- return {
2794
- isSupported: false,
2795
- reason: 'Provider not configured',
2796
- availableProviders: Array.from(this.providers.keys()),
2797
- };
2798
- }
2799
- const provider = this.getProvider(options.provider);
2800
- const isSupported = await provider.isSupported();
2801
- return {
2802
- isSupported,
2803
- reason: isSupported
2804
- ? undefined
2805
- : 'Provider not supported on this platform',
2806
- availableProviders: Array.from(this.providers.keys()),
2807
- };
2808
- }
2809
- catch (error) {
2810
- return {
2811
- isSupported: false,
2812
- reason: error instanceof Error ? error.message : 'Unknown error',
2813
- availableProviders: Array.from(this.providers.keys()),
2814
- };
2815
- }
2816
- }
2817
- async configure(options) {
2818
- this.validateInitialized();
2819
- const providerConfig = {
2820
- provider: options.provider,
2821
- options: options.options,
2822
- };
2823
- await this.initializeProvider(providerConfig);
2824
- }
2825
- async linkAccount(options) {
2826
- this.validateInitialized();
2827
- const provider = this.getProvider(options.provider);
2828
- if (!provider.linkAccount) {
2829
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking not supported for provider ${options.provider}`);
2830
- }
2831
- try {
2832
- return await provider.linkAccount(options);
2833
- }
2834
- catch (error) {
2835
- this.logger.error(`Account linking failed for ${options.provider}`, error);
2836
- throw AuthError.fromError(error, options.provider);
2837
- }
2838
- }
2839
- async unlinkAccount(options) {
2840
- this.validateInitialized();
2841
- const provider = this.getProvider(options.provider);
2842
- if (!provider.unlinkAccount) {
2843
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking not supported for provider ${options.provider}`);
2844
- }
2845
- try {
2846
- await provider.unlinkAccount(options);
2847
- }
2848
- catch (error) {
2849
- this.logger.error(`Account unlinking failed for ${options.provider}`, error);
2850
- throw AuthError.fromError(error, options.provider);
2851
- }
2852
- }
2853
- async sendPasswordResetEmail(options) {
2854
- this.validateInitialized();
2855
- // Try email-password provider first
2856
- const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
2857
- if (emailPasswordProvider && 'sendPasswordReset' in emailPasswordProvider) {
2858
- const provider = emailPasswordProvider;
2859
- await provider.sendPasswordReset(options.email);
2860
- return;
2861
- }
2862
- // Try phone-password provider
2863
- const phonePasswordProvider = this.providers.get(exports.AuthProvider.PHONE_PASSWORD);
2864
- if (phonePasswordProvider && 'sendPasswordReset' in phonePasswordProvider) {
2865
- const provider = phonePasswordProvider;
2866
- await provider.sendPasswordReset(options.email);
2867
- return;
2868
- }
2869
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Password reset requires email-password or phone-password provider to be configured');
2870
- }
2871
- async sendEmailVerification(_options) {
2872
- this.validateInitialized();
2873
- // Email verification is typically handled by email-password provider
2874
- const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
2875
- if (emailPasswordProvider && 'sendEmailVerification' in emailPasswordProvider) {
2876
- const provider = emailPasswordProvider;
2877
- await provider.sendEmailVerification();
2878
- return;
2879
- }
2880
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email verification requires email-password provider to be configured');
2881
- }
2882
- async sendSmsCode(options) {
2883
- this.validateInitialized();
2884
- // Delegate to SMS provider
2885
- const smsProvider = this.providers.get(exports.AuthProvider.SMS);
2886
- if (smsProvider && 'sendCode' in smsProvider) {
2887
- const provider = smsProvider;
2888
- await provider.sendCode(options.phoneNumber);
2889
- return;
2890
- }
2891
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
2892
- }
2893
- async verifySmsCode(options) {
2894
- this.validateInitialized();
2895
- // Delegate to SMS provider
2896
- const smsProvider = this.providers.get(exports.AuthProvider.SMS);
2897
- if (smsProvider && 'verifyCode' in smsProvider) {
2898
- const provider = smsProvider;
2899
- return await provider.verifyCode(options.phoneNumber, options.code);
2900
- }
2901
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
2902
- }
2903
- async sendEmailCode(options) {
2904
- this.validateInitialized();
2905
- // Delegate to email-code provider
2906
- const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
2907
- if (emailCodeProvider) {
2908
- // The email-code provider's signIn accepts { email } to send the code
2909
- await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email } });
2910
- return;
2911
- }
2912
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
2913
- }
2914
- async verifyEmailCode(options) {
2915
- this.validateInitialized();
2916
- // Delegate to email-code provider
2917
- const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
2918
- if (emailCodeProvider) {
2919
- // The email-code provider's signIn accepts { email, code } to verify
2920
- return await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email, code: options.code } });
2921
- }
2922
- throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
2923
- }
2924
- async updateProfile(options) {
2925
- this.validateInitialized();
2926
- if (!this.currentProvider) {
2927
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
2928
- }
2929
- const provider = this.providers.get(this.currentProvider);
2930
- if (!provider) {
2931
- throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Current provider not found');
2932
- }
2933
- // Check if provider supports updateProfile
2934
- if ('updateProfile' in provider && typeof provider.updateProfile === 'function') {
2935
- const updateFn = provider.updateProfile;
2936
- return await updateFn(options);
2937
- }
2938
- // Fallback: update cached user info locally
2939
- const currentUser = await this.getCurrentUser();
2940
- if (!currentUser) {
2941
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
2942
- }
2943
- // Update local user data
2944
- const updatedUser = Object.assign(Object.assign({}, currentUser), { displayName: options.displayName !== undefined ? options.displayName : currentUser.displayName, photoURL: options.photoURL !== undefined ? options.photoURL : currentUser.photoURL, phoneNumber: options.phoneNumber !== undefined ? options.phoneNumber : currentUser.phoneNumber });
2945
- // Persist the updated user so it survives a reload — providers that extend BaseAuthProvider
2946
- // read the cached user from `${provider}_current_user` on init (F-36). Without this the
2947
- // fallback only emitted the change in-memory and it reverted on the next page load.
2948
- await this.persistFallbackUser(updatedUser);
2949
- this.authStateEmitter.emit(updatedUser);
2950
- return updatedUser;
2951
- }
2952
- /**
2953
- * Writes an updated user back to storage under the same key BaseAuthProvider uses
2954
- * (`${provider}_current_user`) for the active provider, so the local profile change survives a
2955
- * reload even when the provider has no native `updateProfile`. Best-effort: storage failures are
2956
- * logged, not thrown, since the in-memory update already succeeded.
2957
- */
2958
- async persistFallbackUser(user) {
2959
- if (!this.currentProvider) {
2960
- return;
2961
- }
2962
- try {
2963
- await this.storage.set(`${this.currentProvider}_current_user`, user);
2964
- }
2965
- catch (error) {
2966
- this.logger.error(`Failed to persist updated profile for ${this.currentProvider}`, error);
2967
- }
2968
- }
2969
- async deleteAccount(options) {
2970
- this.validateInitialized();
2971
- const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
2972
- if (!providerId) {
2973
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
2974
- }
2975
- const provider = this.providers.get(providerId);
2976
- if (!provider) {
2977
- throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Provider not found');
2978
- }
2979
- // Check if provider supports account deletion
2980
- if ('deleteAccount' in provider && typeof provider.deleteAccount === 'function') {
2981
- const deleteFn = provider.deleteAccount;
2982
- await deleteFn();
2983
- await this.signOut();
2984
- return;
2985
- }
2986
- // If provider doesn't support deletion, revoke access and sign out
2987
- if ('revokeAccess' in provider && typeof provider.revokeAccess === 'function') {
2988
- const revokeFn = provider.revokeAccess;
2989
- await revokeFn();
2990
- }
2991
- await this.signOut();
2992
- }
2993
- async getIdToken(options) {
2994
- var _a;
2995
- this.validateInitialized();
2996
- const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
2997
- if (!providerId) {
2998
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for ID token');
2999
- }
3000
- const provider = this.providers.get(providerId);
3001
- if (!provider) {
3002
- throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, `Provider ${providerId} not configured`);
3003
- }
3004
- // Check if provider has getIdToken method
3005
- if ('getIdToken' in provider && typeof provider.getIdToken === 'function') {
3006
- const getIdTokenFn = provider.getIdToken;
3007
- return await getIdTokenFn((_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
3008
- }
3009
- // Try to get ID token from stored credential. The storage layer (WebStorage/
3010
- // CapacitorPreferencesStorage) already JSON-parses on read, so the value is the
3011
- // parsed credential object — do NOT JSON.parse it again.
3012
- const parsed = (await this.storage.get(`${providerId}_credential`));
3013
- if (parsed) {
3014
- if (parsed.idToken) {
3015
- // Check if token needs refresh
3016
- if ((options === null || options === void 0 ? void 0 : options.forceRefresh) ||
3017
- (parsed.expiresAt && parsed.expiresAt < Date.now())) {
3018
- // Try to refresh
3019
- if (provider.refreshToken) {
3020
- const result = await provider.refreshToken({
3021
- provider: providerId,
3022
- forceRefresh: true,
3023
- });
3024
- if (result.credential.idToken) {
3025
- return result.credential.idToken;
3026
- }
3027
- }
3028
- }
3029
- else {
3030
- return parsed.idToken;
3031
- }
3032
- }
3033
- }
3034
- throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, `No ID token available for provider ${providerId}. Some providers (OAuth without OIDC) do not issue ID tokens.`);
3035
- }
3036
- /**
3037
- * Persists provider-specific custom OAuth parameters.
3038
- *
3039
- * IMPORTANT (F-35): the underlying OAuth flow applies custom parameters that are passed directly
3040
- * to {@link signIn} (`signIn({ provider, options: { customParameters } })`). The values stored
3041
- * here are NOT automatically merged into a later `signIn` authorization URL — read them back and
3042
- * pass them to `signIn` if you need them applied. The stored value is the raw parameters object
3043
- * (the storage layer serializes it); it is not double JSON-encoded.
3044
- */
3045
- async setCustomParameters(options) {
3046
- this.validateInitialized();
3047
- // Store the raw object — WebStorage/CapacitorPreferencesStorage serialize on write, so passing
3048
- // a pre-stringified value here would double-encode it.
3049
- await this.storage.set(`${options.provider}_custom_params`, options.parameters);
3050
- }
3051
- async revokeAccess(options) {
3052
- this.validateInitialized();
3053
- const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
3054
- if (!providerId) {
3055
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for access revocation');
3056
- }
3057
- const provider = this.getProvider(providerId);
3058
- if (!provider.revokeAccess) {
3059
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation not supported for provider ${providerId}`);
3060
- }
3061
- try {
3062
- await provider.revokeAccess(options === null || options === void 0 ? void 0 : options.token);
3063
- }
3064
- catch (error) {
3065
- this.logger.error(`Access revocation failed for ${providerId}`, error);
3066
- throw AuthError.fromError(error, providerId);
3067
- }
3068
- }
3069
- validateInitialized() {
3070
- if (!this.isInitialized) {
3071
- throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Auth manager not initialized. Call initialize() first.');
3072
- }
3073
- }
3074
- getProvider(providerId) {
3075
- const provider = this.providers.get(providerId);
3076
- if (!provider) {
3077
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, `Provider ${providerId} not configured`);
3078
- }
3079
- return provider;
3080
- }
3081
- async initializeProvider(config) {
3082
- try {
3083
- // Dynamically import provider implementation
3084
- const provider = await this.createProvider(config);
3085
- if (provider) {
3086
- // Initialize if the provider supports it
3087
- if (provider.initialize) {
3088
- await provider.initialize(config.options);
3089
- }
3090
- // Forward auth state changes if provider supports it (BaseAuthProvider only)
3091
- if ('addAuthStateListener' in provider && typeof provider.addAuthStateListener === 'function') {
3092
- provider.addAuthStateListener((user) => {
3093
- if (user) {
3094
- this.authStateEmitter.emit(user);
3095
- }
3096
- });
3097
- }
3098
- this.providers.set(config.provider, provider);
3099
- this.logger.info(`Provider ${config.provider} initialized`);
3100
- }
3101
- }
3102
- catch (error) {
3103
- this.logger.error(`Failed to initialize provider ${config.provider}`, error);
3104
- throw error;
3105
- }
3106
- }
3107
- async createProvider(config) {
3108
- return ProviderFactory.createProvider(config, this.storage, this.logger, this.storage instanceof WebStorage
3109
- ? exports.AuthPersistence.LOCAL
3110
- : exports.AuthPersistence.NONE);
3111
- }
3112
- setupTokenRefresh(provider, credential) {
3113
- // Cancel existing refresh timer
3114
- this.cancelTokenRefresh(provider);
3115
- if (!credential.expiresAt || !credential.refreshToken) {
3116
- return;
3117
- }
3118
- const refreshTime = credential.expiresAt - this.tokenRefreshBuffer - Date.now();
3119
- if (refreshTime > 0) {
3120
- this.scheduleRefresh(provider, refreshTime);
3121
- }
3122
- }
3123
- /**
3124
- * Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
3125
- * (2,147,483,647 ms ≈ 24.8 days). A far-future `expiresAt` would otherwise overflow the timer
3126
- * and fire almost immediately (refresh storm). When clamped, the timer reschedules the remaining
3127
- * wait on fire instead of refreshing early (F-17).
3128
- */
3129
- scheduleRefresh(provider, delayMs) {
3130
- const MAX_TIMEOUT = 2147483647;
3131
- const clamped = Math.min(delayMs, MAX_TIMEOUT);
3132
- const timer = setTimeout(() => {
3133
- const remaining = delayMs - clamped;
3134
- if (remaining > 0) {
3135
- this.scheduleRefresh(provider, remaining);
3136
- return;
3137
- }
3138
- void (async () => {
3139
- try {
3140
- await this.refreshToken({ provider });
3141
- }
3142
- catch (error) {
3143
- this.logger.error(`Auto token refresh failed for ${provider}`, error);
3144
- }
3145
- })();
3146
- }, clamped);
3147
- this.tokenRefreshTimers.set(provider, timer);
3148
- }
3149
- cancelTokenRefresh(provider) {
3150
- const timer = this.tokenRefreshTimers.get(provider);
3151
- if (timer) {
3152
- clearTimeout(timer);
3153
- this.tokenRefreshTimers.delete(provider);
3154
- }
3155
- }
3156
- /** Clears every active refresh timer (used on a global, untargeted sign-out). */
3157
- cancelAllTokenRefresh() {
3158
- for (const timer of this.tokenRefreshTimers.values()) {
3159
- clearTimeout(timer);
3160
- }
3161
- this.tokenRefreshTimers.clear();
3162
- }
3163
- }
3164
-
3165
- var web = /*#__PURE__*/Object.freeze({
3166
- __proto__: null,
3167
- CapacitorAuthManagerWeb: CapacitorAuthManagerWeb
688
+ Object.defineProperty(exports, "auth", {
689
+ enumerable: true,
690
+ get: function () { return core.auth; }
3168
691
  });
3169
-
3170
692
  exports.AuthError = AuthError;
3171
- exports.CapacitorAuthManager = CapacitorAuthManager;
3172
693
  exports.CapacitorPreferencesStorage = CapacitorPreferencesStorage;
3173
694
  exports.Logger = Logger;
3174
695
  exports.PlatformDetector = PlatformDetector;
3175
696
  exports.WebStorage = WebStorage;
3176
- exports.auth = auth;
3177
697
  exports.defaultLogger = defaultLogger;
3178
698
  exports.isAuthError = isAuthError;