capacitor-auth-manager 2.4.4 → 3.0.0

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