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