capacitor-auth-manager 2.1.0 → 2.2.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 (148) hide show
  1. package/CapacitorAuthManager.podspec +1 -1
  2. package/Readme.md +223 -103
  3. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +28 -0
  4. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +109 -15
  5. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/FacebookAuthProvider.java +389 -0
  6. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +353 -0
  7. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/MicrosoftAuthProvider.java +455 -0
  8. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +180 -0
  9. package/dist/angular.cjs.js +7017 -0
  10. package/dist/angular.cjs.js.map +1 -0
  11. package/dist/core.cjs.js +2155 -444
  12. package/dist/core.cjs.js.map +1 -1
  13. package/dist/esm/angular/auth.guard.d.ts +18 -0
  14. package/dist/esm/angular/auth.guard.js +82 -0
  15. package/dist/esm/angular/auth.guard.js.map +1 -0
  16. package/dist/esm/angular/auth.module.d.ts +18 -0
  17. package/dist/esm/angular/auth.module.js +56 -0
  18. package/dist/esm/angular/auth.module.js.map +1 -0
  19. package/dist/esm/angular/auth.service.d.ts +108 -0
  20. package/dist/esm/angular/auth.service.js +224 -0
  21. package/dist/esm/angular/auth.service.js.map +1 -0
  22. package/dist/esm/angular/index.d.ts +3 -0
  23. package/dist/esm/angular/index.js +4 -0
  24. package/dist/esm/angular/index.js.map +1 -0
  25. package/dist/esm/core/auth-manager.d.ts +61 -1
  26. package/dist/esm/core/auth-manager.js +285 -24
  27. package/dist/esm/core/auth-manager.js.map +1 -1
  28. package/dist/esm/core/platform.d.ts +7 -0
  29. package/dist/esm/core/platform.js +30 -10
  30. package/dist/esm/core/platform.js.map +1 -1
  31. package/dist/esm/core/provider-manifests.d.ts +9 -0
  32. package/dist/esm/core/provider-manifests.js +471 -0
  33. package/dist/esm/core/provider-manifests.js.map +1 -0
  34. package/dist/esm/core/provider-registry.d.ts +19 -1
  35. package/dist/esm/core/provider-registry.js +72 -480
  36. package/dist/esm/core/provider-registry.js.map +1 -1
  37. package/dist/esm/core/types.d.ts +18 -7
  38. package/dist/esm/definitions.d.ts +42 -1
  39. package/dist/esm/definitions.js +28 -0
  40. package/dist/esm/definitions.js.map +1 -1
  41. package/dist/esm/index.d.ts +4 -0
  42. package/dist/esm/index.js +6 -0
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/providers/base-provider.d.ts +3 -3
  45. package/dist/esm/providers/base-provider.js +26 -1
  46. package/dist/esm/providers/base-provider.js.map +1 -1
  47. package/dist/esm/providers/oauth-provider.d.ts +23 -2
  48. package/dist/esm/providers/oauth-provider.js +134 -17
  49. package/dist/esm/providers/oauth-provider.js.map +1 -1
  50. package/dist/esm/providers/provider-factory.d.ts +3 -1
  51. package/dist/esm/providers/provider-factory.js +29 -41
  52. package/dist/esm/providers/provider-factory.js.map +1 -1
  53. package/dist/esm/providers/web/apple-provider.d.ts +2 -1
  54. package/dist/esm/providers/web/apple-provider.js +25 -9
  55. package/dist/esm/providers/web/apple-provider.js.map +1 -1
  56. package/dist/esm/providers/web/biometric-provider.d.ts +14 -0
  57. package/dist/esm/providers/web/biometric-provider.js +116 -18
  58. package/dist/esm/providers/web/biometric-provider.js.map +1 -1
  59. package/dist/esm/providers/web/email-code-provider.d.ts +48 -0
  60. package/dist/esm/providers/web/email-code-provider.js +295 -0
  61. package/dist/esm/providers/web/email-code-provider.js.map +1 -0
  62. package/dist/esm/providers/web/email-password-provider.js +29 -28
  63. package/dist/esm/providers/web/email-password-provider.js.map +1 -1
  64. package/dist/esm/providers/web/facebook-provider.d.ts +52 -1
  65. package/dist/esm/providers/web/facebook-provider.js +2 -2
  66. package/dist/esm/providers/web/facebook-provider.js.map +1 -1
  67. package/dist/esm/providers/web/firebase-provider.d.ts +5 -3
  68. package/dist/esm/providers/web/firebase-provider.js +74 -42
  69. package/dist/esm/providers/web/firebase-provider.js.map +1 -1
  70. package/dist/esm/providers/web/github-provider.d.ts +9 -0
  71. package/dist/esm/providers/web/github-provider.js +91 -14
  72. package/dist/esm/providers/web/github-provider.js.map +1 -1
  73. package/dist/esm/providers/web/index.d.ts +2 -0
  74. package/dist/esm/providers/web/index.js +2 -0
  75. package/dist/esm/providers/web/index.js.map +1 -1
  76. package/dist/esm/providers/web/linkedin-provider.d.ts +2 -3
  77. package/dist/esm/providers/web/linkedin-provider.js +40 -14
  78. package/dist/esm/providers/web/linkedin-provider.js.map +1 -1
  79. package/dist/esm/providers/web/magic-link-provider.d.ts +3 -3
  80. package/dist/esm/providers/web/magic-link-provider.js +40 -26
  81. package/dist/esm/providers/web/magic-link-provider.js.map +1 -1
  82. package/dist/esm/providers/web/microsoft-provider.d.ts +2 -0
  83. package/dist/esm/providers/web/microsoft-provider.js +45 -20
  84. package/dist/esm/providers/web/microsoft-provider.js.map +1 -1
  85. package/dist/esm/providers/web/phone-password-provider.d.ts +66 -0
  86. package/dist/esm/providers/web/phone-password-provider.js +438 -0
  87. package/dist/esm/providers/web/phone-password-provider.js.map +1 -0
  88. package/dist/esm/providers/web/slack-provider.d.ts +2 -3
  89. package/dist/esm/providers/web/slack-provider.js +38 -14
  90. package/dist/esm/providers/web/slack-provider.js.map +1 -1
  91. package/dist/esm/providers/web/sms-provider.d.ts +3 -3
  92. package/dist/esm/providers/web/sms-provider.js +25 -18
  93. package/dist/esm/providers/web/sms-provider.js.map +1 -1
  94. package/dist/esm/providers/web/username-password-provider.js +23 -22
  95. package/dist/esm/providers/web/username-password-provider.js.map +1 -1
  96. package/dist/esm/react/hooks.d.ts +110 -0
  97. package/dist/esm/react/hooks.js +307 -0
  98. package/dist/esm/react/hooks.js.map +1 -0
  99. package/dist/esm/react/index.d.ts +2 -0
  100. package/dist/esm/react/index.js +3 -0
  101. package/dist/esm/react/index.js.map +1 -0
  102. package/dist/esm/react/types.d.ts +30 -0
  103. package/dist/esm/react/types.js +2 -0
  104. package/dist/esm/react/types.js.map +1 -0
  105. package/dist/esm/utils/auth-error.d.ts +7 -0
  106. package/dist/esm/utils/auth-error.js +31 -5
  107. package/dist/esm/utils/auth-error.js.map +1 -1
  108. package/dist/esm/utils/event-emitter.d.ts +7 -0
  109. package/dist/esm/utils/event-emitter.js +8 -2
  110. package/dist/esm/utils/event-emitter.js.map +1 -1
  111. package/dist/esm/utils/logger.d.ts +28 -1
  112. package/dist/esm/utils/logger.js +115 -1
  113. package/dist/esm/utils/logger.js.map +1 -1
  114. package/dist/esm/utils/pending-verification-store.d.ts +59 -0
  115. package/dist/esm/utils/pending-verification-store.js +103 -0
  116. package/dist/esm/utils/pending-verification-store.js.map +1 -0
  117. package/dist/esm/utils/storage.d.ts +29 -1
  118. package/dist/esm/utils/storage.js +64 -5
  119. package/dist/esm/utils/storage.js.map +1 -1
  120. package/dist/esm/vue/composables.d.ts +124 -0
  121. package/dist/esm/vue/composables.js +290 -0
  122. package/dist/esm/vue/composables.js.map +1 -0
  123. package/dist/esm/vue/index.d.ts +1 -0
  124. package/dist/esm/vue/index.js +2 -0
  125. package/dist/esm/vue/index.js.map +1 -0
  126. package/dist/esm/web.d.ts +32 -7
  127. package/dist/esm/web.js +247 -52
  128. package/dist/esm/web.js.map +1 -1
  129. package/dist/plugin.cjs.js +2606 -670
  130. package/dist/plugin.cjs.js.map +1 -1
  131. package/dist/plugin.js +2606 -670
  132. package/dist/plugin.js.map +1 -1
  133. package/dist/react.cjs.js +6972 -0
  134. package/dist/react.cjs.js.map +1 -0
  135. package/dist/vue.cjs.js +6955 -0
  136. package/dist/vue.cjs.js.map +1 -0
  137. package/ios/Plugin/AppleAuthProvider.swift +288 -0
  138. package/ios/Plugin/AuthStorage.swift +49 -1
  139. package/ios/Plugin/CapacitorAuthManager.swift +45 -23
  140. package/ios/Plugin/FacebookAuthProvider.swift +297 -0
  141. package/ios/Plugin/GitHubAuthProvider.swift +54 -0
  142. package/ios/Plugin/GoogleAuthProvider.swift +265 -0
  143. package/ios/Plugin/LinkedInAuthProvider.swift +63 -0
  144. package/ios/Plugin/MicrosoftAuthProvider.swift +315 -0
  145. package/ios/Plugin/Models.swift +4 -1
  146. package/ios/Plugin/OAuthWebProvider.swift +415 -0
  147. package/ios/Plugin/SlackAuthProvider.swift +108 -0
  148. package/package.json +60 -39
package/dist/plugin.js CHANGED
@@ -1,43 +1,66 @@
1
1
  var CapacitorAuthManager = (function (exports, core) {
2
2
  'use strict';
3
3
 
4
- class EventEmitter {
5
- constructor() {
6
- this.listeners = new Set();
7
- }
8
- emit(data) {
9
- this.listeners.forEach((listener) => {
10
- try {
11
- listener(data);
12
- }
13
- catch (error) {
14
- console.error('Error in event listener:', error);
15
- }
16
- });
17
- }
18
- subscribe(listener) {
19
- this.listeners.add(listener);
20
- return () => {
21
- this.listeners.delete(listener);
22
- };
23
- }
24
- clear() {
25
- this.listeners.clear();
26
- }
27
- get listenerCount() {
28
- return this.listeners.size;
29
- }
4
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
5
+ /**
6
+ * Reads a default log level from the build/runtime environment WITHOUT assuming a particular
7
+ * bundler or host. Checked defensively (each access wrapped) so it is safe in:
8
+ * - Vite / bundlers that define `import.meta.env`
9
+ * - Node / SSR where `globalThis.process.env` exists
10
+ * - Plain browsers where neither is present (falls back to 'warn')
11
+ *
12
+ * Intentional omissions for a PUBLISHED LIBRARY (see F-42):
13
+ * - We do NOT patch the host application's global `console.*`. A library silencing the host's
14
+ * console would be hostile and surprising.
15
+ * - We do NOT read the host's `localStorage` for a log-level switch. The host owns its storage;
16
+ * the consumer configures logging explicitly via `auth.configure({ logLevel })` or
17
+ * `logger.setLevel()`.
18
+ */
19
+ function readEnvLogLevel() {
20
+ var _a;
21
+ const candidates = [];
22
+ try {
23
+ // import.meta.env may not exist (CJS) — guard the whole access.
24
+ const metaEnv = (_a = ({ url: (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.js', document.baseURI).href) })) === null || _a === void 0 ? void 0 : _a.env;
25
+ if (metaEnv) {
26
+ candidates.push(metaEnv.VITE_LOG_LEVEL, metaEnv.LOG_LEVEL);
27
+ }
28
+ }
29
+ catch (_b) {
30
+ // import.meta unsupported in this environment — ignore.
31
+ }
32
+ try {
33
+ const proc = globalThis.process;
34
+ if (proc === null || proc === void 0 ? void 0 : proc.env) {
35
+ candidates.push(proc.env.VITE_LOG_LEVEL, proc.env.LOG_LEVEL);
36
+ }
37
+ }
38
+ catch (_c) {
39
+ // process not available — ignore.
40
+ }
41
+ for (const value of candidates) {
42
+ if (value === 'debug' ||
43
+ value === 'info' ||
44
+ value === 'warn' ||
45
+ value === 'error' ||
46
+ value === 'silent') {
47
+ return value;
48
+ }
49
+ }
50
+ return undefined;
30
51
  }
31
-
32
52
  class Logger {
33
53
  constructor(config) {
54
+ var _a, _b;
34
55
  this.logLevels = {
35
56
  debug: 0,
36
57
  info: 1,
37
58
  warn: 2,
38
59
  error: 3,
60
+ silent: 4,
39
61
  };
40
- this.config = config;
62
+ // An explicit logLevel from the caller wins; otherwise fall back to the env default, then 'warn'.
63
+ this.config = Object.assign(Object.assign({}, config), { logLevel: (_b = (_a = config.logLevel) !== null && _a !== void 0 ? _a : readEnvLogLevel()) !== null && _b !== void 0 ? _b : 'warn' });
41
64
  }
42
65
  shouldLog(level) {
43
66
  if (!this.config.enableLogging)
@@ -69,13 +92,110 @@ var CapacitorAuthManager = (function (exports, core) {
69
92
  console.error(this.formatMessage('error', message), error);
70
93
  }
71
94
  }
95
+ /** Verbose tracing — gated at `debug` level like {@link debug}. */
96
+ trace(message, ...args) {
97
+ if (this.shouldLog('debug')) {
98
+ console.trace(this.formatMessage('trace', message), ...args);
99
+ }
100
+ }
101
+ /** Tabular output — gated at `debug` level. Falls back to `debug` when `console.table` is absent. */
102
+ table(data, columns) {
103
+ if (this.shouldLog('debug')) {
104
+ if (typeof console.table === 'function') {
105
+ console.table(data, columns);
106
+ }
107
+ else {
108
+ console.debug(this.formatMessage('table', ''), data);
109
+ }
110
+ }
111
+ }
112
+ /** Opens a console group — gated at `debug` level. No-ops if `console.group` is absent. */
113
+ group(label) {
114
+ if (this.shouldLog('debug') && typeof console.group === 'function') {
115
+ console.group(label ? this.formatMessage('group', label) : undefined);
116
+ }
117
+ }
118
+ /** Closes a console group opened by {@link group}. */
119
+ groupEnd() {
120
+ if (this.shouldLog('debug') && typeof console.groupEnd === 'function') {
121
+ console.groupEnd();
122
+ }
123
+ }
124
+ /** Starts a timer — gated at `debug` level. No-ops if `console.time` is absent. */
125
+ time(label) {
126
+ if (this.shouldLog('debug') && typeof console.time === 'function') {
127
+ console.time(label);
128
+ }
129
+ }
130
+ /** Stops a timer started by {@link time} and logs the elapsed duration. */
131
+ timeEnd(label) {
132
+ if (this.shouldLog('debug') && typeof console.timeEnd === 'function') {
133
+ console.timeEnd(label);
134
+ }
135
+ }
72
136
  setLogLevel(level) {
73
137
  this.config.logLevel = level;
74
138
  }
139
+ /** Alias for {@link setLogLevel} matching the workspace logger convention. */
140
+ setLevel(level) {
141
+ this.config.logLevel = level;
142
+ }
143
+ getLevel() {
144
+ return this.config.logLevel;
145
+ }
75
146
  setEnabled(enabled) {
76
147
  this.config.enableLogging = enabled;
77
148
  }
78
149
  }
150
+ /**
151
+ * Shared default logger instance used by package internals that don't receive a logger via
152
+ * dependency injection (e.g. {@link EventEmitter}, {@link WebStorage} defaults, the biometric
153
+ * provider). Enabled by default at `warn` level so only warnings + errors surface unless the
154
+ * consumer raises the level. Consumers can adjust it programmatically:
155
+ *
156
+ * ```ts
157
+ * import { defaultLogger } from 'capacitor-auth-manager';
158
+ * defaultLogger.setLevel('debug');
159
+ * ```
160
+ */
161
+ const defaultLogger = new Logger({
162
+ enableLogging: true,
163
+ logLevel: 'warn',
164
+ prefix: 'CapacitorAuthManager',
165
+ });
166
+
167
+ class EventEmitter {
168
+ /**
169
+ * @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
170
+ * so emitter errors honour the package log level instead of writing to `console` directly.
171
+ */
172
+ constructor(logger = defaultLogger) {
173
+ this.listeners = new Set();
174
+ this.logger = logger;
175
+ }
176
+ emit(data) {
177
+ this.listeners.forEach((listener) => {
178
+ try {
179
+ listener(data);
180
+ }
181
+ catch (error) {
182
+ this.logger.error('Error in event listener:', error);
183
+ }
184
+ });
185
+ }
186
+ subscribe(listener) {
187
+ this.listeners.add(listener);
188
+ return () => {
189
+ this.listeners.delete(listener);
190
+ };
191
+ }
192
+ clear() {
193
+ this.listeners.clear();
194
+ }
195
+ get listenerCount() {
196
+ return this.listeners.size;
197
+ }
198
+ }
79
199
 
80
200
  exports.AuthProvider = void 0;
81
201
  (function (AuthProvider) {
@@ -189,11 +309,46 @@ var CapacitorAuthManager = (function (exports, core) {
189
309
  AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
190
310
  AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
191
311
  AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
312
+ // --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
313
+ // magic-link / biometric / email-password / username-password / phone-password) throw enum
314
+ // codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
315
+ AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
316
+ AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
317
+ AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
318
+ AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
319
+ AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
320
+ AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
321
+ AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
322
+ AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
323
+ AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
324
+ AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
325
+ AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
326
+ AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
327
+ AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
328
+ AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
329
+ AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
330
+ AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
331
+ AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
332
+ AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
333
+ AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
334
+ AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
335
+ AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
336
+ AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
337
+ AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
338
+ AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
339
+ AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
192
340
  })(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
193
341
 
194
342
  class WebStorage {
195
- constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_') {
343
+ /**
344
+ * @param persistence Where to persist values (local / session / in-memory).
345
+ * @param prefix Key prefix to namespace this package's storage.
346
+ * @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
347
+ * so storage failures honour the package log level instead of writing to `console` directly.
348
+ */
349
+ constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
196
350
  this.prefix = prefix;
351
+ this.logger = logger;
197
352
  switch (persistence) {
198
353
  case exports.AuthPersistence.SESSION:
199
354
  this.storage = window.sessionStorage;
@@ -223,7 +378,7 @@ var CapacitorAuthManager = (function (exports, core) {
223
378
  return null;
224
379
  }
225
380
  catch (error) {
226
- console.error('Storage get error:', error);
381
+ this.logger.error('Storage get error:', error);
227
382
  return null;
228
383
  }
229
384
  }
@@ -233,7 +388,7 @@ var CapacitorAuthManager = (function (exports, core) {
233
388
  this.storage.setItem(this.prefix + key, stringValue);
234
389
  }
235
390
  catch (error) {
236
- console.error('Storage set error:', error);
391
+ this.logger.error('Storage set error:', error);
237
392
  throw error;
238
393
  }
239
394
  }
@@ -242,7 +397,7 @@ var CapacitorAuthManager = (function (exports, core) {
242
397
  this.storage.removeItem(this.prefix + key);
243
398
  }
244
399
  catch (error) {
245
- console.error('Storage remove error:', error);
400
+ this.logger.error('Storage remove error:', error);
246
401
  }
247
402
  }
248
403
  async clear() {
@@ -257,8 +412,59 @@ var CapacitorAuthManager = (function (exports, core) {
257
412
  keys.forEach((key) => this.storage.removeItem(key));
258
413
  }
259
414
  catch (error) {
260
- console.error('Storage clear error:', error);
415
+ this.logger.error('Storage clear error:', error);
416
+ }
417
+ }
418
+ }
419
+ /**
420
+ * StorageInterface backed by `@capacitor/preferences` (native KV — iOS UserDefaults /
421
+ * Android SharedPreferences). On a device this keeps tokens out of the webview's localStorage,
422
+ * which is the right default for Capacitor apps. Lazily imports the optional
423
+ * `@capacitor/preferences` package on first use; opt in by passing an instance as `storage`
424
+ * to `auth.configure({ storage: new CapacitorPreferencesStorage() })`.
425
+ *
426
+ * NOTE: Preferences is not hardware-encrypted. For secrecy at rest, inject a Keychain/Keystore
427
+ * (e.g. a secure-storage plugin) implementation of StorageInterface instead.
428
+ */
429
+ class CapacitorPreferencesStorage {
430
+ constructor(prefix = 'cap_auth_') {
431
+ this.prefsPromise = null;
432
+ this.prefix = prefix;
433
+ }
434
+ getPrefs() {
435
+ if (!this.prefsPromise) {
436
+ this.prefsPromise = import('@capacitor/preferences').then((m) => m.Preferences);
261
437
  }
438
+ return this.prefsPromise;
439
+ }
440
+ async get(key) {
441
+ const prefs = await this.getPrefs();
442
+ const { value } = await prefs.get({ key: this.prefix + key });
443
+ if (value === null || value === undefined) {
444
+ return null;
445
+ }
446
+ try {
447
+ return JSON.parse(value);
448
+ }
449
+ catch (_a) {
450
+ return value;
451
+ }
452
+ }
453
+ async set(key, value) {
454
+ const prefs = await this.getPrefs();
455
+ const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
456
+ await prefs.set({ key: this.prefix + key, value: stringValue });
457
+ }
458
+ async remove(key) {
459
+ const prefs = await this.getPrefs();
460
+ await prefs.remove({ key: this.prefix + key });
461
+ }
462
+ async clear() {
463
+ const prefs = await this.getPrefs();
464
+ const { keys } = await prefs.keys();
465
+ await Promise.all(keys
466
+ .filter((k) => k.startsWith(this.prefix))
467
+ .map((k) => prefs.remove({ key: k })));
262
468
  }
263
469
  }
264
470
  class InMemoryStorage {
@@ -292,11 +498,36 @@ var CapacitorAuthManager = (function (exports, core) {
292
498
  this.name = 'AuthError';
293
499
  this.code = code;
294
500
  this.provider = provider;
295
- this.details = details;
296
- // Maintains proper stack trace for where our error was thrown (only available on V8)
297
- if (Error.captureStackTrace) {
298
- Error.captureStackTrace(this, AuthError);
501
+ this.details = AuthError.sanitizeDetails(details);
502
+ // Maintains proper stack trace for where our error was thrown (only available on V8 engines:
503
+ // Node.js and Chromium). Typed locally so the package does not depend on @types/node globals.
504
+ const ErrorCtor = Error;
505
+ if (ErrorCtor.captureStackTrace) {
506
+ ErrorCtor.captureStackTrace(this, AuthError);
507
+ }
508
+ }
509
+ /**
510
+ * Produces a safe, shallow `details` object: redacts sensitive keys and keeps only JSON-safe
511
+ * primitives. Prevents tokens/PII embedded in a raw error or token-endpoint response body from
512
+ * being captured into AuthError.details (and thus logged or serialized via toJSON()).
513
+ */
514
+ static sanitizeDetails(input) {
515
+ if (input === null || typeof input !== 'object') {
516
+ return undefined;
517
+ }
518
+ const out = {};
519
+ for (const [key, value] of Object.entries(input)) {
520
+ if (AuthError.SENSITIVE_KEY.test(key)) {
521
+ out[key] = '[redacted]';
522
+ }
523
+ else if (value === null ||
524
+ typeof value === 'string' ||
525
+ typeof value === 'number' ||
526
+ typeof value === 'boolean') {
527
+ out[key] = value;
528
+ }
299
529
  }
530
+ return Object.keys(out).length > 0 ? out : undefined;
300
531
  }
301
532
  static fromError(error, provider) {
302
533
  if (error instanceof AuthError) {
@@ -304,7 +535,7 @@ var CapacitorAuthManager = (function (exports, core) {
304
535
  }
305
536
  let code = exports.AuthErrorCode.INTERNAL_ERROR;
306
537
  let message = 'An unknown error occurred';
307
- let details = error;
538
+ const details = error;
308
539
  if (error instanceof Error) {
309
540
  message = error.message;
310
541
  // Try to map common error patterns to specific error codes
@@ -339,6 +570,7 @@ var CapacitorAuthManager = (function (exports, core) {
339
570
  };
340
571
  }
341
572
  }
573
+ AuthError.SENSITIVE_KEY = /(token|secret|password|authorization|code_verifier|client_secret|credential|api[-_]?key|cookie)/i;
342
574
  function isAuthError(error) {
343
575
  return (error instanceof AuthError ||
344
576
  (typeof error === 'object' &&
@@ -347,9 +579,18 @@ var CapacitorAuthManager = (function (exports, core) {
347
579
  error.code !== undefined));
348
580
  }
349
581
 
582
+ function getPlatformWindow() {
583
+ return typeof window !== 'undefined'
584
+ ? window
585
+ : undefined;
586
+ }
350
587
  class PlatformDetector {
351
588
  static getPlatform() {
352
- if (this.platformInfo) {
589
+ // A cached NON-web result is final (native/electron never reverts to web). But a cached
590
+ // 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
591
+ // module first runs (the native bridge initializes asynchronously), so re-evaluate while
592
+ // the last verdict was 'web' to pick up a late native environment. See F-26.
593
+ if (this.platformInfo && this.platformInfo.platform !== 'web') {
353
594
  return this.platformInfo;
354
595
  }
355
596
  const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
@@ -367,11 +608,21 @@ var CapacitorAuthManager = (function (exports, core) {
367
608
  };
368
609
  return this.platformInfo;
369
610
  }
611
+ /**
612
+ * Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
613
+ * result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
614
+ * initializes late). Most callers can rely on the automatic re-check while the cached value is
615
+ * still 'web'.
616
+ */
617
+ static reset() {
618
+ this.platformInfo = null;
619
+ }
370
620
  static detectPlatform(userAgent) {
371
621
  var _a, _b;
622
+ const win = getPlatformWindow();
372
623
  // Check if running in Capacitor
373
- if (typeof window !== 'undefined' && window.Capacitor) {
374
- const capacitor = window.Capacitor;
624
+ if (win === null || win === void 0 ? void 0 : win.Capacitor) {
625
+ const capacitor = win.Capacitor;
375
626
  if (capacitor.getPlatform) {
376
627
  const platform = capacitor.getPlatform();
377
628
  if (platform === 'ios' || platform === 'android') {
@@ -380,8 +631,7 @@ var CapacitorAuthManager = (function (exports, core) {
380
631
  }
381
632
  }
382
633
  // Check if running in Electron
383
- if (typeof window !== 'undefined' &&
384
- ((_b = (_a = window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron)) {
634
+ 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) {
385
635
  return 'electron';
386
636
  }
387
637
  // Check for React Native
@@ -410,124 +660,34 @@ var CapacitorAuthManager = (function (exports, core) {
410
660
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
411
661
  }
412
662
  static isCapacitorAvailable() {
413
- return typeof window !== 'undefined' && !!window.Capacitor;
663
+ var _a;
664
+ return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
414
665
  }
415
666
  static async checkCapacitorPlugin(pluginName) {
416
- if (!this.isCapacitorAvailable()) {
667
+ var _a;
668
+ const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
669
+ if (!capacitor) {
417
670
  return false;
418
671
  }
419
672
  try {
420
- const { Capacitor } = window;
421
- return !!(Capacitor.Plugins && Capacitor.Plugins[pluginName]);
673
+ return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
422
674
  }
423
- catch (_a) {
675
+ catch (_b) {
424
676
  return false;
425
677
  }
426
678
  }
427
679
  }
428
680
  PlatformDetector.platformInfo = null;
429
681
 
430
- var _a;
431
- class ProviderRegistry {
432
- static registerManifest(manifest) {
433
- this.manifests.set(manifest.name, manifest);
434
- }
435
- static registerLoader(name, loader) {
436
- this.loaders.set(name, loader);
437
- }
438
- static getManifest(name) {
439
- return this.manifests.get(name);
440
- }
441
- static async getProvider(name, config) {
442
- var _b, _c;
443
- // Check if already loaded
444
- const existing = this.providers.get(name);
445
- if (existing) {
446
- return existing;
447
- }
448
- // Check if loader exists
449
- const loader = this.loaders.get(name);
450
- if (!loader) {
451
- const manifest = this.manifests.get(name);
452
- if (manifest) {
453
- throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
454
- }
455
- throw new Error(`Unknown provider: ${name}`);
456
- }
457
- // Check platform support
458
- const manifest = this.manifests.get(name);
459
- if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
460
- const platform = PlatformDetector.getPlatform();
461
- if (!manifest.platforms.includes(platform.platform)) {
462
- throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
463
- }
464
- }
465
- try {
466
- // Load the provider
467
- const module = await loader();
468
- const ProviderClass = module.default;
469
- // Create instance
470
- const provider = new ProviderClass(config);
471
- // Initialize if needed
472
- if (provider.initialize) {
473
- await provider.initialize(config);
474
- }
475
- // Cache the provider
476
- this.providers.set(name, provider);
477
- return provider;
478
- }
479
- catch (error) {
480
- // Check if it's a missing dependency error
481
- if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot find module')) ||
482
- ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Failed to resolve module'))) {
483
- const manifest = this.manifests.get(name);
484
- if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
485
- throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
486
- `Install the required package:\n` +
487
- `npm install ${manifest.packageName}\n\n` +
488
- `Then try again.`);
489
- }
490
- }
491
- throw error;
492
- }
493
- }
494
- static clearProvider(name) {
495
- const provider = this.providers.get(name);
496
- if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
497
- provider.dispose();
498
- }
499
- this.providers.delete(name);
500
- }
501
- static clearAll() {
502
- for (const [, provider] of this.providers) {
503
- if (provider.dispose) {
504
- provider.dispose();
505
- }
506
- }
507
- this.providers.clear();
508
- }
509
- static getAvailableProviders() {
510
- return Array.from(this.manifests.keys());
511
- }
512
- static getSupportedProviders() {
513
- const platform = PlatformDetector.getPlatform();
514
- const supported = [];
515
- for (const [name, manifest] of this.manifests) {
516
- if (!manifest.platforms ||
517
- manifest.platforms.includes(platform.platform)) {
518
- supported.push(name);
519
- }
520
- }
521
- return Promise.resolve(supported);
522
- }
523
- }
524
- _a = ProviderRegistry;
525
- ProviderRegistry.providers = new Map();
526
- ProviderRegistry.loaders = new Map();
527
- ProviderRegistry.manifests = new Map();
528
- (() => {
529
- // Register built-in provider manifests
530
- _a.registerManifest({
682
+ /**
683
+ * Built-in provider manifests (display metadata + human-readable setup instructions).
684
+ *
685
+ * Extracted from `provider-registry.ts` as a pure data module (zero logic) so the registry stays
686
+ * under the project's file-size guideline. `ProviderRegistry` imports this array and registers each
687
+ * entry in its static initializer — behaviour is unchanged (see F-40).
688
+ */
689
+ const BUILT_IN_PROVIDER_MANIFESTS = [
690
+ {
531
691
  name: 'google',
532
692
  displayName: 'Google',
533
693
  packageName: '@google/gsi',
@@ -559,8 +719,8 @@ To use Google authentication, you need to:
559
719
  scopes: { type: 'array', items: 'string' },
560
720
  hostedDomain: { type: 'string' },
561
721
  },
562
- });
563
- _a.registerManifest({
722
+ },
723
+ {
564
724
  name: 'apple',
565
725
  displayName: 'Apple',
566
726
  setupInstructions: `
@@ -588,8 +748,8 @@ To use Apple authentication:
588
748
  redirectUri: { type: 'string', required: true },
589
749
  scopes: { type: 'array', items: 'string' },
590
750
  },
591
- });
592
- _a.registerManifest({
751
+ },
752
+ {
593
753
  name: 'firebase',
594
754
  displayName: 'Firebase Auth',
595
755
  packageName: 'firebase',
@@ -623,8 +783,8 @@ To use Firebase authentication:
623
783
  authDomain: { type: 'string', required: true },
624
784
  projectId: { type: 'string', required: true },
625
785
  },
626
- });
627
- _a.registerManifest({
786
+ },
787
+ {
628
788
  name: 'microsoft',
629
789
  displayName: 'Microsoft',
630
790
  packageName: '@azure/msal-browser',
@@ -658,8 +818,8 @@ To use Microsoft authentication:
658
818
  redirectUri: { type: 'string' },
659
819
  scopes: { type: 'array', items: 'string' },
660
820
  },
661
- });
662
- _a.registerManifest({
821
+ },
822
+ {
663
823
  name: 'facebook',
664
824
  displayName: 'Facebook',
665
825
  setupInstructions: `
@@ -672,7 +832,7 @@ To use Facebook authentication:
672
832
  - Configure OAuth redirect URIs
673
833
 
674
834
  2. Add Facebook SDK to your HTML:
675
- <script async defer crossorigin="anonymous"
835
+ <script async defer crossorigin="anonymous"
676
836
  src="https://connect.facebook.net/en_US/sdk.js"></script>
677
837
 
678
838
  3. Configure the provider:
@@ -691,8 +851,8 @@ To use Facebook authentication:
691
851
  version: { type: 'string' },
692
852
  scopes: { type: 'array', items: 'string' },
693
853
  },
694
- });
695
- _a.registerManifest({
854
+ },
855
+ {
696
856
  name: 'github',
697
857
  displayName: 'GitHub',
698
858
  setupInstructions: `
@@ -721,9 +881,8 @@ Note: You'll need a backend service to exchange the authorization code for an ac
721
881
  redirectUri: { type: 'string' },
722
882
  scopes: { type: 'array', items: 'string' },
723
883
  },
724
- });
725
- // Register all new provider manifests
726
- _a.registerManifest({
884
+ },
885
+ {
727
886
  name: 'magic-link',
728
887
  displayName: 'Email Magic Link',
729
888
  setupInstructions: `
@@ -750,8 +909,8 @@ To use Email Magic Link authentication:
750
909
  verifyUrl: { type: 'string' },
751
910
  redirectUrl: { type: 'string' },
752
911
  },
753
- });
754
- _a.registerManifest({
912
+ },
913
+ {
755
914
  name: 'sms',
756
915
  displayName: 'SMS Authentication',
757
916
  setupInstructions: `
@@ -780,8 +939,8 @@ To use SMS authentication:
780
939
  countryCode: { type: 'string' },
781
940
  codeLength: { type: 'number' },
782
941
  },
783
- });
784
- _a.registerManifest({
942
+ },
943
+ {
785
944
  name: 'email-password',
786
945
  displayName: 'Email & Password',
787
946
  setupInstructions: `
@@ -808,8 +967,8 @@ To use Email/Password authentication:
808
967
  apiUrl: { type: 'string', required: true },
809
968
  passwordRequirements: { type: 'object' },
810
969
  },
811
- });
812
- _a.registerManifest({
970
+ },
971
+ {
813
972
  name: 'biometric',
814
973
  displayName: 'Biometric Authentication',
815
974
  packageName: 'capacitor-biometric-authentication',
@@ -838,8 +997,8 @@ Note: Users must first authenticate with another method before enabling biometri
838
997
  title: { type: 'string' },
839
998
  subtitle: { type: 'string' },
840
999
  },
841
- });
842
- _a.registerManifest({
1000
+ },
1001
+ {
843
1002
  name: 'slack',
844
1003
  displayName: 'Slack',
845
1004
  setupInstructions: `
@@ -882,8 +1041,8 @@ Note: Slack OAuth requires a backend service to exchange the authorization code
882
1041
  scopes: { type: 'array', items: 'string' },
883
1042
  teamId: { type: 'string' },
884
1043
  },
885
- });
886
- _a.registerManifest({
1044
+ },
1045
+ {
887
1046
  name: 'linkedin',
888
1047
  displayName: 'LinkedIn',
889
1048
  setupInstructions: `
@@ -927,8 +1086,8 @@ The redirect URI must be HTTPS in production (LinkedIn requirement).
927
1086
  redirectUri: { type: 'string', required: true },
928
1087
  scopes: { type: 'array', items: 'string' },
929
1088
  },
930
- });
931
- _a.registerManifest({
1089
+ },
1090
+ {
932
1091
  name: 'username-password',
933
1092
  displayName: 'Username & Password',
934
1093
  setupInstructions: `
@@ -988,79 +1147,255 @@ Note: This provider requires a backend service to handle authentication.
988
1147
  passwordRequirements: { type: 'object' },
989
1148
  allowSignUp: { type: 'boolean' },
990
1149
  },
991
- });
992
- // Register provider loaders
993
- _a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
994
- default: m.GoogleAuthProviderWeb,
995
- })));
996
- _a.registerLoader('apple', () => Promise.resolve().then(function () { return appleProvider; }).then((m) => ({
997
- default: m.AppleAuthProviderWeb,
998
- })));
999
- _a.registerLoader('microsoft', () => Promise.resolve().then(function () { return microsoftProvider; }).then((m) => ({
1000
- default: m.MicrosoftAuthProviderWeb,
1001
- })));
1002
- _a.registerLoader('facebook', () => Promise.resolve().then(function () { return facebookProvider; }).then((m) => ({
1003
- default: m.FacebookAuthProviderWeb,
1004
- })));
1005
- _a.registerLoader('github', () => Promise.resolve().then(function () { return githubProvider; }).then((m) => ({
1006
- default: m.GitHubAuthProviderWeb,
1007
- })));
1008
- _a.registerLoader('firebase', () => Promise.resolve().then(function () { return firebaseProvider; }).then((m) => ({
1009
- default: m.FirebaseAuthProviderWeb,
1010
- })));
1011
- _a.registerLoader('magic-link', () => Promise.resolve().then(function () { return magicLinkProvider; }).then((m) => ({
1012
- default: m.MagicLinkProvider,
1013
- })));
1014
- _a.registerLoader('sms', () => Promise.resolve().then(function () { return smsProvider; }).then((m) => ({
1015
- default: m.SMSProvider,
1016
- })));
1017
- _a.registerLoader('email-password', () => Promise.resolve().then(function () { return emailPasswordProvider; }).then((m) => ({
1018
- default: m.EmailPasswordProvider,
1019
- })));
1020
- _a.registerLoader('biometric', () => Promise.resolve().then(function () { return biometricProvider; }).then((m) => ({
1021
- default: m.BiometricProvider,
1022
- })));
1023
- _a.registerLoader('slack', () => Promise.resolve().then(function () { return slackProvider; }).then((m) => ({
1024
- default: m.SlackProvider,
1025
- })));
1026
- _a.registerLoader('linkedin', () => Promise.resolve().then(function () { return linkedinProvider; }).then((m) => ({
1027
- default: m.LinkedInProvider,
1028
- })));
1029
- _a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
1030
- default: m.UsernamePasswordProvider,
1031
- })));
1032
- })();
1150
+ },
1151
+ ];
1033
1152
 
1034
- class AuthManagerCore {
1035
- constructor() {
1036
- this.state = {
1037
- user: null,
1038
- isLoading: false,
1039
- isAuthenticated: false,
1040
- provider: null,
1041
- };
1042
- this.stateEmitter = new EventEmitter();
1043
- this.config = {};
1044
- this.isInitialized = false;
1045
- this.tokenRefreshTimers = new Map();
1046
- this.storage = new WebStorage('local');
1047
- this.logger = new Logger({
1048
- enableLogging: false,
1049
- logLevel: 'info',
1050
- prefix: 'AuthManager',
1051
- });
1052
- // Auto-initialize on first use
1053
- if (typeof window !== 'undefined') {
1054
- this.initialize().catch((err) => {
1055
- this.logger.error('Auto-initialization failed:', err);
1056
- });
1057
- }
1153
+ var _a;
1154
+ class ProviderRegistry {
1155
+ static registerManifest(manifest) {
1156
+ this.manifests.set(manifest.name, manifest);
1058
1157
  }
1059
- async initialize(config) {
1060
- if (this.isInitialized && !config) {
1061
- return;
1062
- }
1063
- if (config) {
1158
+ static registerLoader(name, loader) {
1159
+ this.loaders.set(name, loader);
1160
+ }
1161
+ static getManifest(name) {
1162
+ return this.manifests.get(name);
1163
+ }
1164
+ static canonicalName(name) {
1165
+ var _b;
1166
+ return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
1167
+ }
1168
+ static async getProvider(name, options, deps) {
1169
+ var _b, _c, _d, _e;
1170
+ const key = this.canonicalName(name);
1171
+ // Check if already loaded
1172
+ const existing = this.providers.get(key);
1173
+ if (existing) {
1174
+ return existing;
1175
+ }
1176
+ // Check if loader exists
1177
+ const loader = this.loaders.get(key);
1178
+ if (!loader) {
1179
+ const manifest = this.manifests.get(key);
1180
+ if (manifest) {
1181
+ throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
1182
+ }
1183
+ throw new Error(`Unknown provider: ${name}`);
1184
+ }
1185
+ // Check platform support
1186
+ const manifest = this.manifests.get(key);
1187
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
1188
+ const platform = PlatformDetector.getPlatform();
1189
+ if (!manifest.platforms.includes(platform.platform)) {
1190
+ throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
1191
+ }
1192
+ }
1193
+ try {
1194
+ // Load the provider class
1195
+ const module = await loader();
1196
+ const ProviderClass = module.default;
1197
+ // Build the constructor argument. BaseAuthProvider subclasses need a full
1198
+ // BaseProviderConfig ({ provider, options, storage, logger, persistence });
1199
+ // standalone providers take their options object directly.
1200
+ const storage = (_b = deps === null || deps === void 0 ? void 0 : deps.storage) !== null && _b !== void 0 ? _b : new WebStorage(exports.AuthPersistence.LOCAL);
1201
+ const logger = (_c = deps === null || deps === void 0 ? void 0 : deps.logger) !== null && _c !== void 0 ? _c : new Logger({
1202
+ enableLogging: false,
1203
+ logLevel: 'warn',
1204
+ prefix: 'AuthManager',
1205
+ });
1206
+ const constructorArg = this.STANDALONE_PROVIDERS.has(key)
1207
+ ? (options !== null && options !== void 0 ? options : {})
1208
+ : {
1209
+ provider: key,
1210
+ options: (options !== null && options !== void 0 ? options : {}),
1211
+ storage,
1212
+ logger,
1213
+ persistence: deps === null || deps === void 0 ? void 0 : deps.persistence,
1214
+ };
1215
+ // Create instance
1216
+ const provider = new ProviderClass(constructorArg);
1217
+ // Initialize if supported (BaseAuthProvider.initialize takes no arguments)
1218
+ if (provider.initialize) {
1219
+ await provider.initialize();
1220
+ }
1221
+ // Cache the provider under its canonical key
1222
+ this.providers.set(key, provider);
1223
+ return provider;
1224
+ }
1225
+ catch (error) {
1226
+ // Check if it's a missing dependency error
1227
+ if (((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot find module')) ||
1228
+ ((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to resolve module'))) {
1229
+ const manifest = this.manifests.get(this.canonicalName(name));
1230
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
1231
+ throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
1232
+ `Install the required package:\n` +
1233
+ `npm install ${manifest.packageName}\n\n` +
1234
+ `Then try again.`);
1235
+ }
1236
+ }
1237
+ throw error;
1238
+ }
1239
+ }
1240
+ static clearProvider(name) {
1241
+ const key = this.canonicalName(name);
1242
+ const provider = this.providers.get(key);
1243
+ if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
1244
+ provider.dispose();
1245
+ }
1246
+ this.providers.delete(key);
1247
+ }
1248
+ static clearAll() {
1249
+ for (const [, provider] of this.providers) {
1250
+ if (provider.dispose) {
1251
+ provider.dispose();
1252
+ }
1253
+ }
1254
+ this.providers.clear();
1255
+ }
1256
+ static getAvailableProviders() {
1257
+ return Array.from(this.manifests.keys());
1258
+ }
1259
+ static getSupportedProviders() {
1260
+ const platform = PlatformDetector.getPlatform();
1261
+ const supported = [];
1262
+ for (const [name, manifest] of this.manifests) {
1263
+ if (!manifest.platforms ||
1264
+ manifest.platforms.includes(platform.platform)) {
1265
+ supported.push(name);
1266
+ }
1267
+ }
1268
+ return Promise.resolve(supported);
1269
+ }
1270
+ }
1271
+ _a = ProviderRegistry;
1272
+ ProviderRegistry.providers = new Map();
1273
+ ProviderRegistry.loaders = new Map();
1274
+ ProviderRegistry.manifests = new Map();
1275
+ /** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
1276
+ ProviderRegistry.STANDALONE_PROVIDERS = new Set([
1277
+ 'magic-link',
1278
+ 'sms',
1279
+ 'email-password',
1280
+ 'username-password',
1281
+ 'biometric',
1282
+ 'phone-password',
1283
+ 'email-code',
1284
+ ]);
1285
+ /** Maps AuthProvider enum values (some underscored) to the registered hyphenated loader keys. */
1286
+ ProviderRegistry.NAME_ALIASES = {
1287
+ email_magic_link: 'magic-link',
1288
+ username_password: 'username-password',
1289
+ phone_password: 'phone-password',
1290
+ email_code: 'email-code',
1291
+ };
1292
+ (() => {
1293
+ // Register built-in provider manifests (data lives in provider-manifests.ts — F-40).
1294
+ for (const manifest of BUILT_IN_PROVIDER_MANIFESTS) {
1295
+ _a.registerManifest(manifest);
1296
+ }
1297
+ // Register provider loaders
1298
+ _a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
1299
+ default: m.GoogleAuthProviderWeb,
1300
+ })));
1301
+ _a.registerLoader('apple', () => Promise.resolve().then(function () { return appleProvider; }).then((m) => ({
1302
+ default: m.AppleAuthProviderWeb,
1303
+ })));
1304
+ _a.registerLoader('microsoft', () => Promise.resolve().then(function () { return microsoftProvider; }).then((m) => ({
1305
+ default: m.MicrosoftAuthProviderWeb,
1306
+ })));
1307
+ _a.registerLoader('facebook', () => Promise.resolve().then(function () { return facebookProvider; }).then((m) => ({
1308
+ default: m.FacebookAuthProviderWeb,
1309
+ })));
1310
+ _a.registerLoader('github', () => Promise.resolve().then(function () { return githubProvider; }).then((m) => ({
1311
+ default: m.GitHubAuthProviderWeb,
1312
+ })));
1313
+ _a.registerLoader('firebase', () => Promise.resolve().then(function () { return firebaseProvider; }).then((m) => ({
1314
+ default: m.FirebaseAuthProviderWeb,
1315
+ })));
1316
+ _a.registerLoader('magic-link', () => Promise.resolve().then(function () { return magicLinkProvider; }).then((m) => ({
1317
+ default: m.MagicLinkProvider,
1318
+ })));
1319
+ _a.registerLoader('sms', () => Promise.resolve().then(function () { return smsProvider; }).then((m) => ({
1320
+ default: m.SMSProvider,
1321
+ })));
1322
+ _a.registerLoader('email-password', () => Promise.resolve().then(function () { return emailPasswordProvider; }).then((m) => ({
1323
+ default: m.EmailPasswordProvider,
1324
+ })));
1325
+ _a.registerLoader('biometric', () => Promise.resolve().then(function () { return biometricProvider; }).then((m) => ({
1326
+ default: m.BiometricProvider,
1327
+ })));
1328
+ _a.registerLoader('slack', () => Promise.resolve().then(function () { return slackProvider; }).then((m) => ({
1329
+ default: m.SlackProvider,
1330
+ })));
1331
+ _a.registerLoader('linkedin', () => Promise.resolve().then(function () { return linkedinProvider; }).then((m) => ({
1332
+ default: m.LinkedInProvider,
1333
+ })));
1334
+ _a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
1335
+ default: m.UsernamePasswordProvider,
1336
+ })));
1337
+ _a.registerLoader('email-code', () => Promise.resolve().then(function () { return emailCodeProvider; }).then((m) => ({
1338
+ default: m.EmailCodeProvider,
1339
+ })));
1340
+ _a.registerLoader('phone-password', () => Promise.resolve().then(function () { return phonePasswordProvider; }).then((m) => ({
1341
+ default: m.PhonePasswordProvider,
1342
+ })));
1343
+ })();
1344
+
1345
+ /**
1346
+ * Maps the config's persistence literal to the {@link AuthPersistence} enum WebStorage expects.
1347
+ * Critically, `'memory'` maps to {@link AuthPersistence.NONE} (`'none'`) — previously the literal
1348
+ * was cast via `as any` and fell through WebStorage's switch to localStorage, silently breaking
1349
+ * in-memory persistence.
1350
+ */
1351
+ function toAuthPersistence(persistence) {
1352
+ switch (persistence) {
1353
+ case 'session':
1354
+ return exports.AuthPersistence.SESSION;
1355
+ case 'memory':
1356
+ return exports.AuthPersistence.NONE;
1357
+ case 'local':
1358
+ default:
1359
+ return exports.AuthPersistence.LOCAL;
1360
+ }
1361
+ }
1362
+ class AuthManagerCore {
1363
+ constructor() {
1364
+ this.state = {
1365
+ user: null,
1366
+ isLoading: false,
1367
+ isAuthenticated: false,
1368
+ provider: null,
1369
+ };
1370
+ this.stateEmitter = new EventEmitter();
1371
+ this.config = {};
1372
+ this.isInitialized = false;
1373
+ this.tokenRefreshTimers = new Map();
1374
+ this.initPromise = null;
1375
+ this.logger = new Logger({
1376
+ enableLogging: false,
1377
+ logLevel: 'info',
1378
+ prefix: 'AuthManager',
1379
+ });
1380
+ this.storage = new WebStorage(exports.AuthPersistence.LOCAL, undefined, this.logger);
1381
+ this.currentPersistence = 'local';
1382
+ // Auto-initialize on first use
1383
+ if (typeof window !== 'undefined') {
1384
+ this.initialize().catch((err) => {
1385
+ this.logger.error('Auto-initialization failed:', err);
1386
+ });
1387
+ }
1388
+ }
1389
+ async initialize(config) {
1390
+ if (this.isInitialized && !config) {
1391
+ return;
1392
+ }
1393
+ // Coalesce concurrent first-time initialization (e.g. the constructor's auto-init
1394
+ // racing with an explicit initialize()) so restoreAuthState does not run twice.
1395
+ if (this.initPromise && !config) {
1396
+ return this.initPromise;
1397
+ }
1398
+ if (config) {
1064
1399
  this.config = Object.assign(Object.assign({}, this.config), config);
1065
1400
  }
1066
1401
  // Configure logger
@@ -1070,12 +1405,21 @@ Note: This provider requires a backend service to handle authentication.
1070
1405
  if (this.config.logLevel) {
1071
1406
  this.logger.setLogLevel(this.config.logLevel);
1072
1407
  }
1073
- // Configure persistence
1074
- if (this.config.persistence) {
1075
- this.storage = new WebStorage(this.config.persistence);
1408
+ // A custom storage backend (e.g. secure native storage) takes precedence. Otherwise only
1409
+ // recreate storage when persistence actually changes (don't discard in-memory state on a
1410
+ // no-op re-initialize).
1411
+ if (this.config.storage) {
1412
+ this.storage = this.config.storage;
1413
+ this.currentPersistence = 'custom';
1414
+ }
1415
+ else if (this.config.persistence &&
1416
+ this.config.persistence !== this.currentPersistence) {
1417
+ this.storage = new WebStorage(toAuthPersistence(this.config.persistence), undefined, this.logger);
1418
+ this.currentPersistence = this.config.persistence;
1076
1419
  }
1077
1420
  // Restore auth state
1078
- await this.restoreAuthState();
1421
+ this.initPromise = this.restoreAuthState();
1422
+ await this.initPromise;
1079
1423
  this.isInitialized = true;
1080
1424
  this.logger.info('Auth manager initialized');
1081
1425
  }
@@ -1087,12 +1431,23 @@ Note: This provider requires a backend service to handle authentication.
1087
1431
  if (config.logLevel) {
1088
1432
  this.logger.setLogLevel(config.logLevel);
1089
1433
  }
1090
- if (config.persistence) {
1091
- this.storage = new WebStorage(config.persistence);
1434
+ if (config.storage) {
1435
+ this.storage = config.storage;
1436
+ this.currentPersistence = 'custom';
1437
+ }
1438
+ else if (config.persistence &&
1439
+ config.persistence !== this.currentPersistence) {
1440
+ this.storage = new WebStorage(toAuthPersistence(config.persistence), undefined, this.logger);
1441
+ this.currentPersistence = config.persistence;
1442
+ }
1443
+ // Now that providers may be configured, (re)attempt session restore so a persisted
1444
+ // session is rehydrated even when the singleton auto-initialized before configure().
1445
+ if (config.providers && Object.keys(config.providers).length > 0) {
1446
+ void this.restoreAuthState();
1092
1447
  }
1093
1448
  }
1094
1449
  async signIn(providerOrOptions) {
1095
- var _a;
1450
+ var _a, _b, _c;
1096
1451
  await this.ensureInitialized();
1097
1452
  let providerName;
1098
1453
  let signInOptions = {};
@@ -1118,10 +1473,12 @@ Note: This provider requires a backend service to handle authentication.
1118
1473
  throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
1119
1474
  }
1120
1475
  // Get provider instance
1121
- const provider = await ProviderRegistry.getProvider(providerName, providerConfig);
1122
- // Sign in
1476
+ const provider = await ProviderRegistry.getProvider(providerName, providerConfig, this.getProviderDeps());
1477
+ // Sign in. Credentials are spread to the top level (where credential providers read
1478
+ // email/password/phoneNumber/username) AND kept nested under `credentials` for
1479
+ // providers that read them there.
1123
1480
  this.logger.info(`Signing in with ${providerName}`);
1124
- const result = await provider.signIn(Object.assign(Object.assign({}, signInOptions.options), { credentials: signInOptions.credentials }));
1481
+ const result = await provider.signIn(Object.assign(Object.assign(Object.assign({}, signInOptions.options), ((_b = signInOptions.credentials) !== null && _b !== void 0 ? _b : {})), { credentials: signInOptions.credentials }));
1125
1482
  // Update state
1126
1483
  this.updateState({
1127
1484
  user: result.user,
@@ -1136,7 +1493,7 @@ Note: This provider requires a backend service to handle authentication.
1136
1493
  credential: result.credential,
1137
1494
  });
1138
1495
  // Setup token refresh
1139
- if (this.config.autoRefreshToken && result.credential.refreshToken) {
1496
+ if (this.config.autoRefreshToken && ((_c = result.credential) === null || _c === void 0 ? void 0 : _c.refreshToken)) {
1140
1497
  this.setupTokenRefresh(providerName, result.credential);
1141
1498
  }
1142
1499
  return result;
@@ -1159,11 +1516,17 @@ Note: This provider requires a backend service to handle authentication.
1159
1516
  try {
1160
1517
  // Get provider instance
1161
1518
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
1162
- const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig);
1519
+ const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig, this.getProviderDeps());
1163
1520
  // Sign out
1164
1521
  await providerInstance.signOut(options);
1165
- // Clear token refresh
1166
- this.clearTokenRefresh(provider);
1522
+ // Clear token refresh. When no specific provider was targeted, clear ALL refresh timers
1523
+ // (not just the active provider's) so a global sign-out leaves no orphaned timers behind.
1524
+ if (options === null || options === void 0 ? void 0 : options.provider) {
1525
+ this.clearTokenRefresh(provider);
1526
+ }
1527
+ else {
1528
+ this.clearAllTokenRefresh();
1529
+ }
1167
1530
  // Clear state
1168
1531
  this.updateState({
1169
1532
  user: null,
@@ -1194,7 +1557,7 @@ Note: This provider requires a backend service to handle authentication.
1194
1557
  return this.state.provider;
1195
1558
  }
1196
1559
  async refreshToken(provider) {
1197
- var _a;
1560
+ var _a, _b;
1198
1561
  await this.ensureInitialized();
1199
1562
  const targetProvider = provider || this.state.provider;
1200
1563
  if (!targetProvider) {
@@ -1202,7 +1565,7 @@ Note: This provider requires a backend service to handle authentication.
1202
1565
  }
1203
1566
  try {
1204
1567
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
1205
- const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig);
1568
+ const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig, this.getProviderDeps());
1206
1569
  if (!providerInstance.refreshToken) {
1207
1570
  throw new AuthError('auth/operation-not-supported', `Provider '${targetProvider}' does not support token refresh`);
1208
1571
  }
@@ -1210,7 +1573,7 @@ Note: This provider requires a backend service to handle authentication.
1210
1573
  // Update user
1211
1574
  this.updateState({ user: result.user });
1212
1575
  // Setup new token refresh
1213
- if (this.config.autoRefreshToken && result.credential.refreshToken) {
1576
+ if (this.config.autoRefreshToken && ((_b = result.credential) === null || _b === void 0 ? void 0 : _b.refreshToken)) {
1214
1577
  this.setupTokenRefresh(targetProvider, result.credential);
1215
1578
  }
1216
1579
  return result;
@@ -1220,6 +1583,177 @@ Note: This provider requires a backend service to handle authentication.
1220
1583
  throw AuthError.fromError(error);
1221
1584
  }
1222
1585
  }
1586
+ /**
1587
+ * Links an additional auth credential to the current account, delegating to the resolved
1588
+ * provider's optional `linkAccount`. Throws `OPERATION_NOT_ALLOWED` if the provider doesn't
1589
+ * implement it. Mirrors `CapacitorAuthManagerWeb.linkAccount` so React/Vue/Angular consumers
1590
+ * reach the same capability through the `auth` singleton.
1591
+ */
1592
+ async linkAccount(options) {
1593
+ await this.ensureInitialized();
1594
+ const providerName = typeof options.provider === 'string'
1595
+ ? options.provider
1596
+ : exports.AuthProvider[options.provider];
1597
+ const provider = await this.resolveProvider(providerName);
1598
+ if (typeof provider.linkAccount !== 'function') {
1599
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `linkAccount not supported for ${providerName}`);
1600
+ }
1601
+ try {
1602
+ const result = await provider.linkAccount(options);
1603
+ this.updateState({ user: result.user });
1604
+ return result;
1605
+ }
1606
+ catch (error) {
1607
+ this.logger.error(`Account linking failed for ${providerName}`, error);
1608
+ throw AuthError.fromError(error);
1609
+ }
1610
+ }
1611
+ /**
1612
+ * Unlinks a provider credential from the current account via the resolved provider's optional
1613
+ * `unlinkAccount`. Throws `OPERATION_NOT_ALLOWED` if unsupported.
1614
+ */
1615
+ async unlinkAccount(options) {
1616
+ await this.ensureInitialized();
1617
+ const providerName = typeof options.provider === 'string'
1618
+ ? options.provider
1619
+ : exports.AuthProvider[options.provider];
1620
+ const provider = await this.resolveProvider(providerName);
1621
+ if (typeof provider.unlinkAccount !== 'function') {
1622
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `unlinkAccount not supported for ${providerName}`);
1623
+ }
1624
+ try {
1625
+ await provider.unlinkAccount(options);
1626
+ }
1627
+ catch (error) {
1628
+ this.logger.error(`Account unlinking failed for ${providerName}`, error);
1629
+ throw AuthError.fromError(error);
1630
+ }
1631
+ }
1632
+ /**
1633
+ * Revokes the access/refresh token for a provider (current provider when `provider` is omitted),
1634
+ * delegating to the provider's optional `revokeAccess`. Throws `OPERATION_NOT_ALLOWED` if
1635
+ * unsupported.
1636
+ */
1637
+ async revokeAccess(token, provider) {
1638
+ await this.ensureInitialized();
1639
+ const targetProvider = provider || this.state.provider;
1640
+ if (!targetProvider) {
1641
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to revoke access for');
1642
+ }
1643
+ const providerInstance = await this.resolveProvider(targetProvider);
1644
+ if (typeof providerInstance.revokeAccess !== 'function') {
1645
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `revokeAccess not supported for ${targetProvider}`);
1646
+ }
1647
+ try {
1648
+ await providerInstance.revokeAccess(token);
1649
+ }
1650
+ catch (error) {
1651
+ this.logger.error(`Access revocation failed for ${targetProvider}`, error);
1652
+ throw AuthError.fromError(error);
1653
+ }
1654
+ }
1655
+ /**
1656
+ * Returns the current ID token for a provider (current provider when `provider` is omitted) by
1657
+ * delegating to the provider's optional `getIdToken`. Throws `OPERATION_NOT_ALLOWED` if the
1658
+ * provider doesn't issue/expose ID tokens.
1659
+ */
1660
+ async getIdToken(options) {
1661
+ var _a;
1662
+ await this.ensureInitialized();
1663
+ const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1664
+ ? typeof options.provider === 'string'
1665
+ ? options.provider
1666
+ : exports.AuthProvider[options.provider]
1667
+ : undefined) || this.state.provider;
1668
+ if (!targetProvider) {
1669
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to get an ID token for');
1670
+ }
1671
+ const provider = await this.resolveProvider(targetProvider);
1672
+ const getIdTokenFn = provider.getIdToken;
1673
+ if (typeof getIdTokenFn !== 'function') {
1674
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `getIdToken not supported for ${targetProvider}`);
1675
+ }
1676
+ try {
1677
+ return await getIdTokenFn.call(provider, (_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
1678
+ }
1679
+ catch (error) {
1680
+ this.logger.error(`getIdToken failed for ${targetProvider}`, error);
1681
+ throw AuthError.fromError(error);
1682
+ }
1683
+ }
1684
+ /**
1685
+ * Updates the signed-in user's profile via the current provider's optional `updateProfile`.
1686
+ * Throws `OPERATION_NOT_ALLOWED` if the provider doesn't implement it.
1687
+ */
1688
+ async updateProfile(options) {
1689
+ await this.ensureInitialized();
1690
+ const targetProvider = this.state.provider;
1691
+ if (!targetProvider) {
1692
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
1693
+ }
1694
+ const provider = await this.resolveProvider(targetProvider);
1695
+ const updateFn = provider.updateProfile;
1696
+ if (typeof updateFn !== 'function') {
1697
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `updateProfile not supported for ${targetProvider}`);
1698
+ }
1699
+ try {
1700
+ const updatedUser = await updateFn.call(provider, options);
1701
+ this.updateState({ user: updatedUser });
1702
+ return updatedUser;
1703
+ }
1704
+ catch (error) {
1705
+ this.logger.error(`updateProfile failed for ${targetProvider}`, error);
1706
+ throw AuthError.fromError(error);
1707
+ }
1708
+ }
1709
+ /**
1710
+ * Deletes the current account via the provider's optional `deleteAccount` (current provider when
1711
+ * `provider` is omitted), then clears local state. Throws `OPERATION_NOT_ALLOWED` if the provider
1712
+ * doesn't implement it.
1713
+ */
1714
+ async deleteAccount(options) {
1715
+ await this.ensureInitialized();
1716
+ const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1717
+ ? typeof options.provider === 'string'
1718
+ ? options.provider
1719
+ : exports.AuthProvider[options.provider]
1720
+ : undefined) || this.state.provider;
1721
+ if (!targetProvider) {
1722
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
1723
+ }
1724
+ const provider = await this.resolveProvider(targetProvider);
1725
+ const deleteFn = provider.deleteAccount;
1726
+ if (typeof deleteFn !== 'function') {
1727
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
1728
+ }
1729
+ try {
1730
+ await deleteFn.call(provider);
1731
+ // Account deleted server-side: clear local session + timers.
1732
+ this.clearTokenRefresh(targetProvider);
1733
+ this.updateState({
1734
+ user: null,
1735
+ isAuthenticated: false,
1736
+ provider: null,
1737
+ });
1738
+ await this.storage.remove('auth_state');
1739
+ }
1740
+ catch (error) {
1741
+ this.logger.error(`deleteAccount failed for ${targetProvider}`, error);
1742
+ throw AuthError.fromError(error);
1743
+ }
1744
+ }
1745
+ /**
1746
+ * Whether a provider has been supplied to `configure()`/`initialize()`. Public accessor so
1747
+ * adapters (React/Vue/Angular) no longer reach into the private `config` via `as any`.
1748
+ */
1749
+ isProviderConfigured(name) {
1750
+ var _a;
1751
+ return !!((_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name]);
1752
+ }
1753
+ /** Names of every provider supplied to `configure()`/`initialize()`. */
1754
+ getConfiguredProviders() {
1755
+ return this.config.providers ? Object.keys(this.config.providers) : [];
1756
+ }
1223
1757
  onAuthStateChange(listener) {
1224
1758
  // Immediately call with current state
1225
1759
  listener(this.getAuthState());
@@ -1241,6 +1775,18 @@ Note: This provider requires a backend service to handle authentication.
1241
1775
  await this.initialize();
1242
1776
  }
1243
1777
  }
1778
+ getProviderDeps() {
1779
+ return { storage: this.storage, logger: this.logger };
1780
+ }
1781
+ /**
1782
+ * Resolves a provider instance through the registry, threading the configured options and the
1783
+ * manager's shared storage/logger. Shared by the capability methods (link/unlink/revoke/
1784
+ * getIdToken/updateProfile/deleteAccount).
1785
+ */
1786
+ async resolveProvider(name) {
1787
+ var _a;
1788
+ return ProviderRegistry.getProvider(name, (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name], this.getProviderDeps());
1789
+ }
1244
1790
  updateState(partial) {
1245
1791
  this.state = Object.assign(Object.assign({}, this.state), partial);
1246
1792
  this.stateEmitter.emit(this.state);
@@ -1254,7 +1800,7 @@ Note: This provider requires a backend service to handle authentication.
1254
1800
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
1255
1801
  if (providerConfig) {
1256
1802
  try {
1257
- const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig);
1803
+ const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
1258
1804
  const currentUser = await provider.getCurrentUser();
1259
1805
  if (currentUser) {
1260
1806
  this.updateState({
@@ -1288,16 +1834,35 @@ Note: This provider requires a backend service to handle authentication.
1288
1834
  const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
1289
1835
  const refreshTime = credential.expiresAt - buffer - Date.now();
1290
1836
  if (refreshTime > 0) {
1291
- const timer = setTimeout(async () => {
1837
+ this.scheduleRefresh(provider, refreshTime, credential);
1838
+ }
1839
+ }
1840
+ /**
1841
+ * Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
1842
+ * (2,147,483,647 ms ≈ 24.8 days). Without clamping, a far-future `expiresAt` overflows the
1843
+ * timer and fires almost immediately, causing a refresh storm. When clamped, the timer simply
1844
+ * re-schedules the remaining wait on fire instead of refreshing early.
1845
+ */
1846
+ scheduleRefresh(provider, delayMs, credential) {
1847
+ const MAX_TIMEOUT = 2147483647;
1848
+ const clamped = Math.min(delayMs, MAX_TIMEOUT);
1849
+ const timer = setTimeout(() => {
1850
+ const remaining = delayMs - clamped;
1851
+ if (remaining > 0) {
1852
+ // We hit the clamp ceiling — reschedule the rest rather than refreshing prematurely.
1853
+ this.scheduleRefresh(provider, remaining, credential);
1854
+ return;
1855
+ }
1856
+ void (async () => {
1292
1857
  try {
1293
1858
  await this.refreshToken(provider);
1294
1859
  }
1295
1860
  catch (error) {
1296
1861
  this.logger.error(`Auto token refresh failed for ${provider}`, error);
1297
1862
  }
1298
- }, refreshTime);
1299
- this.tokenRefreshTimers.set(provider, timer);
1300
- }
1863
+ })();
1864
+ }, clamped);
1865
+ this.tokenRefreshTimers.set(provider, timer);
1301
1866
  }
1302
1867
  clearTokenRefresh(provider) {
1303
1868
  const timer = this.tokenRefreshTimers.get(provider);
@@ -1306,6 +1871,13 @@ Note: This provider requires a backend service to handle authentication.
1306
1871
  this.tokenRefreshTimers.delete(provider);
1307
1872
  }
1308
1873
  }
1874
+ /** Clears every active refresh timer (used on a global, untargeted sign-out). */
1875
+ clearAllTokenRefresh() {
1876
+ for (const timer of this.tokenRefreshTimers.values()) {
1877
+ clearTimeout(timer);
1878
+ }
1879
+ this.tokenRefreshTimers.clear();
1880
+ }
1309
1881
  dispose() {
1310
1882
  // Clear all timers
1311
1883
  for (const timer of this.tokenRefreshTimers.values()) {
@@ -1340,7 +1912,20 @@ Note: This provider requires a backend service to handle authentication.
1340
1912
  this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
1341
1913
  this.authStateEmitter = new EventEmitter();
1342
1914
  }
1343
- async getCurrentUser() {
1915
+ // Capability methods with concrete defaults: providers that support these operations override
1916
+ // them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
1917
+ // across every provider (see AuthProviderInterface, where they are optional). Marking them
1918
+ // abstract previously forced every subclass to re-implement them just to throw.
1919
+ async linkAccount(_options) {
1920
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support account linking`, this.provider);
1921
+ }
1922
+ async unlinkAccount(_options) {
1923
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support account unlinking`, this.provider);
1924
+ }
1925
+ async revokeAccess(_token) {
1926
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support access revocation`, this.provider);
1927
+ }
1928
+ async getCurrentUser() {
1344
1929
  if (!this.isInitialized) {
1345
1930
  await this.initialize();
1346
1931
  }
@@ -1417,7 +2002,19 @@ Note: This provider requires a backend service to handle authentication.
1417
2002
  };
1418
2003
  }
1419
2004
  generateUniqueId() {
1420
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2005
+ // Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
2006
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
2007
+ return crypto.randomUUID();
2008
+ }
2009
+ const bytes = new Uint8Array(16);
2010
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
2011
+ crypto.getRandomValues(bytes);
2012
+ }
2013
+ let hex = '';
2014
+ for (let i = 0; i < bytes.length; i++) {
2015
+ hex += bytes[i].toString(16).padStart(2, '0');
2016
+ }
2017
+ return `${Date.now()}-${hex}`;
1421
2018
  }
1422
2019
  isTokenExpired(expiresAt) {
1423
2020
  if (!expiresAt)
@@ -1445,11 +2042,26 @@ Note: This provider requires a backend service to handle authentication.
1445
2042
  // Generate state and nonce for security
1446
2043
  const state = this.generateSecureRandomString();
1447
2044
  const nonce = this.generateSecureRandomString();
1448
- // Store state and nonce for validation
2045
+ // PKCE (RFC 7636) — default on; requires Web Crypto 'subtle' (HTTPS / localhost).
2046
+ let codeVerifier;
2047
+ let codeChallenge;
2048
+ if (config.pkceEnabled !== false) {
2049
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
2050
+ codeVerifier = this.generateCodeVerifier();
2051
+ codeChallenge = await this.generateCodeChallenge(codeVerifier);
2052
+ }
2053
+ else {
2054
+ this.logger.warn(`PKCE skipped for ${this.provider}: Web Crypto 'subtle' is unavailable (insecure context). Serve over HTTPS to enable PKCE.`);
2055
+ }
2056
+ }
2057
+ // Store state, nonce, and PKCE verifier for validation
1449
2058
  await this.storage.set(`${this.provider}_oauth_state`, state);
1450
2059
  await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
2060
+ if (codeVerifier) {
2061
+ await this.storage.set(`${this.provider}_oauth_verifier`, codeVerifier);
2062
+ }
1451
2063
  // Build authorization URL
1452
- const authUrl = this.buildAuthorizationUrl(config, state, nonce, options);
2064
+ const authUrl = this.buildAuthorizationUrl(config, state, nonce, options, codeChallenge);
1453
2065
  // Perform the OAuth flow (platform-specific implementation)
1454
2066
  const authResponse = await this.openAuthorizationUrl(authUrl);
1455
2067
  // Validate response
@@ -1458,7 +2070,10 @@ Note: This provider requires a backend service to handle authentication.
1458
2070
  if (!authResponse.code) {
1459
2071
  throw new AuthError(exports.AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
1460
2072
  }
1461
- const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
2073
+ const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config, codeVerifier);
2074
+ // Validate the ID token's nonce + expiry (replay protection). NOTE: the signature is
2075
+ // NOT verified client-side — always re-validate ID tokens on your backend.
2076
+ this.validateIdToken(tokenResponse.id_token, nonce);
1462
2077
  // Parse user information
1463
2078
  const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
1464
2079
  // Create AuthUser and AuthCredential
@@ -1477,31 +2092,47 @@ Note: This provider requires a backend service to handle authentication.
1477
2092
  // Clean up temporary storage
1478
2093
  await this.storage.remove(`${this.provider}_oauth_state`);
1479
2094
  await this.storage.remove(`${this.provider}_oauth_nonce`);
2095
+ await this.storage.remove(`${this.provider}_oauth_verifier`);
1480
2096
  }
1481
2097
  }
1482
- buildAuthorizationUrl(config, state, nonce, options) {
2098
+ buildAuthorizationUrl(config, state, nonce, options, codeChallenge) {
1483
2099
  var _a, _b, _c, _d;
1484
- const params = new URLSearchParams(Object.assign({ client_id: config.clientId, redirect_uri: config.redirectUri, response_type: config.responseType || 'code', state,
1485
- nonce }, config.additionalParams));
1486
- // Add scopes
1487
- const scopes = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) || config.scopes || [];
1488
- if (scopes.length > 0) {
1489
- params.set('scope', scopes.join(' '));
2100
+ const params = new URLSearchParams();
2101
+ // Developer-supplied params FIRST, so the security-critical params set below cannot be
2102
+ // overridden by additionalParams / customParameters.
2103
+ if (config.additionalParams) {
2104
+ for (const [key, value] of Object.entries(config.additionalParams)) {
2105
+ params.set(key, value);
2106
+ }
1490
2107
  }
1491
- // Add custom parameters
1492
- if ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.customParameters) {
1493
- Object.entries(options.options.customParameters).forEach(([key, value]) => {
2108
+ if ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.customParameters) {
2109
+ for (const [key, value] of Object.entries(options.options.customParameters)) {
1494
2110
  params.set(key, value);
1495
- });
2111
+ }
2112
+ }
2113
+ // Scopes
2114
+ const scopes = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.scopes) || config.scopes || [];
2115
+ if (scopes.length > 0) {
2116
+ params.set('scope', scopes.join(' '));
1496
2117
  }
1497
- // Add login hint if provided
2118
+ // Login hint / prompt
1498
2119
  if ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) {
1499
2120
  params.set('login_hint', options.options.loginHint);
1500
2121
  }
1501
- // Add prompt if provided
1502
2122
  if ((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) {
1503
2123
  params.set('prompt', options.options.prompt);
1504
2124
  }
2125
+ // Security-critical parameters — set LAST so custom params cannot override them.
2126
+ params.set('client_id', config.clientId);
2127
+ params.set('redirect_uri', config.redirectUri);
2128
+ params.set('response_type', config.responseType || 'code');
2129
+ params.set('state', state);
2130
+ params.set('nonce', nonce);
2131
+ if (codeChallenge) {
2132
+ params.set('code_challenge', codeChallenge);
2133
+ params.set('code_challenge_method', 'S256');
2134
+ }
2135
+ this.assertSecureEndpoint(config.authorizationEndpoint);
1505
2136
  return `${config.authorizationEndpoint}?${params.toString()}`;
1506
2137
  }
1507
2138
  async validateOAuthResponse(response, expectedState, _expectedNonce) {
@@ -1513,16 +2144,21 @@ Note: This provider requires a backend service to handle authentication.
1513
2144
  }
1514
2145
  // Nonce validation is done after ID token is received
1515
2146
  }
1516
- async exchangeCodeForTokens(code, config) {
2147
+ async exchangeCodeForTokens(code, config, codeVerifier) {
1517
2148
  const params = new URLSearchParams({
1518
2149
  grant_type: config.grantType || 'authorization_code',
1519
2150
  code,
1520
2151
  redirect_uri: config.redirectUri,
1521
2152
  client_id: config.clientId,
1522
2153
  });
2154
+ if (codeVerifier) {
2155
+ params.set('code_verifier', codeVerifier);
2156
+ }
1523
2157
  if (config.clientSecret) {
2158
+ this.warnClientSecretInBrowser();
1524
2159
  params.set('client_secret', config.clientSecret);
1525
2160
  }
2161
+ this.assertSecureEndpoint(config.tokenEndpoint);
1526
2162
  try {
1527
2163
  const response = await fetch(config.tokenEndpoint, {
1528
2164
  method: 'POST',
@@ -1559,8 +2195,10 @@ Note: This provider requires a backend service to handle authentication.
1559
2195
  client_id: config.clientId,
1560
2196
  });
1561
2197
  if (config.clientSecret) {
2198
+ this.warnClientSecretInBrowser();
1562
2199
  params.set('client_secret', config.clientSecret);
1563
2200
  }
2201
+ this.assertSecureEndpoint(config.tokenEndpoint);
1564
2202
  const response = await fetch(config.tokenEndpoint, {
1565
2203
  method: 'POST',
1566
2204
  headers: {
@@ -1607,8 +2245,10 @@ Note: This provider requires a backend service to handle authentication.
1607
2245
  client_id: config.clientId,
1608
2246
  });
1609
2247
  if (config.clientSecret) {
2248
+ this.warnClientSecretInBrowser();
1610
2249
  params.set('client_secret', config.clientSecret);
1611
2250
  }
2251
+ this.assertSecureEndpoint(config.revokeEndpoint);
1612
2252
  await fetch(config.revokeEndpoint, {
1613
2253
  method: 'POST',
1614
2254
  headers: {
@@ -1695,6 +2335,80 @@ Note: This provider requires a backend service to handle authentication.
1695
2335
  }
1696
2336
  return result;
1697
2337
  }
2338
+ /** RFC 7636 PKCE code verifier: 64 chars from the unreserved set [A-Za-z0-9]. */
2339
+ generateCodeVerifier() {
2340
+ return this.generateSecureRandomString(64);
2341
+ }
2342
+ /** Derives the S256 PKCE code challenge: base64url(SHA-256(verifier)). */
2343
+ async generateCodeChallenge(verifier) {
2344
+ const data = new TextEncoder().encode(verifier);
2345
+ const digest = await crypto.subtle.digest('SHA-256', data);
2346
+ return this.base64UrlEncode(new Uint8Array(digest));
2347
+ }
2348
+ base64UrlEncode(bytes) {
2349
+ let binary = '';
2350
+ for (let i = 0; i < bytes.length; i++) {
2351
+ binary += String.fromCharCode(bytes[i]);
2352
+ }
2353
+ return btoa(binary)
2354
+ .replace(/\+/g, '-')
2355
+ .replace(/\//g, '_')
2356
+ .replace(/=+$/, '');
2357
+ }
2358
+ /** Decodes a JWT payload without verifying the signature. Returns null if malformed. */
2359
+ decodeJwtPayload(token) {
2360
+ try {
2361
+ const parts = token.split('.');
2362
+ if (parts.length < 2) {
2363
+ return null;
2364
+ }
2365
+ let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
2366
+ const pad = payload.length % 4;
2367
+ if (pad) {
2368
+ payload += '='.repeat(4 - pad);
2369
+ }
2370
+ return JSON.parse(atob(payload));
2371
+ }
2372
+ catch (_a) {
2373
+ return null;
2374
+ }
2375
+ }
2376
+ /**
2377
+ * Validates the ID token's nonce (replay protection) and expiry. The signature is NOT
2378
+ * verified client-side — always re-validate ID tokens on your backend before trusting them.
2379
+ */
2380
+ validateIdToken(idToken, expectedNonce) {
2381
+ if (!idToken) {
2382
+ return;
2383
+ }
2384
+ const payload = this.decodeJwtPayload(idToken);
2385
+ if (!payload) {
2386
+ return;
2387
+ }
2388
+ if (payload.nonce !== undefined && payload.nonce !== expectedNonce) {
2389
+ throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'OIDC nonce mismatch in ID token', this.provider);
2390
+ }
2391
+ if (typeof payload.exp === 'number' && payload.exp * 1000 < Date.now()) {
2392
+ throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'ID token is expired', this.provider);
2393
+ }
2394
+ }
2395
+ warnClientSecretInBrowser() {
2396
+ this.logger.warn(`${this.provider}: a client secret was supplied to a browser-facing provider. Secrets ` +
2397
+ `placed in client config ship in the JS bundle and are recoverable by end users. Use a ` +
2398
+ `backend token-exchange proxy (set tokenEndpoint to your server) instead.`);
2399
+ }
2400
+ assertSecureEndpoint(url) {
2401
+ try {
2402
+ const parsed = new URL(url);
2403
+ const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
2404
+ if (parsed.protocol !== 'https:' && !isLocalhost) {
2405
+ this.logger.warn(`${this.provider}: endpoint ${url} is not HTTPS — credentials/tokens may be sent in cleartext.`);
2406
+ }
2407
+ }
2408
+ catch (_a) {
2409
+ // Malformed URL: let the subsequent fetch surface the error.
2410
+ }
2411
+ }
1698
2412
  }
1699
2413
 
1700
2414
  class GoogleAuthProviderWeb extends OAuthProvider {
@@ -2053,8 +2767,8 @@ Note: This provider requires a backend service to handle authentication.
2053
2767
  const response = await window.AppleID.auth.signIn(signInConfig);
2054
2768
  // Validate response
2055
2769
  await this.validateAppleResponse(response, state, nonce);
2056
- // Parse user information from response
2057
- const user = this.createAppleAuthUser(response);
2770
+ // Parse user information from response (validates ID token nonce + expiry first)
2771
+ const user = this.createAppleAuthUser(response, nonce);
2058
2772
  const credential = this.createAppleCredential(response);
2059
2773
  // Save user and credential
2060
2774
  await this.setCurrentUser(user);
@@ -2088,6 +2802,12 @@ Note: This provider requires a backend service to handle authentication.
2088
2802
  throw AuthError.fromError(error, this.provider);
2089
2803
  }
2090
2804
  }
2805
+ async refreshToken(_options) {
2806
+ // Apple's JS (web) Sign In flow never issues a refresh token, so the inherited
2807
+ // OAuthProvider.refreshToken() would fail with a confusing "No refresh token available".
2808
+ // Surface an explicit, accurate error instead: callers must re-authenticate.
2809
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Apple web sign-in does not issue refresh tokens; re-authenticate instead.', this.provider);
2810
+ }
2091
2811
  async isSupported() {
2092
2812
  // Check if we're in a browser environment
2093
2813
  if (typeof window === 'undefined' || typeof document === 'undefined') {
@@ -2168,19 +2888,29 @@ Note: This provider requires a backend service to handle authentication.
2168
2888
  // ID token validation with nonce would be done here
2169
2889
  // For production, you should validate the ID token on your backend
2170
2890
  }
2171
- createAppleAuthUser(response) {
2891
+ createAppleAuthUser(response, expectedNonce) {
2172
2892
  var _a, _b, _c;
2173
2893
  const user = response.user || {};
2174
2894
  const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
2175
- // Parse ID token claims (in production, do this on backend)
2895
+ // Validate the ID token's nonce (replay protection) and expiry BEFORE trusting any
2896
+ // claims. The signature is NOT verified client-side — always re-validate on your backend.
2897
+ // Defensive: only enforce the nonce when both an expected nonce and a token nonce exist.
2176
2898
  let claims = {};
2177
2899
  if (idToken) {
2178
- try {
2179
- const payload = idToken.split('.')[1];
2180
- claims = JSON.parse(atob(payload));
2900
+ const payload = this.decodeJwtPayload(idToken);
2901
+ if (payload) {
2902
+ claims = payload;
2903
+ if (expectedNonce &&
2904
+ claims.nonce !== undefined &&
2905
+ claims.nonce !== expectedNonce) {
2906
+ throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'Apple ID token nonce does not match the expected value', this.provider);
2907
+ }
2908
+ if (typeof claims.exp === 'number' && claims.exp * 1000 < Date.now()) {
2909
+ throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Apple ID token is expired', this.provider);
2910
+ }
2181
2911
  }
2182
- catch (error) {
2183
- this.logger.error('Failed to parse ID token', error);
2912
+ else {
2913
+ this.logger.error('Failed to decode Apple ID token payload');
2184
2914
  }
2185
2915
  }
2186
2916
  return {
@@ -2253,11 +2983,16 @@ Note: This provider requires a backend service to handle authentication.
2253
2983
  class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2254
2984
  constructor() {
2255
2985
  super(...arguments);
2986
+ this.msalConfig = {};
2256
2987
  this.clientId = '';
2257
2988
  this.authority = '';
2258
2989
  this.redirectUri = '';
2259
2990
  this.scopes = [];
2260
2991
  }
2992
+ /** Reads the host-page MSAL SDK, casting the `window` boundary exactly once. */
2993
+ getMsal() {
2994
+ return window.msal;
2995
+ }
2261
2996
  async initialize() {
2262
2997
  const options = this.options;
2263
2998
  if (!options.clientId) {
@@ -2269,7 +3004,7 @@ Note: This provider requires a backend service to handle authentication.
2269
3004
  this.redirectUri = options.redirectUri || window.location.origin;
2270
3005
  this.scopes = options.scopes || ['openid', 'profile', 'email'];
2271
3006
  // Check if MSAL is available
2272
- const msal = window.msal;
3007
+ const msal = this.getMsal();
2273
3008
  if (!msal) {
2274
3009
  throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Microsoft Authentication Library (MSAL) is not loaded. Please include the MSAL script in your HTML.', this.provider);
2275
3010
  }
@@ -2316,9 +3051,22 @@ Note: This provider requires a backend service to handle authentication.
2316
3051
  }
2317
3052
  }
2318
3053
  async signIn(options) {
3054
+ var _a, _b, _c, _d;
2319
3055
  this.validateInitialized();
2320
3056
  try {
2321
- const loginRequest = Object.assign({ scopes: this.scopes }, options);
3057
+ // Build the MSAL login request EXPLICITLY from the standard options shape — spreading
3058
+ // raw `options` here would leak junk (provider, credentials, …) into MSAL and ignore
3059
+ // per-sign-in scopes. Honour per-call scopes/loginHint/prompt, fall back to configured
3060
+ // scopes, and omit undefined keys.
3061
+ const loginRequest = {
3062
+ scopes: (_b = (_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : this.scopes,
3063
+ };
3064
+ if (((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) !== undefined) {
3065
+ loginRequest.loginHint = options.options.loginHint;
3066
+ }
3067
+ if (((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) !== undefined) {
3068
+ loginRequest.prompt = options.options.prompt;
3069
+ }
2322
3070
  // Try popup first, fallback to redirect
2323
3071
  let response;
2324
3072
  try {
@@ -2337,10 +3085,11 @@ Note: This provider requires a backend service to handle authentication.
2337
3085
  }
2338
3086
  catch (error) {
2339
3087
  this.logger.error('Microsoft sign in failed', error);
2340
- if (error.errorCode === 'user_cancelled') {
3088
+ const err = error;
3089
+ if (err.errorCode === 'user_cancelled') {
2341
3090
  throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
2342
3091
  }
2343
- throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${error.message}`, this.provider);
3092
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${err.message}`, this.provider);
2344
3093
  }
2345
3094
  }
2346
3095
  async signOut(options) {
@@ -2386,15 +3135,16 @@ Note: This provider requires a backend service to handle authentication.
2386
3135
  }
2387
3136
  catch (error) {
2388
3137
  this.logger.error('Token refresh failed', error);
2389
- if (error.errorCode === 'interaction_required') {
3138
+ const err = error;
3139
+ if (err.errorCode === 'interaction_required') {
2390
3140
  // Need user interaction, trigger sign in
2391
3141
  return await this.signIn();
2392
3142
  }
2393
- throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${error.message}`, this.provider);
3143
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${err.message}`, this.provider);
2394
3144
  }
2395
3145
  }
2396
3146
  async isSupported() {
2397
- return typeof window !== 'undefined' && !!window.msal;
3147
+ return typeof window !== 'undefined' && !!this.getMsal();
2398
3148
  }
2399
3149
  async linkAccount() {
2400
3150
  // Microsoft doesn't support account linking in the same way
@@ -2424,32 +3174,37 @@ Note: This provider requires a backend service to handle authentication.
2424
3174
  scope: response.scopes.join(' '),
2425
3175
  };
2426
3176
  await this.saveCredential(credential);
2427
- return this.createAuthResult(user, credential, ((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser) || false);
3177
+ return this.createAuthResult(user, credential, Boolean((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser));
2428
3178
  }
2429
3179
  createUserFromMSALAccount(account) {
2430
3180
  const idTokenClaims = account.idTokenClaims || {};
3181
+ const claim = (key) => {
3182
+ const value = idTokenClaims[key];
3183
+ return typeof value === 'string' ? value : undefined;
3184
+ };
3185
+ const iat = idTokenClaims.iat;
2431
3186
  return {
2432
- uid: account.localAccountId || account.homeAccountId,
2433
- email: idTokenClaims.email || account.username,
3187
+ uid: account.localAccountId || account.homeAccountId || '',
3188
+ email: claim('email') || account.username || null,
2434
3189
  emailVerified: !!idTokenClaims.email_verified,
2435
- displayName: account.name || idTokenClaims.name,
2436
- photoURL: idTokenClaims.picture || null,
2437
- phoneNumber: idTokenClaims.phone_number || null,
3190
+ displayName: account.name || claim('name') || null,
3191
+ photoURL: claim('picture') || null,
3192
+ phoneNumber: claim('phone_number') || null,
2438
3193
  isAnonymous: false,
2439
- tenantId: account.tenantId,
3194
+ tenantId: account.tenantId || null,
2440
3195
  providerData: [
2441
3196
  {
2442
3197
  providerId: this.provider,
2443
- uid: account.localAccountId,
2444
- displayName: account.name,
2445
- email: account.username,
3198
+ uid: account.localAccountId || '',
3199
+ displayName: account.name || null,
3200
+ email: account.username || null,
2446
3201
  phoneNumber: null,
2447
- photoURL: idTokenClaims.picture || null,
3202
+ photoURL: claim('picture') || null,
2448
3203
  },
2449
3204
  ],
2450
3205
  metadata: {
2451
- creationTime: idTokenClaims.iat
2452
- ? new Date(idTokenClaims.iat * 1000).toISOString()
3206
+ creationTime: typeof iat === 'number'
3207
+ ? new Date(iat * 1000).toISOString()
2453
3208
  : undefined,
2454
3209
  lastSignInTime: new Date().toISOString(),
2455
3210
  },
@@ -2547,7 +3302,7 @@ Note: This provider requires a backend service to handle authentication.
2547
3302
  checkLoginStatus() {
2548
3303
  return new Promise((resolve) => {
2549
3304
  window.FB.getLoginStatus(async (response) => {
2550
- if (response.status === 'connected') {
3305
+ if (response.status === 'connected' && response.authResponse) {
2551
3306
  await this.handleAuthResponse(response.authResponse);
2552
3307
  }
2553
3308
  resolve();
@@ -2602,7 +3357,7 @@ Note: This provider requires a backend service to handle authentication.
2602
3357
  // Facebook access tokens are short-lived and need to be refreshed via re-authentication
2603
3358
  return new Promise((resolve, reject) => {
2604
3359
  window.FB.getLoginStatus(async (response) => {
2605
- if (response.status === 'connected') {
3360
+ if (response.status === 'connected' && response.authResponse) {
2606
3361
  try {
2607
3362
  const result = await this.handleAuthResponse(response.authResponse, true);
2608
3363
  resolve(result);
@@ -2722,6 +3477,12 @@ Note: This provider requires a backend service to handle authentication.
2722
3477
  this.scopes = [];
2723
3478
  this.authWindow = null;
2724
3479
  this.authPromise = null;
3480
+ /** Bound 'message' handler reference so it can be removed in dispose(). */
3481
+ this.boundAuthMessageHandler = null;
3482
+ /** Active popup-closed polling interval, tracked so it is cleared on every exit path. */
3483
+ this.popupCheckInterval = null;
3484
+ /** CSRF state from the most recent sign-in, forwarded to the proxy for re-verification. */
3485
+ this.lastState = null;
2725
3486
  }
2726
3487
  async initialize() {
2727
3488
  const options = this.options;
@@ -2732,8 +3493,12 @@ Note: This provider requires a backend service to handle authentication.
2732
3493
  this.redirectUri =
2733
3494
  options.redirectUri || window.location.origin + '/auth/github/callback';
2734
3495
  this.scopes = options.scopes || ['read:user', 'user:email'];
2735
- // Set up message listener for OAuth callback
2736
- window.addEventListener('message', this.handleAuthMessage.bind(this));
3496
+ this.tokenExchangeProxy =
3497
+ options.tokenExchangeProxy || options.tokenEndpoint;
3498
+ // Set up message listener for OAuth callback. Keep the bound reference so the exact
3499
+ // same function can be removed in dispose() (a fresh `.bind()` would not match).
3500
+ this.boundAuthMessageHandler = this.handleAuthMessage.bind(this);
3501
+ window.addEventListener('message', this.boundAuthMessageHandler);
2737
3502
  // Check for stored session
2738
3503
  await this.loadCurrentUser();
2739
3504
  this.isInitialized = true;
@@ -2744,6 +3509,7 @@ Note: This provider requires a backend service to handle authentication.
2744
3509
  return new Promise((resolve, reject) => {
2745
3510
  this.authPromise = { resolve, reject };
2746
3511
  const state = this.generateState();
3512
+ this.lastState = state;
2747
3513
  const authUrl = this.buildAuthUrl(state);
2748
3514
  // Open GitHub OAuth in a popup window
2749
3515
  const width = 600;
@@ -2756,11 +3522,13 @@ Note: This provider requires a backend service to handle authentication.
2756
3522
  reject(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, 'Popup window was blocked. Please allow popups for this site.', this.provider));
2757
3523
  return;
2758
3524
  }
2759
- // Check if popup is closed
2760
- const checkInterval = setInterval(() => {
3525
+ // Check if popup is closed. Track the interval so the success path
3526
+ // (handleAuthMessage) and dispose() can also clear it — otherwise it leaks.
3527
+ this.clearPopupCheckInterval();
3528
+ this.popupCheckInterval = setInterval(() => {
2761
3529
  var _a;
2762
3530
  if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
2763
- clearInterval(checkInterval);
3531
+ this.clearPopupCheckInterval();
2764
3532
  if (this.authPromise) {
2765
3533
  this.authPromise = null;
2766
3534
  reject(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User closed the authentication window', this.provider));
@@ -2769,6 +3537,12 @@ Note: This provider requires a backend service to handle authentication.
2769
3537
  }, 1000);
2770
3538
  });
2771
3539
  }
3540
+ clearPopupCheckInterval() {
3541
+ if (this.popupCheckInterval !== null) {
3542
+ clearInterval(this.popupCheckInterval);
3543
+ this.popupCheckInterval = null;
3544
+ }
3545
+ }
2772
3546
  async signOut(options) {
2773
3547
  this.validateInitialized();
2774
3548
  try {
@@ -2847,6 +3621,8 @@ Note: This provider requires a backend service to handle authentication.
2847
3621
  if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) !== 'github-auth-callback') {
2848
3622
  return;
2849
3623
  }
3624
+ // The callback arrived — stop polling for a closed popup (success path cleanup).
3625
+ this.clearPopupCheckInterval();
2850
3626
  if (this.authWindow) {
2851
3627
  this.authWindow.close();
2852
3628
  this.authWindow = null;
@@ -2889,9 +3665,44 @@ Note: This provider requires a backend service to handle authentication.
2889
3665
  reject(AuthError.fromError(error, this.provider));
2890
3666
  }
2891
3667
  }
2892
- async exchangeCodeForToken(_code) {
2893
- // NOTE: This should be done server-side in production to keep client secret secure
2894
- throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'GitHub token exchange must be implemented server-side. Please set up a backend endpoint to exchange the authorization code for an access token.', this.provider);
3668
+ async exchangeCodeForToken(code) {
3669
+ // GitHub does NOT permit browser-side code→token exchange (it needs the client secret
3670
+ // and blocks CORS), so the exchange must run on a developer-supplied backend proxy.
3671
+ if (!this.tokenExchangeProxy) {
3672
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'GitHub sign-in requires a backend token-exchange proxy. Set `tokenExchangeProxy` ' +
3673
+ '(or `tokenEndpoint`) in the GitHub provider config to a server endpoint that ' +
3674
+ 'exchanges the authorization code for an access token. See the GitHub provider ' +
3675
+ 'setup guide / docs/providers for an example.', this.provider);
3676
+ }
3677
+ let response;
3678
+ try {
3679
+ response = await fetch(this.tokenExchangeProxy, {
3680
+ method: 'POST',
3681
+ headers: {
3682
+ 'Content-Type': 'application/json',
3683
+ Accept: 'application/json',
3684
+ },
3685
+ body: JSON.stringify({
3686
+ code,
3687
+ redirectUri: this.redirectUri,
3688
+ state: this.lastState,
3689
+ }),
3690
+ });
3691
+ }
3692
+ catch (error) {
3693
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach the GitHub token-exchange proxy', this.provider, error);
3694
+ }
3695
+ const data = (await response
3696
+ .json()
3697
+ .catch(() => null));
3698
+ if (!response.ok || !data || !data.access_token) {
3699
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `GitHub token exchange failed${(data === null || data === void 0 ? void 0 : data.error_description)
3700
+ ? `: ${data.error_description}`
3701
+ : (data === null || data === void 0 ? void 0 : data.error)
3702
+ ? `: ${data.error}`
3703
+ : ''}`, this.provider);
3704
+ }
3705
+ return Object.assign(Object.assign({}, data), { access_token: data.access_token });
2895
3706
  }
2896
3707
  async fetchUserData(accessToken) {
2897
3708
  const response = await fetch('https://api.github.com/user', {
@@ -2918,6 +3729,7 @@ Note: This provider requires a backend service to handle authentication.
2918
3729
  return await response.json();
2919
3730
  }
2920
3731
  async createUserFromGitHubData(userData, accessToken) {
3732
+ var _a, _b, _c, _d, _e, _f;
2921
3733
  // Get primary email
2922
3734
  const emails = await this.fetchUserEmails(accessToken);
2923
3735
  const primaryEmail = emails.find((e) => e.primary) || emails[0];
@@ -2948,15 +3760,35 @@ Note: This provider requires a backend service to handle authentication.
2948
3760
  },
2949
3761
  customClaims: {
2950
3762
  login: userData.login,
2951
- company: userData.company,
2952
- location: userData.location,
2953
- bio: userData.bio,
2954
- public_repos: userData.public_repos,
2955
- followers: userData.followers,
2956
- following: userData.following,
3763
+ company: (_a = userData.company) !== null && _a !== void 0 ? _a : null,
3764
+ location: (_b = userData.location) !== null && _b !== void 0 ? _b : null,
3765
+ bio: (_c = userData.bio) !== null && _c !== void 0 ? _c : null,
3766
+ public_repos: (_d = userData.public_repos) !== null && _d !== void 0 ? _d : null,
3767
+ followers: (_e = userData.followers) !== null && _e !== void 0 ? _e : null,
3768
+ following: (_f = userData.following) !== null && _f !== void 0 ? _f : null,
2957
3769
  },
2958
3770
  };
2959
3771
  }
3772
+ dispose() {
3773
+ // Remove the global 'message' listener added in initialize() so it doesn't leak across
3774
+ // repeated init/dispose cycles, and stop any active popup-polling interval.
3775
+ if (this.boundAuthMessageHandler) {
3776
+ window.removeEventListener('message', this.boundAuthMessageHandler);
3777
+ this.boundAuthMessageHandler = null;
3778
+ }
3779
+ this.clearPopupCheckInterval();
3780
+ if (this.authWindow) {
3781
+ try {
3782
+ this.authWindow.close();
3783
+ }
3784
+ catch (_a) {
3785
+ // window already closed / cross-origin — safe to ignore
3786
+ }
3787
+ this.authWindow = null;
3788
+ }
3789
+ this.authPromise = null;
3790
+ super.dispose();
3791
+ }
2960
3792
  }
2961
3793
 
2962
3794
  var githubProvider = /*#__PURE__*/Object.freeze({
@@ -2969,6 +3801,11 @@ Note: This provider requires a backend service to handle authentication.
2969
3801
  super(...arguments);
2970
3802
  this.unsubscribeAuth = null;
2971
3803
  }
3804
+ /** Reads the host-page Firebase SDK, casting the `window` boundary exactly once. */
3805
+ getFirebase() {
3806
+ return window
3807
+ .firebase;
3808
+ }
2972
3809
  async initialize() {
2973
3810
  const options = this.options;
2974
3811
  if (!options.apiKey || !options.authDomain || !options.projectId) {
@@ -2976,7 +3813,7 @@ Note: This provider requires a backend service to handle authentication.
2976
3813
  }
2977
3814
  try {
2978
3815
  // Check if Firebase is available
2979
- const firebase = window.firebase;
3816
+ const firebase = this.getFirebase();
2980
3817
  if (!firebase) {
2981
3818
  throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded. Please include the Firebase scripts in your HTML.', this.provider);
2982
3819
  }
@@ -3024,73 +3861,88 @@ Note: This provider requires a backend service to handle authentication.
3024
3861
  }
3025
3862
  }
3026
3863
  getPersistenceMode() {
3027
- const firebase = window.firebase;
3864
+ const firebase = this.getFirebase();
3865
+ const persistence = firebase === null || firebase === void 0 ? void 0 : firebase.auth.Auth.Persistence;
3028
3866
  switch (this.persistence) {
3029
3867
  case 'session':
3030
- return firebase.auth.Auth.Persistence.SESSION;
3868
+ return persistence === null || persistence === void 0 ? void 0 : persistence.SESSION;
3031
3869
  case 'none':
3032
- return firebase.auth.Auth.Persistence.NONE;
3870
+ return persistence === null || persistence === void 0 ? void 0 : persistence.NONE;
3033
3871
  default:
3034
- return firebase.auth.Auth.Persistence.LOCAL;
3872
+ return persistence === null || persistence === void 0 ? void 0 : persistence.LOCAL;
3035
3873
  }
3036
3874
  }
3037
3875
  async signIn(options) {
3876
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3038
3877
  this.validateInitialized();
3039
- const signInOptions = options || {};
3878
+ // The manager spreads credentials to the top level AND nests them under `credentials`,
3879
+ // and spreads `options.*` (scopes, prompt, etc.) to the top level too. Derive the
3880
+ // Firebase sub-method from the STANDARD shape instead of an undocumented `options.method`.
3881
+ const raw = options || {};
3882
+ const nestedOptions = raw.options || {};
3883
+ const credentials = raw.credentials || {};
3884
+ // email/password may arrive nested under `credentials` or spread to the top level.
3885
+ const email = ((_a = credentials.email) !== null && _a !== void 0 ? _a : raw.email);
3886
+ const password = ((_b = credentials.password) !== null && _b !== void 0 ? _b : raw.password);
3887
+ const scopes = ((_c = nestedOptions.scopes) !== null && _c !== void 0 ? _c : raw.scopes);
3888
+ const firebaseOptions = this.options;
3889
+ const method = ((_e = (_d = nestedOptions.method) !== null && _d !== void 0 ? _d : raw.method) !== null && _e !== void 0 ? _e : (email && password
3890
+ ? 'email'
3891
+ : firebaseOptions.defaultMethod || 'google'));
3892
+ const signInOptions = { method, email, password, scopes };
3893
+ const firebase = this.getFirebase();
3894
+ if (!firebase) {
3895
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
3896
+ }
3897
+ const applyScopes = (provider) => {
3898
+ if (signInOptions.scopes) {
3899
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3900
+ }
3901
+ };
3040
3902
  try {
3041
3903
  let firebaseUser;
3042
3904
  let credential;
3043
3905
  let additionalUserInfo;
3044
3906
  // Determine sign-in method
3045
3907
  if (signInOptions.method === 'google') {
3046
- const provider = new window.firebase.auth.GoogleAuthProvider();
3047
- if (signInOptions.scopes) {
3048
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3049
- }
3908
+ const provider = new firebase.auth.GoogleAuthProvider();
3909
+ applyScopes(provider);
3050
3910
  const result = await this.firebaseAuth.signInWithPopup(provider);
3051
3911
  firebaseUser = result.user;
3052
3912
  credential = result.credential;
3053
- additionalUserInfo = result.additionalUserInfo;
3913
+ additionalUserInfo = (_f = result.additionalUserInfo) !== null && _f !== void 0 ? _f : {};
3054
3914
  }
3055
3915
  else if (signInOptions.method === 'facebook') {
3056
- const provider = new window.firebase.auth.FacebookAuthProvider();
3057
- if (signInOptions.scopes) {
3058
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3059
- }
3916
+ const provider = new firebase.auth.FacebookAuthProvider();
3917
+ applyScopes(provider);
3060
3918
  const result = await this.firebaseAuth.signInWithPopup(provider);
3061
3919
  firebaseUser = result.user;
3062
3920
  credential = result.credential;
3063
- additionalUserInfo = result.additionalUserInfo;
3921
+ additionalUserInfo = (_g = result.additionalUserInfo) !== null && _g !== void 0 ? _g : {};
3064
3922
  }
3065
3923
  else if (signInOptions.method === 'github') {
3066
- const provider = new window.firebase.auth.GithubAuthProvider();
3067
- if (signInOptions.scopes) {
3068
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3069
- }
3924
+ const provider = new firebase.auth.GithubAuthProvider();
3925
+ applyScopes(provider);
3070
3926
  const result = await this.firebaseAuth.signInWithPopup(provider);
3071
3927
  firebaseUser = result.user;
3072
3928
  credential = result.credential;
3073
- additionalUserInfo = result.additionalUserInfo;
3929
+ additionalUserInfo = (_h = result.additionalUserInfo) !== null && _h !== void 0 ? _h : {};
3074
3930
  }
3075
3931
  else if (signInOptions.method === 'microsoft') {
3076
- const provider = new window.firebase.auth.OAuthProvider('microsoft.com');
3077
- if (signInOptions.scopes) {
3078
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3079
- }
3932
+ const provider = new firebase.auth.OAuthProvider('microsoft.com');
3933
+ applyScopes(provider);
3080
3934
  const result = await this.firebaseAuth.signInWithPopup(provider);
3081
3935
  firebaseUser = result.user;
3082
3936
  credential = result.credential;
3083
- additionalUserInfo = result.additionalUserInfo;
3937
+ additionalUserInfo = (_j = result.additionalUserInfo) !== null && _j !== void 0 ? _j : {};
3084
3938
  }
3085
3939
  else if (signInOptions.method === 'apple') {
3086
- const provider = new window.firebase.auth.OAuthProvider('apple.com');
3087
- if (signInOptions.scopes) {
3088
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3089
- }
3940
+ const provider = new firebase.auth.OAuthProvider('apple.com');
3941
+ applyScopes(provider);
3090
3942
  const result = await this.firebaseAuth.signInWithPopup(provider);
3091
3943
  firebaseUser = result.user;
3092
3944
  credential = result.credential;
3093
- additionalUserInfo = result.additionalUserInfo;
3945
+ additionalUserInfo = (_k = result.additionalUserInfo) !== null && _k !== void 0 ? _k : {};
3094
3946
  }
3095
3947
  else if (signInOptions.method === 'email' &&
3096
3948
  signInOptions.email &&
@@ -3122,11 +3974,12 @@ Note: This provider requires a backend service to handle authentication.
3122
3974
  }
3123
3975
  catch (error) {
3124
3976
  this.logger.error('Firebase sign in failed', error);
3125
- if (error.code === 'auth/popup-closed-by-user' ||
3126
- error.code === 'auth/cancelled-popup-request') {
3977
+ const err = error;
3978
+ if (err.code === 'auth/popup-closed-by-user' ||
3979
+ err.code === 'auth/cancelled-popup-request') {
3127
3980
  throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
3128
3981
  }
3129
- throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${error.message}`, this.provider);
3982
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${err.message}`, this.provider);
3130
3983
  }
3131
3984
  }
3132
3985
  async signOut(options) {
@@ -3170,24 +4023,33 @@ Note: This provider requires a backend service to handle authentication.
3170
4023
  }
3171
4024
  }
3172
4025
  async isSupported() {
3173
- return typeof window !== 'undefined' && !!window.firebase;
4026
+ return typeof window !== 'undefined' && !!this.getFirebase();
3174
4027
  }
3175
4028
  async linkAccount(options) {
4029
+ var _a, _b, _c, _d;
3176
4030
  this.validateInitialized();
3177
4031
  const currentUser = this.firebaseAuth.currentUser;
3178
4032
  if (!currentUser) {
3179
4033
  throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session to link account to', this.provider);
3180
4034
  }
4035
+ const firebase = this.getFirebase();
4036
+ if (!firebase) {
4037
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
4038
+ }
4039
+ // `method`/`email`/`password` may arrive nested under credentials or in provider options.
4040
+ const raw = options;
4041
+ const creds = (_a = raw.credentials) !== null && _a !== void 0 ? _a : {};
4042
+ const method = ((_b = raw.method) !== null && _b !== void 0 ? _b : creds.method);
4043
+ const linkEmail = ((_c = creds.email) !== null && _c !== void 0 ? _c : raw.email);
4044
+ const linkPassword = ((_d = creds.password) !== null && _d !== void 0 ? _d : raw.password);
3181
4045
  try {
3182
4046
  let result;
3183
- if (options.method === 'google') {
3184
- const provider = new window.firebase.auth.GoogleAuthProvider();
4047
+ if (method === 'google') {
4048
+ const provider = new firebase.auth.GoogleAuthProvider();
3185
4049
  result = await currentUser.linkWithPopup(provider);
3186
4050
  }
3187
- else if (options.method === 'email' &&
3188
- options.email &&
3189
- options.password) {
3190
- const credential = window.firebase.auth.EmailAuthProvider.credential(options.email, options.password);
4051
+ else if (method === 'email' && linkEmail && linkPassword) {
4052
+ const credential = firebase.auth.EmailAuthProvider.credential(linkEmail, linkPassword);
3191
4053
  result = await currentUser.linkWithCredential(credential);
3192
4054
  }
3193
4055
  else {
@@ -3198,6 +4060,8 @@ Note: This provider requires a backend service to handle authentication.
3198
4060
  return this.createAuthResult(user, authCredential, false, 'link');
3199
4061
  }
3200
4062
  catch (error) {
4063
+ if (error instanceof AuthError)
4064
+ throw error;
3201
4065
  throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to link account: ${error.message}`, this.provider);
3202
4066
  }
3203
4067
  }
@@ -3208,7 +4072,7 @@ Note: This provider requires a backend service to handle authentication.
3208
4072
  throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session', this.provider);
3209
4073
  }
3210
4074
  try {
3211
- await currentUser.unlink(options.providerId);
4075
+ await currentUser.unlink(options.provider);
3212
4076
  }
3213
4077
  catch (error) {
3214
4078
  throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to unlink account: ${error.message}`, this.provider);
@@ -3272,10 +4136,116 @@ Note: This provider requires a backend service to handle authentication.
3272
4136
  FirebaseAuthProviderWeb: FirebaseAuthProviderWeb
3273
4137
  });
3274
4138
 
4139
+ class PendingVerificationStore {
4140
+ /**
4141
+ * @param namespace Provider namespace (e.g. `'sms'`, `'email-code'`, `'magic-link'`). Keys are
4142
+ * stored under `cap_auth_pending_<namespace>` so providers never collide.
4143
+ */
4144
+ constructor(namespace) {
4145
+ /** In-memory mirror so the store works in SSR / private-mode where localStorage is unavailable. */
4146
+ this.memory = new Map();
4147
+ this.storageKey = `cap_auth_pending_${namespace}`;
4148
+ }
4149
+ getLocalStorage() {
4150
+ try {
4151
+ return typeof localStorage !== 'undefined' ? localStorage : null;
4152
+ }
4153
+ catch (_a) {
4154
+ // Access to localStorage can throw (e.g. sandboxed iframe) — fall back to memory only.
4155
+ return null;
4156
+ }
4157
+ }
4158
+ readAll() {
4159
+ const ls = this.getLocalStorage();
4160
+ if (!ls) {
4161
+ return Object.fromEntries(this.memory);
4162
+ }
4163
+ try {
4164
+ const raw = ls.getItem(this.storageKey);
4165
+ if (!raw)
4166
+ return {};
4167
+ const parsed = JSON.parse(raw);
4168
+ return parsed && typeof parsed === 'object' ? parsed : {};
4169
+ }
4170
+ catch (error) {
4171
+ defaultLogger.warn(`PendingVerificationStore: failed to read ${this.storageKey}`, error);
4172
+ return {};
4173
+ }
4174
+ }
4175
+ writeAll(all) {
4176
+ const ls = this.getLocalStorage();
4177
+ if (!ls) {
4178
+ this.memory.clear();
4179
+ for (const [k, v] of Object.entries(all))
4180
+ this.memory.set(k, v);
4181
+ return;
4182
+ }
4183
+ try {
4184
+ ls.setItem(this.storageKey, JSON.stringify(all));
4185
+ }
4186
+ catch (error) {
4187
+ defaultLogger.warn(`PendingVerificationStore: failed to write ${this.storageKey}`, error);
4188
+ }
4189
+ }
4190
+ /**
4191
+ * Stores (or replaces) the pending record for `key` (phone / email / magic-link token). Other
4192
+ * expired entries in the namespace are pruned here to bound storage growth.
4193
+ */
4194
+ set(key, record) {
4195
+ const all = this.readAll();
4196
+ this.pruneExpired(all, key);
4197
+ all[key] = record;
4198
+ this.writeAll(all);
4199
+ }
4200
+ /**
4201
+ * Returns the pending record for `key`, or null if absent. Does NOT filter by expiry — the
4202
+ * caller owns the expiry decision so it can throw a precise error and clean up itself.
4203
+ */
4204
+ get(key) {
4205
+ var _a;
4206
+ const all = this.readAll();
4207
+ return (_a = all[key]) !== null && _a !== void 0 ? _a : null;
4208
+ }
4209
+ /** Removes the pending record for `key` (e.g. after a successful or expired verification). */
4210
+ delete(key) {
4211
+ const all = this.readAll();
4212
+ if (key in all) {
4213
+ delete all[key];
4214
+ this.writeAll(all);
4215
+ }
4216
+ }
4217
+ /** Clears every pending record in this namespace. */
4218
+ clear() {
4219
+ const ls = this.getLocalStorage();
4220
+ this.memory.clear();
4221
+ if (ls) {
4222
+ try {
4223
+ ls.removeItem(this.storageKey);
4224
+ }
4225
+ catch (error) {
4226
+ defaultLogger.warn(`PendingVerificationStore: failed to clear ${this.storageKey}`, error);
4227
+ }
4228
+ }
4229
+ }
4230
+ pruneExpired(all, exceptKey) {
4231
+ const now = Date.now();
4232
+ for (const [k, v] of Object.entries(all)) {
4233
+ if (k !== exceptKey && now > v.expires) {
4234
+ delete all[k];
4235
+ }
4236
+ }
4237
+ return all;
4238
+ }
4239
+ }
4240
+
3275
4241
  class MagicLinkProvider {
3276
4242
  constructor(config) {
3277
4243
  this.name = 'magic-link';
3278
- this.pendingVerification = new Map();
4244
+ // Persisted (SSR-guarded localStorage) so a magic link clicked from an email — which opens a
4245
+ // FRESH page load with empty in-memory state — can still find its pending entry to verify
4246
+ // against. Keyed by the link token (already present in the callback URL); we store only the
4247
+ // email + expiry, never any additional secret (see PendingVerificationStore + F-11).
4248
+ this.pendingVerification = new PendingVerificationStore('magic-link');
3279
4249
  // Initialize with config
3280
4250
  this.config = config;
3281
4251
  // Check for magic link callback on initialization
@@ -3283,15 +4253,17 @@ Note: This provider requires a backend service to handle authentication.
3283
4253
  }
3284
4254
  async signIn(options) {
3285
4255
  if (!(options === null || options === void 0 ? void 0 : options.email)) {
3286
- throw new AuthError('EMAIL_REQUIRED', 'Email is required for magic link authentication');
4256
+ throw new AuthError(exports.AuthErrorCode.EMAIL_REQUIRED, 'Email is required for magic link authentication');
3287
4257
  }
3288
4258
  try {
3289
4259
  // Send magic link to email
3290
4260
  const token = this.generateToken();
3291
4261
  const magicLink = this.generateMagicLink(token);
3292
- // Store pending verification
4262
+ // Store pending verification (persisted; email + expiry only, keyed by the link token).
3293
4263
  this.pendingVerification.set(token, {
3294
- email: options.email,
4264
+ identifier: options.email,
4265
+ sessionId: token,
4266
+ attempts: 0,
3295
4267
  expires: Date.now() + 15 * 60 * 1000, // 15 minutes
3296
4268
  });
3297
4269
  // Send email via backend API
@@ -3308,7 +4280,7 @@ Note: This provider requires a backend service to handle authentication.
3308
4280
  }),
3309
4281
  });
3310
4282
  if (!response.ok) {
3311
- throw new AuthError('SEND_LINK_FAILED', 'Failed to send magic link');
4283
+ throw new AuthError(exports.AuthErrorCode.SEND_LINK_FAILED, 'Failed to send magic link');
3312
4284
  }
3313
4285
  // Return partial auth result for pending state
3314
4286
  const tempUser = {
@@ -3342,18 +4314,22 @@ Note: This provider requires a backend service to handle authentication.
3342
4314
  };
3343
4315
  }
3344
4316
  catch (error) {
3345
- throw new AuthError('MAGIC_LINK_ERROR', error.message || 'Failed to send magic link');
4317
+ if (error instanceof AuthError)
4318
+ throw error;
4319
+ throw new AuthError(exports.AuthErrorCode.SEND_LINK_FAILED, error.message || 'Failed to send magic link');
3346
4320
  }
3347
4321
  }
3348
4322
  async verifyMagicLink(token) {
3349
4323
  const pending = this.pendingVerification.get(token);
3350
4324
  if (!pending) {
3351
- throw new AuthError('INVALID_TOKEN', 'Invalid or expired magic link');
4325
+ throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Invalid or expired magic link');
3352
4326
  }
3353
4327
  if (Date.now() > pending.expires) {
3354
4328
  this.pendingVerification.delete(token);
3355
- throw new AuthError('TOKEN_EXPIRED', 'Magic link has expired');
4329
+ throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Magic link has expired');
3356
4330
  }
4331
+ // The persisted record stores the email under `identifier`.
4332
+ const email = pending.identifier;
3357
4333
  try {
3358
4334
  // Verify token with backend if configured
3359
4335
  if (this.config.verifyUrl) {
@@ -3364,27 +4340,27 @@ Note: This provider requires a backend service to handle authentication.
3364
4340
  },
3365
4341
  body: JSON.stringify({
3366
4342
  token,
3367
- email: pending.email,
4343
+ email: email,
3368
4344
  clientId: this.config.clientId,
3369
4345
  }),
3370
4346
  });
3371
4347
  if (!response.ok) {
3372
- throw new AuthError('VERIFICATION_FAILED', 'Failed to verify magic link');
4348
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, 'Failed to verify magic link');
3373
4349
  }
3374
4350
  const data = await response.json();
3375
4351
  // Create user from verified data
3376
4352
  const user = {
3377
- uid: data.uid || this.generateUid(pending.email),
3378
- email: pending.email,
3379
- displayName: data.displayName || pending.email.split('@')[0],
4353
+ uid: data.uid || this.generateUid(email),
4354
+ email: email,
4355
+ displayName: data.displayName || email.split('@')[0],
3380
4356
  photoURL: data.photoURL || null,
3381
4357
  emailVerified: true,
3382
4358
  providerData: [
3383
4359
  {
3384
4360
  providerId: this.name,
3385
- uid: data.uid || pending.email,
3386
- displayName: data.displayName || pending.email.split('@')[0],
3387
- email: pending.email,
4361
+ uid: data.uid || email,
4362
+ displayName: data.displayName || email.split('@')[0],
4363
+ email: email,
3388
4364
  phoneNumber: null,
3389
4365
  photoURL: data.photoURL || null,
3390
4366
  },
@@ -3413,17 +4389,17 @@ Note: This provider requires a backend service to handle authentication.
3413
4389
  else {
3414
4390
  // Simple verification without backend
3415
4391
  const user = {
3416
- uid: this.generateUid(pending.email),
3417
- email: pending.email,
3418
- displayName: pending.email.split('@')[0],
4392
+ uid: this.generateUid(email),
4393
+ email: email,
4394
+ displayName: email.split('@')[0],
3419
4395
  photoURL: null,
3420
4396
  emailVerified: true,
3421
4397
  providerData: [
3422
4398
  {
3423
4399
  providerId: this.name,
3424
- uid: pending.email,
3425
- displayName: pending.email.split('@')[0],
3426
- email: pending.email,
4400
+ uid: email,
4401
+ displayName: email.split('@')[0],
4402
+ email: email,
3427
4403
  phoneNumber: null,
3428
4404
  photoURL: null,
3429
4405
  },
@@ -3450,7 +4426,9 @@ Note: This provider requires a backend service to handle authentication.
3450
4426
  }
3451
4427
  }
3452
4428
  catch (error) {
3453
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify magic link');
4429
+ if (error instanceof AuthError)
4430
+ throw error;
4431
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify magic link');
3454
4432
  }
3455
4433
  }
3456
4434
  async signOut() {
@@ -3462,7 +4440,7 @@ Note: This provider requires a backend service to handle authentication.
3462
4440
  return null;
3463
4441
  }
3464
4442
  async refreshToken() {
3465
- throw new AuthError('NOT_SUPPORTED', 'Token refresh is not supported for magic link authentication');
4443
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Token refresh is not supported for magic link authentication');
3466
4444
  }
3467
4445
  generateToken() {
3468
4446
  const array = new Uint8Array(32);
@@ -3520,10 +4498,10 @@ Note: This provider requires a backend service to handle authentication.
3520
4498
  return !!this.config.sendLinkUrl;
3521
4499
  }
3522
4500
  async linkAccount(_options) {
3523
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for magic link authentication');
4501
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for magic link authentication');
3524
4502
  }
3525
4503
  async unlinkAccount(_options) {
3526
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for magic link authentication');
4504
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for magic link authentication');
3527
4505
  }
3528
4506
  async revokeAccess(_token) {
3529
4507
  // Magic link doesn't have persistent access to revoke
@@ -3539,14 +4517,17 @@ Note: This provider requires a backend service to handle authentication.
3539
4517
  class SMSProvider {
3540
4518
  constructor(config) {
3541
4519
  this.name = 'sms';
3542
- this.pendingVerifications = new Map();
4520
+ // Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
4521
+ // page change between sending and verifying the code. Only non-secret metadata is stored —
4522
+ // never the SMS code itself (see PendingVerificationStore + F-11).
4523
+ this.pendingVerifications = new PendingVerificationStore('sms');
3543
4524
  this.MAX_ATTEMPTS = 3;
3544
4525
  // Initialize with config
3545
4526
  this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, config);
3546
4527
  }
3547
4528
  async signIn(options) {
3548
4529
  if (!(options === null || options === void 0 ? void 0 : options.phoneNumber)) {
3549
- throw new AuthError('PHONE_REQUIRED', 'Phone number is required for SMS authentication');
4530
+ throw new AuthError(exports.AuthErrorCode.PHONE_REQUIRED, 'Phone number is required for SMS authentication');
3550
4531
  }
3551
4532
  // If code is provided, verify it
3552
4533
  if (options.code) {
@@ -3565,7 +4546,7 @@ Note: This provider requires a backend service to handle authentication.
3565
4546
  const timeSinceLastResend = Date.now() - existing.lastResent;
3566
4547
  if (timeSinceLastResend < this.config.resendDelay) {
3567
4548
  const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
3568
- throw new AuthError('RESEND_DELAY', `Please wait ${waitTime} seconds before requesting a new code`);
4549
+ throw new AuthError(exports.AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
3569
4550
  }
3570
4551
  }
3571
4552
  // Send SMS code via backend
@@ -3582,12 +4563,12 @@ Note: This provider requires a backend service to handle authentication.
3582
4563
  });
3583
4564
  if (!response.ok) {
3584
4565
  const error = await response.json().catch(() => ({}));
3585
- throw new AuthError('SEND_CODE_FAILED', error.message || 'Failed to send SMS code');
4566
+ throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
3586
4567
  }
3587
4568
  const data = await response.json();
3588
- // Store pending verification
4569
+ // Store pending verification (persisted; metadata only, never the code).
3589
4570
  this.pendingVerifications.set(formattedPhone, {
3590
- phoneNumber: formattedPhone,
4571
+ identifier: formattedPhone,
3591
4572
  sessionId: data.sessionId,
3592
4573
  expires: Date.now() + 10 * 60 * 1000, // 10 minutes
3593
4574
  attempts: 0,
@@ -3630,26 +4611,27 @@ Note: This provider requires a backend service to handle authentication.
3630
4611
  catch (error) {
3631
4612
  if (error instanceof AuthError)
3632
4613
  throw error;
3633
- throw new AuthError('SMS_ERROR', error.message || 'Failed to send SMS code');
4614
+ throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
3634
4615
  }
3635
4616
  }
3636
4617
  async verifyCode(phoneNumber, code) {
3637
4618
  const formattedPhone = this.formatPhoneNumber(phoneNumber);
3638
4619
  const pending = this.pendingVerifications.get(formattedPhone);
3639
4620
  if (!pending) {
3640
- throw new AuthError('NO_PENDING_VERIFICATION', 'No pending SMS verification found');
4621
+ throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending SMS verification found');
3641
4622
  }
3642
4623
  if (Date.now() > pending.expires) {
3643
4624
  this.pendingVerifications.delete(formattedPhone);
3644
- throw new AuthError('CODE_EXPIRED', 'SMS code has expired');
4625
+ throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'SMS code has expired');
3645
4626
  }
3646
4627
  if (pending.attempts >= this.MAX_ATTEMPTS) {
3647
4628
  this.pendingVerifications.delete(formattedPhone);
3648
- throw new AuthError('TOO_MANY_ATTEMPTS', 'Too many failed attempts');
4629
+ throw new AuthError(exports.AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts');
3649
4630
  }
3650
4631
  try {
3651
- // Increment attempts
4632
+ // Increment attempts and persist the bump (so the count survives a reload mid-flow).
3652
4633
  pending.attempts++;
4634
+ this.pendingVerifications.set(formattedPhone, pending);
3653
4635
  // Verify code with backend
3654
4636
  const response = await fetch(this.config.verifyCodeUrl, {
3655
4637
  method: 'POST',
@@ -3666,9 +4648,9 @@ Note: This provider requires a backend service to handle authentication.
3666
4648
  if (!response.ok) {
3667
4649
  const error = await response.json().catch(() => ({}));
3668
4650
  if (response.status === 401) {
3669
- throw new AuthError('INVALID_CODE', 'Invalid SMS code');
4651
+ throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid SMS code');
3670
4652
  }
3671
- throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to verify SMS code');
4653
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
3672
4654
  }
3673
4655
  const data = await response.json();
3674
4656
  // Create user from verified data
@@ -3714,7 +4696,7 @@ Note: This provider requires a backend service to handle authentication.
3714
4696
  catch (error) {
3715
4697
  if (error instanceof AuthError)
3716
4698
  throw error;
3717
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify SMS code');
4699
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
3718
4700
  }
3719
4701
  }
3720
4702
  async signOut() {
@@ -3726,8 +4708,9 @@ Note: This provider requires a backend service to handle authentication.
3726
4708
  return null;
3727
4709
  }
3728
4710
  async refreshToken(_options) {
3729
- // Token refresh would be implemented based on backend requirements
3730
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh is not yet implemented for SMS authentication');
4711
+ // SMS code authentication is single-use and has no refresh flow; the user must request
4712
+ // a new verification code rather than refresh a token.
4713
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication does not support token refresh; request a new code instead.');
3731
4714
  }
3732
4715
  formatPhoneNumber(phoneNumber) {
3733
4716
  // Remove all non-numeric characters
@@ -3779,10 +4762,10 @@ Note: This provider requires a backend service to handle authentication.
3779
4762
  return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
3780
4763
  }
3781
4764
  async linkAccount(_options) {
3782
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for SMS authentication');
4765
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for SMS authentication');
3783
4766
  }
3784
4767
  async unlinkAccount(_options) {
3785
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for SMS authentication');
4768
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for SMS authentication');
3786
4769
  }
3787
4770
  async revokeAccess(_token) {
3788
4771
  // SMS auth doesn't have persistent access to revoke
@@ -3812,7 +4795,7 @@ Note: This provider requires a backend service to handle authentication.
3812
4795
  }
3813
4796
  async signIn(options) {
3814
4797
  if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3815
- throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
4798
+ throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
3816
4799
  }
3817
4800
  try {
3818
4801
  const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
@@ -3829,9 +4812,9 @@ Note: This provider requires a backend service to handle authentication.
3829
4812
  if (!response.ok) {
3830
4813
  const error = await response.json().catch(() => ({}));
3831
4814
  if (response.status === 401) {
3832
- throw new AuthError('INVALID_CREDENTIALS', 'Invalid email or password');
4815
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid email or password');
3833
4816
  }
3834
- throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
4817
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
3835
4818
  }
3836
4819
  const data = await response.json();
3837
4820
  // Create user object
@@ -3878,24 +4861,24 @@ Note: This provider requires a backend service to handle authentication.
3878
4861
  catch (error) {
3879
4862
  if (error instanceof AuthError)
3880
4863
  throw error;
3881
- throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with email and password');
4864
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with email and password');
3882
4865
  }
3883
4866
  }
3884
4867
  async signUp(options) {
3885
4868
  if (!this.config.allowSignUp) {
3886
- throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
4869
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
3887
4870
  }
3888
4871
  if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3889
- throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
4872
+ throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
3890
4873
  }
3891
4874
  // Validate email
3892
4875
  if (!this.isValidEmail(options.email)) {
3893
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
4876
+ throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
3894
4877
  }
3895
4878
  // Validate password
3896
4879
  const passwordError = this.validatePassword(options.password);
3897
4880
  if (passwordError) {
3898
- throw new AuthError('WEAK_PASSWORD', passwordError);
4881
+ throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
3899
4882
  }
3900
4883
  try {
3901
4884
  const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
@@ -3914,9 +4897,9 @@ Note: This provider requires a backend service to handle authentication.
3914
4897
  if (!response.ok) {
3915
4898
  const error = await response.json().catch(() => ({}));
3916
4899
  if (response.status === 409) {
3917
- throw new AuthError('EMAIL_EXISTS', 'Email already in use');
4900
+ throw new AuthError(exports.AuthErrorCode.EMAIL_ALREADY_IN_USE, 'Email already in use');
3918
4901
  }
3919
- throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
4902
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
3920
4903
  }
3921
4904
  const data = await response.json();
3922
4905
  // Create user object
@@ -3963,7 +4946,7 @@ Note: This provider requires a backend service to handle authentication.
3963
4946
  catch (error) {
3964
4947
  if (error instanceof AuthError)
3965
4948
  throw error;
3966
- throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
4949
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
3967
4950
  }
3968
4951
  }
3969
4952
  async signOut() {
@@ -3993,7 +4976,7 @@ Note: This provider requires a backend service to handle authentication.
3993
4976
  }
3994
4977
  async refreshToken(_options) {
3995
4978
  if (!this.refreshTokenValue) {
3996
- throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
4979
+ throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
3997
4980
  }
3998
4981
  try {
3999
4982
  const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
@@ -4007,7 +4990,7 @@ Note: This provider requires a backend service to handle authentication.
4007
4990
  }),
4008
4991
  });
4009
4992
  if (!response.ok) {
4010
- throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
4993
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
4011
4994
  }
4012
4995
  const data = await response.json();
4013
4996
  // Update tokens
@@ -4029,17 +5012,17 @@ Note: This provider requires a backend service to handle authentication.
4029
5012
  catch (error) {
4030
5013
  if (error instanceof AuthError)
4031
5014
  throw error;
4032
- throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
5015
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
4033
5016
  }
4034
5017
  }
4035
5018
  async updatePassword(currentPassword, newPassword) {
4036
5019
  if (!this.currentUser || !this.authToken) {
4037
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
5020
+ throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
4038
5021
  }
4039
5022
  // Validate new password
4040
5023
  const passwordError = this.validatePassword(newPassword);
4041
5024
  if (passwordError) {
4042
- throw new AuthError('WEAK_PASSWORD', passwordError);
5025
+ throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
4043
5026
  }
4044
5027
  try {
4045
5028
  const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
@@ -4057,20 +5040,20 @@ Note: This provider requires a backend service to handle authentication.
4057
5040
  if (!response.ok) {
4058
5041
  const error = await response.json().catch(() => ({}));
4059
5042
  if (response.status === 401) {
4060
- throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
5043
+ throw new AuthError(exports.AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
4061
5044
  }
4062
- throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
5045
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4063
5046
  }
4064
5047
  }
4065
5048
  catch (error) {
4066
5049
  if (error instanceof AuthError)
4067
5050
  throw error;
4068
- throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
5051
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4069
5052
  }
4070
5053
  }
4071
5054
  async sendPasswordResetEmail(email) {
4072
5055
  if (!this.isValidEmail(email)) {
4073
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
5056
+ throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
4074
5057
  }
4075
5058
  try {
4076
5059
  const response = await fetch(`${this.config.apiUrl}/auth/reset-password`, {
@@ -4085,21 +5068,21 @@ Note: This provider requires a backend service to handle authentication.
4085
5068
  });
4086
5069
  if (!response.ok) {
4087
5070
  const error = await response.json().catch(() => ({}));
4088
- throw new AuthError('RESET_FAILED', error.message || 'Failed to send reset email');
5071
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send reset email');
4089
5072
  }
4090
5073
  }
4091
5074
  catch (error) {
4092
5075
  if (error instanceof AuthError)
4093
5076
  throw error;
4094
- throw new AuthError('RESET_ERROR', error.message || 'Failed to send password reset email');
5077
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset email');
4095
5078
  }
4096
5079
  }
4097
5080
  async sendEmailVerification() {
4098
5081
  if (!this.currentUser || !this.authToken) {
4099
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
5082
+ throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
4100
5083
  }
4101
5084
  if (this.currentUser.emailVerified) {
4102
- throw new AuthError('ALREADY_VERIFIED', 'Email already verified');
5085
+ throw new AuthError(exports.AuthErrorCode.EMAIL_ALREADY_VERIFIED, 'Email already verified');
4103
5086
  }
4104
5087
  try {
4105
5088
  const response = await fetch(`${this.config.apiUrl}/auth/verify-email`, {
@@ -4114,13 +5097,13 @@ Note: This provider requires a backend service to handle authentication.
4114
5097
  });
4115
5098
  if (!response.ok) {
4116
5099
  const error = await response.json().catch(() => ({}));
4117
- throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to send verification email');
5100
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
4118
5101
  }
4119
5102
  }
4120
5103
  catch (error) {
4121
5104
  if (error instanceof AuthError)
4122
5105
  throw error;
4123
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to send verification email');
5106
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
4124
5107
  }
4125
5108
  }
4126
5109
  isValidEmail(email) {
@@ -4155,10 +5138,10 @@ Note: This provider requires a backend service to handle authentication.
4155
5138
  return !!this.config.apiUrl;
4156
5139
  }
4157
5140
  async linkAccount(_options) {
4158
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for email/password authentication');
5141
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for email/password authentication');
4159
5142
  }
4160
5143
  async unlinkAccount(_options) {
4161
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for email/password authentication');
5144
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for email/password authentication');
4162
5145
  }
4163
5146
  async revokeAccess(_token) {
4164
5147
  // For email/password auth, revoking access means signing out
@@ -4175,6 +5158,7 @@ Note: This provider requires a backend service to handle authentication.
4175
5158
  constructor(config = {}) {
4176
5159
  this.name = 'biometric';
4177
5160
  this.biometricAuth = null;
5161
+ this.cryptoKeyPromise = null;
4178
5162
  this.config = Object.assign({ reason: 'Authenticate to access your account', title: 'Authentication Required', subtitle: 'Access your account securely', fallbackTitle: 'Use Passcode', requireRecentAuth: true, recentAuthTimeout: 5 * 60 * 1000 }, config);
4179
5163
  this.storageKey =
4180
5164
  config.storageKey || 'capacitor-auth-biometric-credentials';
@@ -4188,31 +5172,31 @@ Note: This provider requires a backend service to handle authentication.
4188
5172
  this.biometricAuth = BiometricAuth;
4189
5173
  }
4190
5174
  catch (_a) {
4191
- console.warn('Biometric authentication plugin not available');
5175
+ defaultLogger.warn('Biometric authentication plugin not available');
4192
5176
  }
4193
5177
  }
4194
5178
  async signIn(_options) {
4195
5179
  var _a, _b, _c;
4196
5180
  if (!this.biometricAuth) {
4197
- throw new AuthError('BIOMETRIC_NOT_AVAILABLE', 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
5181
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
4198
5182
  }
4199
5183
  try {
4200
5184
  // Check if biometry is available
4201
5185
  const checkResult = await this.biometricAuth.checkBiometry();
4202
5186
  if (!checkResult.isAvailable) {
4203
- throw new AuthError('BIOMETRIC_NOT_AVAILABLE', checkResult.reason ||
5187
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, checkResult.reason ||
4204
5188
  'Biometric authentication is not available on this device');
4205
5189
  }
4206
5190
  // Check if we have stored credentials
4207
5191
  const storedCredentials = await this.getStoredCredentials();
4208
5192
  if (!storedCredentials) {
4209
- throw new AuthError('NO_STORED_CREDENTIALS', 'No stored credentials found. Please sign in with another method first.');
5193
+ throw new AuthError(exports.AuthErrorCode.NO_STORED_CREDENTIALS, 'No stored credentials found. Please sign in with another method first.');
4210
5194
  }
4211
5195
  // Check if recent auth is required
4212
5196
  if (this.config.requireRecentAuth) {
4213
5197
  const timeSinceLastAuth = Date.now() - storedCredentials.lastAuthTime;
4214
5198
  if (timeSinceLastAuth > this.config.recentAuthTimeout) {
4215
- throw new AuthError('AUTH_EXPIRED', 'Authentication expired. Please sign in with another method.');
5199
+ throw new AuthError(exports.AuthErrorCode.REQUIRES_RECENT_LOGIN, 'Authentication expired. Please sign in with another method.');
4216
5200
  }
4217
5201
  }
4218
5202
  // Perform biometric authentication
@@ -4248,17 +5232,17 @@ Note: This provider requires a backend service to handle authentication.
4248
5232
  throw error;
4249
5233
  // Handle biometric errors
4250
5234
  if (error.code === 'userCancel' || ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('cancel'))) {
4251
- throw new AuthError('USER_CANCELLED', 'Authentication cancelled by user');
5235
+ throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Authentication cancelled by user');
4252
5236
  }
4253
5237
  else if (error.code === 'biometryLockout' ||
4254
5238
  ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('lockout'))) {
4255
- throw new AuthError('BIOMETRY_LOCKOUT', 'Too many failed attempts. Biometry is locked.');
5239
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_LOCKOUT, 'Too many failed attempts. Biometry is locked.');
4256
5240
  }
4257
5241
  else if (error.code === 'biometryNotEnrolled' ||
4258
5242
  ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('enrolled'))) {
4259
- throw new AuthError('NOT_ENROLLED', 'No biometric credentials are enrolled');
5243
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_ENROLLED, 'No biometric credentials are enrolled');
4260
5244
  }
4261
- throw new AuthError('BIOMETRIC_ERROR', error.message || 'Biometric authentication failed');
5245
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_AUTHENTICATION_FAILED, error.message || 'Biometric authentication failed');
4262
5246
  }
4263
5247
  }
4264
5248
  async signOut() {
@@ -4322,6 +5306,8 @@ Note: This provider requires a backend service to handle authentication.
4322
5306
  return true;
4323
5307
  }
4324
5308
  async getStoredCredentials() {
5309
+ if (typeof localStorage === 'undefined')
5310
+ return null;
4325
5311
  try {
4326
5312
  const stored = localStorage.getItem(this.storageKey);
4327
5313
  if (!stored)
@@ -4334,25 +5320,118 @@ Note: This provider requires a backend service to handle authentication.
4334
5320
  }
4335
5321
  }
4336
5322
  async storeCredentials(credentials) {
5323
+ if (typeof localStorage === 'undefined') {
5324
+ throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric credential storage is unavailable in this environment');
5325
+ }
4337
5326
  try {
4338
5327
  const encrypted = await this.encrypt(JSON.stringify(credentials));
4339
5328
  localStorage.setItem(this.storageKey, encrypted);
4340
5329
  }
4341
- catch (_a) {
4342
- throw new AuthError('STORAGE_ERROR', 'Failed to store credentials');
5330
+ catch (error) {
5331
+ throw new AuthError(exports.AuthErrorCode.STORAGE_ERROR, 'Failed to store credentials', undefined, { cause: String(error) });
4343
5332
  }
4344
5333
  }
4345
5334
  async clearStoredCredentials() {
4346
- localStorage.removeItem(this.storageKey);
5335
+ if (typeof localStorage !== 'undefined') {
5336
+ localStorage.removeItem(this.storageKey);
5337
+ }
5338
+ }
5339
+ /**
5340
+ * Persistent, non-extractable AES-GCM key kept in IndexedDB so it cannot be read back out by
5341
+ * script — stored biometric credentials are therefore not recoverable by simply reading
5342
+ * localStorage (unlike the previous base64 encoding).
5343
+ */
5344
+ getEncryptionKey() {
5345
+ if (!this.cryptoKeyPromise) {
5346
+ this.cryptoKeyPromise = (async () => {
5347
+ const existing = await this.loadKeyFromIndexedDb();
5348
+ if (existing)
5349
+ return existing;
5350
+ const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
5351
+ await this.saveKeyToIndexedDb(key);
5352
+ return key;
5353
+ })();
5354
+ }
5355
+ return this.cryptoKeyPromise;
5356
+ }
5357
+ openKeyDb() {
5358
+ return new Promise((resolve, reject) => {
5359
+ const req = indexedDB.open('capacitor-auth-keys', 1);
5360
+ req.onupgradeneeded = () => req.result.createObjectStore('keys');
5361
+ req.onsuccess = () => resolve(req.result);
5362
+ req.onerror = () => reject(req.error);
5363
+ });
5364
+ }
5365
+ async loadKeyFromIndexedDb() {
5366
+ if (typeof indexedDB === 'undefined')
5367
+ return null;
5368
+ try {
5369
+ const db = await this.openKeyDb();
5370
+ return await new Promise((resolve) => {
5371
+ const tx = db.transaction('keys', 'readonly');
5372
+ const req = tx.objectStore('keys').get(this.storageKey);
5373
+ req.onsuccess = () => { var _a; return resolve((_a = req.result) !== null && _a !== void 0 ? _a : null); };
5374
+ req.onerror = () => resolve(null);
5375
+ });
5376
+ }
5377
+ catch (_a) {
5378
+ return null;
5379
+ }
5380
+ }
5381
+ async saveKeyToIndexedDb(key) {
5382
+ if (typeof indexedDB === 'undefined')
5383
+ return;
5384
+ try {
5385
+ const db = await this.openKeyDb();
5386
+ await new Promise((resolve) => {
5387
+ const tx = db.transaction('keys', 'readwrite');
5388
+ tx.objectStore('keys').put(key, this.storageKey);
5389
+ tx.oncomplete = () => resolve();
5390
+ tx.onerror = () => resolve();
5391
+ });
5392
+ }
5393
+ catch (_a) {
5394
+ // Best-effort: a fresh key is generated next time if persistence fails.
5395
+ }
4347
5396
  }
4348
- // Simple encryption/decryption (in production, use proper encryption)
5397
+ /**
5398
+ * Encrypts with AES-GCM (Web Crypto). Falls back to base64 ONLY when Web Crypto / IndexedDB
5399
+ * are unavailable (insecure context); the `b64:`/`aes:` prefix tells decrypt() the format.
5400
+ */
4349
5401
  async encrypt(data) {
4350
- // In a real implementation, use Web Crypto API or similar
4351
- return btoa(data);
5402
+ if (typeof crypto === 'undefined' ||
5403
+ !crypto.subtle ||
5404
+ typeof indexedDB === 'undefined') {
5405
+ return `b64:${btoa(data)}`;
5406
+ }
5407
+ const key = await this.getEncryptionKey();
5408
+ const iv = crypto.getRandomValues(new Uint8Array(12));
5409
+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(data));
5410
+ const packed = new Uint8Array(iv.length + ciphertext.byteLength);
5411
+ packed.set(iv, 0);
5412
+ packed.set(new Uint8Array(ciphertext), iv.length);
5413
+ let binary = '';
5414
+ for (let i = 0; i < packed.length; i++) {
5415
+ binary += String.fromCharCode(packed[i]);
5416
+ }
5417
+ return `aes:${btoa(binary)}`;
4352
5418
  }
4353
5419
  async decrypt(data) {
4354
- // In a real implementation, use Web Crypto API or similar
4355
- return atob(data);
5420
+ if (data.startsWith('aes:')) {
5421
+ const key = await this.getEncryptionKey();
5422
+ const binary = atob(data.slice(4));
5423
+ const bytes = new Uint8Array(binary.length);
5424
+ for (let i = 0; i < binary.length; i++) {
5425
+ bytes[i] = binary.charCodeAt(i);
5426
+ }
5427
+ const iv = bytes.slice(0, 12);
5428
+ const ciphertext = bytes.slice(12);
5429
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
5430
+ return new TextDecoder().decode(plaintext);
5431
+ }
5432
+ // Legacy (older versions) or insecure-context fallback: base64-encoded payload.
5433
+ const payload = data.startsWith('b64:') ? data.slice(4) : data;
5434
+ return atob(payload);
4356
5435
  }
4357
5436
  async initialize() {
4358
5437
  // Biometric provider is initialized in constructor
@@ -4364,7 +5443,7 @@ Note: This provider requires a backend service to handle authentication.
4364
5443
  return result.available;
4365
5444
  }
4366
5445
  async linkAccount(_options) {
4367
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for biometric authentication');
5446
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for biometric authentication');
4368
5447
  }
4369
5448
  async unlinkAccount(_options) {
4370
5449
  // Unlinking biometric auth means clearing stored credentials
@@ -4401,9 +5480,9 @@ Note: This provider requires a backend service to handle authentication.
4401
5480
  async signIn(options) {
4402
5481
  return this.performOAuthFlow(options);
4403
5482
  }
4404
- async refreshToken(_options) {
4405
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for Slack provider');
4406
- }
5483
+ // Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
5484
+ // Note: Slack's OAuth 2.0 for public web apps typically doesn't issue refresh tokens.
5485
+ // If no refresh token is available, the base class will throw "No refresh token available".
4407
5486
  getOAuthConfig() {
4408
5487
  return {
4409
5488
  clientId: this.clientId,
@@ -4414,15 +5493,39 @@ Note: This provider requires a backend service to handle authentication.
4414
5493
  additionalParams: this.teamId ? { team: this.teamId } : {},
4415
5494
  };
4416
5495
  }
4417
- async parseUserFromTokenResponse(_response) {
4418
- // In a real implementation, you would parse the user info from the token response
4419
- // or make an additional API call to get user details
5496
+ async parseUserFromTokenResponse(response) {
5497
+ var _a;
5498
+ const accessToken = response.access_token;
5499
+ if (!accessToken) {
5500
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Slack token response did not include an access token; cannot fetch the user profile.', this.provider);
5501
+ }
5502
+ // Fetch the real profile via Slack's OpenID Connect userInfo endpoint.
5503
+ // https://api.slack.com/methods/openid.connect.userInfo
5504
+ let res;
5505
+ try {
5506
+ res = await fetch('https://slack.com/api/openid.connect.userInfo', {
5507
+ method: 'GET',
5508
+ headers: {
5509
+ Authorization: `Bearer ${accessToken}`,
5510
+ Accept: 'application/json',
5511
+ },
5512
+ });
5513
+ }
5514
+ catch (error) {
5515
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach Slack userInfo endpoint', this.provider, error);
5516
+ }
5517
+ // Slack returns HTTP 200 with `{ ok: false, error }` on API-level failures.
5518
+ const data = (await res.json().catch(() => null));
5519
+ if (!res.ok || !data || data.ok === false || !data.sub) {
5520
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, `Failed to fetch Slack user profile${(data === null || data === void 0 ? void 0 : data.error) ? `: ${data.error}` : ''}`, this.provider);
5521
+ }
4420
5522
  return {
4421
- id: 'U1234567890',
4422
- email: 'user@workspace.slack.com',
4423
- name: 'Slack User',
4424
- picture: 'https://ui-avatars.com/api/?name=Slack+User',
4425
- email_verified: true,
5523
+ id: data.sub,
5524
+ sub: data.sub,
5525
+ email: data.email,
5526
+ email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
5527
+ name: data.name,
5528
+ picture: data.picture,
4426
5529
  isNewUser: false,
4427
5530
  };
4428
5531
  }
@@ -4468,10 +5571,10 @@ Note: This provider requires a backend service to handle authentication.
4468
5571
  return true;
4469
5572
  }
4470
5573
  async linkAccount(_options) {
4471
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for Slack provider');
5574
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for Slack provider');
4472
5575
  }
4473
5576
  async unlinkAccount(_options) {
4474
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for Slack provider');
5577
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for Slack provider');
4475
5578
  }
4476
5579
  async revokeAccess(token) {
4477
5580
  await super.revokeAccess(token);
@@ -4510,9 +5613,10 @@ Note: This provider requires a backend service to handle authentication.
4510
5613
  await this.clearStoredData();
4511
5614
  await this.setCurrentUser(null);
4512
5615
  }
4513
- async refreshToken(_options) {
4514
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for LinkedIn provider');
4515
- }
5616
+ // Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
5617
+ // Note: LinkedIn's OAuth 2.0 issues long-lived access tokens (60 days) and typically
5618
+ // doesn't provide refresh tokens for web apps. If no refresh token is available,
5619
+ // the base class will throw "No refresh token available".
4516
5620
  getOAuthConfig() {
4517
5621
  return {
4518
5622
  clientId: this.clientId,
@@ -4522,15 +5626,40 @@ Note: This provider requires a backend service to handle authentication.
4522
5626
  scopes: this.scopes,
4523
5627
  };
4524
5628
  }
4525
- async parseUserFromTokenResponse(_response) {
4526
- // In a real implementation, you would parse the user info from the token response
4527
- // or make an additional API call to get user details
5629
+ async parseUserFromTokenResponse(response) {
5630
+ var _a;
5631
+ const accessToken = response.access_token;
5632
+ if (!accessToken) {
5633
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'LinkedIn token response did not include an access token; cannot fetch the user profile.', this.provider);
5634
+ }
5635
+ // Fetch the real profile via LinkedIn's OpenID Connect userinfo endpoint.
5636
+ // https://learn.microsoft.com/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2
5637
+ let res;
5638
+ try {
5639
+ res = await fetch('https://api.linkedin.com/v2/userinfo', {
5640
+ method: 'GET',
5641
+ headers: {
5642
+ Authorization: `Bearer ${accessToken}`,
5643
+ Accept: 'application/json',
5644
+ },
5645
+ });
5646
+ }
5647
+ catch (error) {
5648
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach LinkedIn userinfo endpoint', this.provider, error);
5649
+ }
5650
+ const data = (await res
5651
+ .json()
5652
+ .catch(() => null));
5653
+ if (!res.ok || !data || !data.sub) {
5654
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Failed to fetch LinkedIn user profile', this.provider);
5655
+ }
4528
5656
  return {
4529
- id: 'linkedin_user_123',
4530
- email: 'user@linkedin.com',
4531
- name: 'LinkedIn User',
4532
- picture: 'https://ui-avatars.com/api/?name=LinkedIn+User',
4533
- email_verified: true,
5657
+ id: data.sub,
5658
+ sub: data.sub,
5659
+ email: data.email,
5660
+ email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
5661
+ name: data.name,
5662
+ picture: data.picture,
4534
5663
  isNewUser: false,
4535
5664
  };
4536
5665
  }
@@ -4577,10 +5706,10 @@ Note: This provider requires a backend service to handle authentication.
4577
5706
  return true;
4578
5707
  }
4579
5708
  async linkAccount(_options) {
4580
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for LinkedIn provider');
5709
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for LinkedIn provider');
4581
5710
  }
4582
5711
  async unlinkAccount(_options) {
4583
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for LinkedIn provider');
5712
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for LinkedIn provider');
4584
5713
  }
4585
5714
  async revokeAccess(token) {
4586
5715
  await super.revokeAccess(token);
@@ -4602,7 +5731,7 @@ Note: This provider requires a backend service to handle authentication.
4602
5731
  }
4603
5732
  async signIn(options) {
4604
5733
  if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4605
- throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
5734
+ throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
4606
5735
  }
4607
5736
  try {
4608
5737
  const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
@@ -4619,9 +5748,9 @@ Note: This provider requires a backend service to handle authentication.
4619
5748
  if (!response.ok) {
4620
5749
  const error = await response.json().catch(() => ({}));
4621
5750
  if (response.status === 401) {
4622
- throw new AuthError('INVALID_CREDENTIALS', 'Invalid username or password');
5751
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid username or password');
4623
5752
  }
4624
- throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
5753
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
4625
5754
  }
4626
5755
  const data = await response.json();
4627
5756
  // Create user object
@@ -4669,29 +5798,29 @@ Note: This provider requires a backend service to handle authentication.
4669
5798
  catch (error) {
4670
5799
  if (error instanceof AuthError)
4671
5800
  throw error;
4672
- throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with username and password');
5801
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with username and password');
4673
5802
  }
4674
5803
  }
4675
5804
  async signUp(options) {
4676
5805
  if (!this.config.allowSignUp) {
4677
- throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
5806
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
4678
5807
  }
4679
5808
  if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4680
- throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
5809
+ throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
4681
5810
  }
4682
5811
  // Validate username
4683
5812
  const usernameError = this.validateUsername(options.username);
4684
5813
  if (usernameError) {
4685
- throw new AuthError('INVALID_USERNAME', usernameError);
5814
+ throw new AuthError(exports.AuthErrorCode.INVALID_USERNAME, usernameError);
4686
5815
  }
4687
5816
  // Validate password
4688
5817
  const passwordError = this.validatePassword(options.password);
4689
5818
  if (passwordError) {
4690
- throw new AuthError('WEAK_PASSWORD', passwordError);
5819
+ throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
4691
5820
  }
4692
5821
  // Validate email if provided
4693
5822
  if (options.email && !this.isValidEmail(options.email)) {
4694
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
5823
+ throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
4695
5824
  }
4696
5825
  try {
4697
5826
  const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
@@ -4711,9 +5840,9 @@ Note: This provider requires a backend service to handle authentication.
4711
5840
  if (!response.ok) {
4712
5841
  const error = await response.json().catch(() => ({}));
4713
5842
  if (response.status === 409) {
4714
- throw new AuthError('USERNAME_EXISTS', 'Username already taken');
5843
+ throw new AuthError(exports.AuthErrorCode.USERNAME_ALREADY_EXISTS, 'Username already taken');
4715
5844
  }
4716
- throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
5845
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
4717
5846
  }
4718
5847
  const data = await response.json();
4719
5848
  // Create user object
@@ -4761,7 +5890,7 @@ Note: This provider requires a backend service to handle authentication.
4761
5890
  catch (error) {
4762
5891
  if (error instanceof AuthError)
4763
5892
  throw error;
4764
- throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
5893
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
4765
5894
  }
4766
5895
  }
4767
5896
  async signOut() {
@@ -4791,7 +5920,7 @@ Note: This provider requires a backend service to handle authentication.
4791
5920
  }
4792
5921
  async refreshToken(_options) {
4793
5922
  if (!this.refreshTokenValue) {
4794
- throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
5923
+ throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
4795
5924
  }
4796
5925
  try {
4797
5926
  const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
@@ -4805,7 +5934,7 @@ Note: This provider requires a backend service to handle authentication.
4805
5934
  }),
4806
5935
  });
4807
5936
  if (!response.ok) {
4808
- throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
5937
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
4809
5938
  }
4810
5939
  const data = await response.json();
4811
5940
  // Update tokens
@@ -4827,136 +5956,769 @@ Note: This provider requires a backend service to handle authentication.
4827
5956
  catch (error) {
4828
5957
  if (error instanceof AuthError)
4829
5958
  throw error;
4830
- throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
5959
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
5960
+ }
5961
+ }
5962
+ async updatePassword(currentPassword, newPassword) {
5963
+ if (!this.currentUser || !this.authToken) {
5964
+ throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
5965
+ }
5966
+ // Validate new password
5967
+ const passwordError = this.validatePassword(newPassword);
5968
+ if (passwordError) {
5969
+ throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
5970
+ }
5971
+ try {
5972
+ const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
5973
+ method: 'POST',
5974
+ headers: {
5975
+ Authorization: `Bearer ${this.authToken}`,
5976
+ 'Content-Type': 'application/json',
5977
+ },
5978
+ body: JSON.stringify({
5979
+ currentPassword,
5980
+ newPassword,
5981
+ clientId: this.config.clientId,
5982
+ }),
5983
+ });
5984
+ if (!response.ok) {
5985
+ const error = await response.json().catch(() => ({}));
5986
+ if (response.status === 401) {
5987
+ throw new AuthError(exports.AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
5988
+ }
5989
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
5990
+ }
5991
+ }
5992
+ catch (error) {
5993
+ if (error instanceof AuthError)
5994
+ throw error;
5995
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
5996
+ }
5997
+ }
5998
+ async checkUsernameAvailability(username) {
5999
+ // Validate username format first
6000
+ const usernameError = this.validateUsername(username);
6001
+ if (usernameError) {
6002
+ return false;
6003
+ }
6004
+ try {
6005
+ const response = await fetch(`${this.config.apiUrl}/auth/check-username`, {
6006
+ method: 'POST',
6007
+ headers: {
6008
+ 'Content-Type': 'application/json',
6009
+ },
6010
+ body: JSON.stringify({
6011
+ username,
6012
+ clientId: this.config.clientId,
6013
+ }),
6014
+ });
6015
+ if (!response.ok) {
6016
+ return false;
6017
+ }
6018
+ const data = await response.json();
6019
+ return data.available || false;
6020
+ }
6021
+ catch (_a) {
6022
+ return false;
6023
+ }
6024
+ }
6025
+ isValidEmail(email) {
6026
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
6027
+ return emailRegex.test(email);
6028
+ }
6029
+ validateUsername(username) {
6030
+ const requirements = this.config.usernameRequirements;
6031
+ if (username.length < requirements.minLength) {
6032
+ return `Username must be at least ${requirements.minLength} characters long`;
6033
+ }
6034
+ if (username.length > requirements.maxLength) {
6035
+ return `Username must be no more than ${requirements.maxLength} characters long`;
6036
+ }
6037
+ if (requirements.allowedCharacters &&
6038
+ !requirements.allowedCharacters.test(username)) {
6039
+ return 'Username contains invalid characters. Only letters, numbers, underscores, and hyphens are allowed';
6040
+ }
6041
+ if (requirements.reservedUsernames &&
6042
+ requirements.reservedUsernames.includes(username.toLowerCase())) {
6043
+ return 'This username is reserved and cannot be used';
6044
+ }
6045
+ return null;
6046
+ }
6047
+ validatePassword(password) {
6048
+ const requirements = this.config.passwordRequirements;
6049
+ if (password.length < requirements.minLength) {
6050
+ return `Password must be at least ${requirements.minLength} characters long`;
6051
+ }
6052
+ if (requirements.requireUppercase && !/[A-Z]/.test(password)) {
6053
+ return 'Password must contain at least one uppercase letter';
6054
+ }
6055
+ if (requirements.requireLowercase && !/[a-z]/.test(password)) {
6056
+ return 'Password must contain at least one lowercase letter';
6057
+ }
6058
+ if (requirements.requireNumbers && !/\d/.test(password)) {
6059
+ return 'Password must contain at least one number';
6060
+ }
6061
+ if (requirements.requireSpecialChars &&
6062
+ !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
6063
+ return 'Password must contain at least one special character';
6064
+ }
6065
+ return null;
6066
+ }
6067
+ async initialize() {
6068
+ // Username/Password provider doesn't require initialization
6069
+ }
6070
+ async isSupported() {
6071
+ // Username/Password auth is supported if we have the required config
6072
+ return !!this.config.apiUrl;
6073
+ }
6074
+ async linkAccount(_options) {
6075
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for username/password authentication');
6076
+ }
6077
+ async unlinkAccount(_options) {
6078
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for username/password authentication');
6079
+ }
6080
+ async revokeAccess(_token) {
6081
+ // For username/password auth, revoking access means signing out
6082
+ await this.signOut();
6083
+ }
6084
+ }
6085
+
6086
+ var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
6087
+ __proto__: null,
6088
+ UsernamePasswordProvider: UsernamePasswordProvider
6089
+ });
6090
+
6091
+ class EmailCodeProvider {
6092
+ constructor(config) {
6093
+ this.name = 'email-code';
6094
+ // Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
6095
+ // page change between sending and verifying the code. Only non-secret metadata is stored —
6096
+ // never the verification code itself (see PendingVerificationStore + F-11).
6097
+ this.pendingVerifications = new PendingVerificationStore('email-code');
6098
+ this.MAX_ATTEMPTS = 3;
6099
+ this.config = Object.assign({ codeLength: 6, resendDelay: 60000, codeExpiration: 10 * 60 * 1000 }, config);
6100
+ }
6101
+ async signIn(options) {
6102
+ if (!(options === null || options === void 0 ? void 0 : options.email)) {
6103
+ throw new AuthError(exports.AuthErrorCode.EMAIL_REQUIRED, 'Email is required for email code authentication');
6104
+ }
6105
+ // Validate email format
6106
+ if (!this.isValidEmail(options.email)) {
6107
+ throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Please enter a valid email address');
6108
+ }
6109
+ // If code is provided, verify it
6110
+ if (options.code) {
6111
+ return this.verifyCode(options.email, options.code);
6112
+ }
6113
+ // Otherwise, send code
6114
+ return this.sendCode(options.email);
6115
+ }
6116
+ async sendCode(email) {
6117
+ try {
6118
+ const normalizedEmail = email.toLowerCase().trim();
6119
+ // Check if we can resend
6120
+ const existing = this.pendingVerifications.get(normalizedEmail);
6121
+ if (existing && existing.lastResent) {
6122
+ const timeSinceLastResend = Date.now() - existing.lastResent;
6123
+ if (timeSinceLastResend < this.config.resendDelay) {
6124
+ const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
6125
+ throw new AuthError(exports.AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
6126
+ }
6127
+ }
6128
+ // Send email code via backend
6129
+ const response = await fetch(this.config.sendCodeUrl, {
6130
+ method: 'POST',
6131
+ headers: {
6132
+ 'Content-Type': 'application/json',
6133
+ },
6134
+ body: JSON.stringify({
6135
+ email: normalizedEmail,
6136
+ clientId: this.config.clientId,
6137
+ codeLength: this.config.codeLength,
6138
+ }),
6139
+ });
6140
+ if (!response.ok) {
6141
+ const error = await response.json().catch(() => ({}));
6142
+ throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6143
+ }
6144
+ const data = await response.json();
6145
+ // Store pending verification (persisted; metadata only, never the code).
6146
+ this.pendingVerifications.set(normalizedEmail, {
6147
+ identifier: normalizedEmail,
6148
+ sessionId: data.sessionId,
6149
+ expires: Date.now() + this.config.codeExpiration,
6150
+ attempts: 0,
6151
+ lastResent: Date.now(),
6152
+ });
6153
+ // Return partial auth result for pending state
6154
+ const tempUser = {
6155
+ uid: `email-code-pending:${data.sessionId}`,
6156
+ email: normalizedEmail,
6157
+ displayName: normalizedEmail.split('@')[0],
6158
+ photoURL: null,
6159
+ phoneNumber: null,
6160
+ emailVerified: false,
6161
+ providerData: [],
6162
+ metadata: {
6163
+ creationTime: new Date().toISOString(),
6164
+ lastSignInTime: new Date().toISOString(),
6165
+ },
6166
+ };
6167
+ return {
6168
+ user: tempUser,
6169
+ credential: {
6170
+ providerId: this.name,
6171
+ signInMethod: 'email-code',
6172
+ accessToken: data.sessionId,
6173
+ },
6174
+ additionalUserInfo: {
6175
+ isNewUser: false,
6176
+ providerId: this.name,
6177
+ profile: {
6178
+ email: normalizedEmail,
6179
+ sessionId: data.sessionId,
6180
+ message: `Verification code sent to ${this.maskEmail(normalizedEmail)}`,
6181
+ pending: true,
6182
+ },
6183
+ },
6184
+ };
6185
+ }
6186
+ catch (error) {
6187
+ if (error instanceof AuthError)
6188
+ throw error;
6189
+ throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6190
+ }
6191
+ }
6192
+ async verifyCode(email, code) {
6193
+ const normalizedEmail = email.toLowerCase().trim();
6194
+ const pending = this.pendingVerifications.get(normalizedEmail);
6195
+ if (!pending) {
6196
+ throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending email verification found. Please request a new code.');
6197
+ }
6198
+ if (Date.now() > pending.expires) {
6199
+ this.pendingVerifications.delete(normalizedEmail);
6200
+ throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
6201
+ }
6202
+ if (pending.attempts >= this.MAX_ATTEMPTS) {
6203
+ this.pendingVerifications.delete(normalizedEmail);
6204
+ throw new AuthError(exports.AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts. Please request a new code.');
6205
+ }
6206
+ try {
6207
+ // Increment attempts and persist the bump (so the count survives a reload mid-flow).
6208
+ pending.attempts++;
6209
+ this.pendingVerifications.set(normalizedEmail, pending);
6210
+ // Verify code with backend
6211
+ const response = await fetch(this.config.verifyCodeUrl, {
6212
+ method: 'POST',
6213
+ headers: {
6214
+ 'Content-Type': 'application/json',
6215
+ },
6216
+ body: JSON.stringify({
6217
+ email: normalizedEmail,
6218
+ code,
6219
+ sessionId: pending.sessionId,
6220
+ clientId: this.config.clientId,
6221
+ }),
6222
+ });
6223
+ if (!response.ok) {
6224
+ const error = await response.json().catch(() => ({}));
6225
+ if (response.status === 401) {
6226
+ throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid verification code');
6227
+ }
6228
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
6229
+ }
6230
+ const data = await response.json();
6231
+ // Create user from verified data
6232
+ const user = {
6233
+ uid: data.uid || this.generateUid(normalizedEmail),
6234
+ email: normalizedEmail,
6235
+ displayName: data.displayName || normalizedEmail.split('@')[0],
6236
+ photoURL: data.photoURL || null,
6237
+ phoneNumber: data.phoneNumber || null,
6238
+ emailVerified: true,
6239
+ providerData: [
6240
+ {
6241
+ providerId: this.name,
6242
+ uid: data.uid || normalizedEmail,
6243
+ displayName: data.displayName || normalizedEmail.split('@')[0],
6244
+ email: normalizedEmail,
6245
+ phoneNumber: null,
6246
+ photoURL: data.photoURL || null,
6247
+ },
6248
+ ],
6249
+ metadata: {
6250
+ creationTime: data.createdAt || new Date().toISOString(),
6251
+ lastSignInTime: new Date().toISOString(),
6252
+ },
6253
+ };
6254
+ // Clean up pending verification
6255
+ this.pendingVerifications.delete(normalizedEmail);
6256
+ return {
6257
+ user,
6258
+ credential: {
6259
+ providerId: this.name,
6260
+ signInMethod: 'email-code',
6261
+ accessToken: data.accessToken,
6262
+ refreshToken: data.refreshToken,
6263
+ expiresAt: data.expiresAt,
6264
+ },
6265
+ additionalUserInfo: {
6266
+ isNewUser: data.isNewUser || false,
6267
+ providerId: this.name,
6268
+ },
6269
+ };
6270
+ }
6271
+ catch (error) {
6272
+ if (error instanceof AuthError)
6273
+ throw error;
6274
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
6275
+ }
6276
+ }
6277
+ async signOut() {
6278
+ this.pendingVerifications.clear();
6279
+ }
6280
+ async getCurrentUser() {
6281
+ return null;
6282
+ }
6283
+ async refreshToken(_options) {
6284
+ // Email code authentication is single-use and has no refresh flow; the user must request
6285
+ // a new verification code rather than refresh a token.
6286
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication does not support token refresh; request a new code instead.');
6287
+ }
6288
+ async initialize() {
6289
+ // Email code provider doesn't require initialization
6290
+ }
6291
+ async isSupported() {
6292
+ return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
6293
+ }
6294
+ async linkAccount(_options) {
6295
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for email code authentication');
6296
+ }
6297
+ async unlinkAccount(_options) {
6298
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for email code authentication');
6299
+ }
6300
+ async revokeAccess(_token) {
6301
+ this.pendingVerifications.clear();
6302
+ }
6303
+ // Public method to resend code
6304
+ async resendCode(email) {
6305
+ return this.sendCode(email);
6306
+ }
6307
+ // Public method to check if can resend
6308
+ canResendCode(email) {
6309
+ const normalizedEmail = email.toLowerCase().trim();
6310
+ const pending = this.pendingVerifications.get(normalizedEmail);
6311
+ if (!pending || !pending.lastResent) {
6312
+ return { canResend: true };
6313
+ }
6314
+ const timeSinceLastResend = Date.now() - pending.lastResent;
6315
+ if (timeSinceLastResend < this.config.resendDelay) {
6316
+ return {
6317
+ canResend: false,
6318
+ waitTime: Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000),
6319
+ };
6320
+ }
6321
+ return { canResend: true };
6322
+ }
6323
+ isValidEmail(email) {
6324
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
6325
+ return emailRegex.test(email);
6326
+ }
6327
+ maskEmail(email) {
6328
+ const [local, domain] = email.split('@');
6329
+ if (local.length <= 2) {
6330
+ return `${local[0]}***@${domain}`;
6331
+ }
6332
+ return `${local[0]}***${local[local.length - 1]}@${domain}`;
6333
+ }
6334
+ generateUid(email) {
6335
+ return `email-code:${email.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
6336
+ }
6337
+ }
6338
+
6339
+ var emailCodeProvider = /*#__PURE__*/Object.freeze({
6340
+ __proto__: null,
6341
+ EmailCodeProvider: EmailCodeProvider
6342
+ });
6343
+
6344
+ class PhonePasswordProvider {
6345
+ constructor(config) {
6346
+ this.name = 'phone-password';
6347
+ this.pendingVerifications = new Map();
6348
+ this.currentUser = null;
6349
+ this.storedAccessToken = null;
6350
+ this.storedRefreshToken = null;
6351
+ this.config = Object.assign({ countryCode: '+1', requirePhoneVerification: false, passwordStrength: {
6352
+ minLength: 8,
6353
+ requireUppercase: true,
6354
+ requireLowercase: true,
6355
+ requireNumbers: true,
6356
+ requireSpecialChars: false,
6357
+ } }, config);
6358
+ }
6359
+ async signIn(options) {
6360
+ const credentials = options === null || options === void 0 ? void 0 : options.credentials;
6361
+ if (!(credentials === null || credentials === void 0 ? void 0 : credentials.phoneNumber) || !(credentials === null || credentials === void 0 ? void 0 : credentials.password)) {
6362
+ throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Phone number and password are required');
6363
+ }
6364
+ const formattedPhone = this.formatPhoneNumber(credentials.phoneNumber);
6365
+ // Handle sign up flow
6366
+ if (options === null || options === void 0 ? void 0 : options.isSignUp) {
6367
+ return this.signUp(formattedPhone, credentials.password);
6368
+ }
6369
+ // Handle phone verification if code is provided
6370
+ if (credentials.code && this.config.requirePhoneVerification) {
6371
+ return this.verifyPhone(formattedPhone, credentials.code, credentials.password);
6372
+ }
6373
+ // Standard sign in
6374
+ return this.performSignIn(formattedPhone, credentials.password);
6375
+ }
6376
+ async performSignIn(phoneNumber, password) {
6377
+ try {
6378
+ const response = await fetch(this.config.signInUrl, {
6379
+ method: 'POST',
6380
+ headers: {
6381
+ 'Content-Type': 'application/json',
6382
+ },
6383
+ body: JSON.stringify({
6384
+ phoneNumber,
6385
+ password,
6386
+ clientId: this.config.clientId,
6387
+ }),
6388
+ });
6389
+ if (!response.ok) {
6390
+ const error = await response.json().catch(() => ({}));
6391
+ if (response.status === 401) {
6392
+ throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid phone number or password');
6393
+ }
6394
+ if (response.status === 403) {
6395
+ throw new AuthError(exports.AuthErrorCode.PHONE_NOT_VERIFIED, 'Please verify your phone number first');
6396
+ }
6397
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
6398
+ }
6399
+ const data = await response.json();
6400
+ return this.createAuthResult(data, phoneNumber);
6401
+ }
6402
+ catch (error) {
6403
+ if (error instanceof AuthError)
6404
+ throw error;
6405
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
6406
+ }
6407
+ }
6408
+ async signUp(phoneNumber, password) {
6409
+ // Validate password strength
6410
+ this.validatePassword(password);
6411
+ try {
6412
+ const response = await fetch(this.config.signUpUrl, {
6413
+ method: 'POST',
6414
+ headers: {
6415
+ 'Content-Type': 'application/json',
6416
+ },
6417
+ body: JSON.stringify({
6418
+ phoneNumber,
6419
+ password,
6420
+ clientId: this.config.clientId,
6421
+ }),
6422
+ });
6423
+ if (!response.ok) {
6424
+ const error = await response.json().catch(() => ({}));
6425
+ if (response.status === 409) {
6426
+ throw new AuthError(exports.AuthErrorCode.PHONE_NUMBER_ALREADY_EXISTS, 'An account with this phone number already exists');
6427
+ }
6428
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
6429
+ }
6430
+ const data = await response.json();
6431
+ // If phone verification is required, send verification code
6432
+ if (this.config.requirePhoneVerification && this.config.sendVerificationUrl) {
6433
+ await this.sendVerificationCode(phoneNumber);
6434
+ return {
6435
+ user: {
6436
+ uid: `phone-pending:${data.sessionId || phoneNumber}`,
6437
+ email: null,
6438
+ displayName: this.maskPhoneNumber(phoneNumber),
6439
+ photoURL: null,
6440
+ phoneNumber,
6441
+ emailVerified: false,
6442
+ providerData: [],
6443
+ metadata: {
6444
+ creationTime: new Date().toISOString(),
6445
+ lastSignInTime: new Date().toISOString(),
6446
+ },
6447
+ },
6448
+ credential: {
6449
+ providerId: this.name,
6450
+ signInMethod: 'phone-password',
6451
+ accessToken: data.sessionId,
6452
+ },
6453
+ additionalUserInfo: {
6454
+ isNewUser: true,
6455
+ providerId: this.name,
6456
+ profile: {
6457
+ phoneNumber,
6458
+ message: 'Phone verification required. Check your SMS.',
6459
+ pending: true,
6460
+ },
6461
+ },
6462
+ };
6463
+ }
6464
+ return this.createAuthResult(data, phoneNumber, true);
6465
+ }
6466
+ catch (error) {
6467
+ if (error instanceof AuthError)
6468
+ throw error;
6469
+ throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
4831
6470
  }
4832
6471
  }
4833
- async updatePassword(currentPassword, newPassword) {
4834
- if (!this.currentUser || !this.authToken) {
4835
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
6472
+ async sendVerificationCode(phoneNumber) {
6473
+ if (!this.config.sendVerificationUrl) {
6474
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
4836
6475
  }
4837
- // Validate new password
4838
- const passwordError = this.validatePassword(newPassword);
4839
- if (passwordError) {
4840
- throw new AuthError('WEAK_PASSWORD', passwordError);
6476
+ const response = await fetch(this.config.sendVerificationUrl, {
6477
+ method: 'POST',
6478
+ headers: {
6479
+ 'Content-Type': 'application/json',
6480
+ },
6481
+ body: JSON.stringify({
6482
+ phoneNumber,
6483
+ clientId: this.config.clientId,
6484
+ }),
6485
+ });
6486
+ if (!response.ok) {
6487
+ const error = await response.json().catch(() => ({}));
6488
+ throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6489
+ }
6490
+ const data = await response.json();
6491
+ this.pendingVerifications.set(phoneNumber, {
6492
+ phoneNumber,
6493
+ sessionId: data.sessionId,
6494
+ expires: Date.now() + 10 * 60 * 1000, // 10 minutes
6495
+ });
6496
+ }
6497
+ async verifyPhone(phoneNumber, code, password) {
6498
+ if (!this.config.verifyPhoneUrl) {
6499
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
6500
+ }
6501
+ const pending = this.pendingVerifications.get(phoneNumber);
6502
+ if (!pending) {
6503
+ throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending phone verification found');
6504
+ }
6505
+ if (Date.now() > pending.expires) {
6506
+ this.pendingVerifications.delete(phoneNumber);
6507
+ throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
4841
6508
  }
4842
6509
  try {
4843
- const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
6510
+ const response = await fetch(this.config.verifyPhoneUrl, {
4844
6511
  method: 'POST',
4845
6512
  headers: {
4846
- Authorization: `Bearer ${this.authToken}`,
4847
6513
  'Content-Type': 'application/json',
4848
6514
  },
4849
6515
  body: JSON.stringify({
4850
- currentPassword,
4851
- newPassword,
6516
+ phoneNumber,
6517
+ code,
6518
+ password,
6519
+ sessionId: pending.sessionId,
4852
6520
  clientId: this.config.clientId,
4853
6521
  }),
4854
6522
  });
4855
6523
  if (!response.ok) {
4856
6524
  const error = await response.json().catch(() => ({}));
4857
6525
  if (response.status === 401) {
4858
- throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
6526
+ throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid verification code');
4859
6527
  }
4860
- throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
6528
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
4861
6529
  }
6530
+ const data = await response.json();
6531
+ this.pendingVerifications.delete(phoneNumber);
6532
+ return this.createAuthResult(data, phoneNumber);
4862
6533
  }
4863
6534
  catch (error) {
4864
6535
  if (error instanceof AuthError)
4865
6536
  throw error;
4866
- throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
6537
+ throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
4867
6538
  }
4868
6539
  }
4869
- async checkUsernameAvailability(username) {
4870
- // Validate username format first
4871
- const usernameError = this.validateUsername(username);
4872
- if (usernameError) {
4873
- return false;
6540
+ async signOut() {
6541
+ this.currentUser = null;
6542
+ this.storedAccessToken = null;
6543
+ this.storedRefreshToken = null;
6544
+ this.pendingVerifications.clear();
6545
+ }
6546
+ async getCurrentUser() {
6547
+ return this.currentUser;
6548
+ }
6549
+ async refreshToken(_options) {
6550
+ if (!this.storedRefreshToken || !this.config.refreshTokenUrl) {
6551
+ throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available or refresh URL not configured');
4874
6552
  }
4875
6553
  try {
4876
- const response = await fetch(`${this.config.apiUrl}/auth/check-username`, {
6554
+ const response = await fetch(this.config.refreshTokenUrl, {
4877
6555
  method: 'POST',
4878
6556
  headers: {
4879
6557
  'Content-Type': 'application/json',
4880
6558
  },
4881
6559
  body: JSON.stringify({
4882
- username,
6560
+ refreshToken: this.storedRefreshToken,
4883
6561
  clientId: this.config.clientId,
4884
6562
  }),
4885
6563
  });
4886
6564
  if (!response.ok) {
4887
- return false;
6565
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Token refresh failed');
4888
6566
  }
4889
6567
  const data = await response.json();
4890
- return data.available || false;
6568
+ this.storedAccessToken = data.accessToken;
6569
+ if (data.refreshToken) {
6570
+ this.storedRefreshToken = data.refreshToken;
6571
+ }
6572
+ if (!this.currentUser) {
6573
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No current user');
6574
+ }
6575
+ return {
6576
+ user: this.currentUser,
6577
+ credential: {
6578
+ providerId: this.name,
6579
+ signInMethod: 'phone-password',
6580
+ accessToken: data.accessToken,
6581
+ refreshToken: data.refreshToken || this.storedRefreshToken,
6582
+ expiresAt: data.expiresAt,
6583
+ },
6584
+ additionalUserInfo: {
6585
+ isNewUser: false,
6586
+ providerId: this.name,
6587
+ },
6588
+ };
4891
6589
  }
4892
- catch (_a) {
4893
- return false;
6590
+ catch (error) {
6591
+ if (error instanceof AuthError)
6592
+ throw error;
6593
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Token refresh failed');
4894
6594
  }
4895
6595
  }
4896
- isValidEmail(email) {
4897
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4898
- return emailRegex.test(email);
6596
+ async initialize() {
6597
+ // Phone password provider doesn't require initialization
4899
6598
  }
4900
- validateUsername(username) {
4901
- const requirements = this.config.usernameRequirements;
4902
- if (username.length < requirements.minLength) {
4903
- return `Username must be at least ${requirements.minLength} characters long`;
4904
- }
4905
- if (username.length > requirements.maxLength) {
4906
- return `Username must be no more than ${requirements.maxLength} characters long`;
4907
- }
4908
- if (requirements.allowedCharacters &&
4909
- !requirements.allowedCharacters.test(username)) {
4910
- return 'Username contains invalid characters. Only letters, numbers, underscores, and hyphens are allowed';
6599
+ async isSupported() {
6600
+ return !!(this.config.signInUrl && this.config.signUpUrl);
6601
+ }
6602
+ async linkAccount(_options) {
6603
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for phone/password authentication');
6604
+ }
6605
+ async unlinkAccount(_options) {
6606
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for phone/password authentication');
6607
+ }
6608
+ async revokeAccess(_token) {
6609
+ await this.signOut();
6610
+ }
6611
+ getAccessToken() {
6612
+ return this.storedAccessToken;
6613
+ }
6614
+ async sendPasswordReset(phoneNumber) {
6615
+ if (!this.config.resetPasswordUrl) {
6616
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Password reset URL not configured');
4911
6617
  }
4912
- if (requirements.reservedUsernames &&
4913
- requirements.reservedUsernames.includes(username.toLowerCase())) {
4914
- return 'This username is reserved and cannot be used';
6618
+ const formattedPhone = this.formatPhoneNumber(phoneNumber);
6619
+ const response = await fetch(this.config.resetPasswordUrl, {
6620
+ method: 'POST',
6621
+ headers: {
6622
+ 'Content-Type': 'application/json',
6623
+ },
6624
+ body: JSON.stringify({
6625
+ phoneNumber: formattedPhone,
6626
+ clientId: this.config.clientId,
6627
+ }),
6628
+ });
6629
+ if (!response.ok) {
6630
+ const error = await response.json().catch(() => ({}));
6631
+ throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset');
4915
6632
  }
4916
- return null;
6633
+ }
6634
+ createAuthResult(data, phoneNumber, isNewUser = false) {
6635
+ const user = {
6636
+ uid: data.uid || this.generateUid(phoneNumber),
6637
+ email: data.email || null,
6638
+ displayName: data.displayName || phoneNumber,
6639
+ photoURL: data.photoURL || null,
6640
+ phoneNumber,
6641
+ emailVerified: false,
6642
+ providerData: [
6643
+ {
6644
+ providerId: this.name,
6645
+ uid: data.uid || phoneNumber,
6646
+ displayName: data.displayName || phoneNumber,
6647
+ email: data.email || null,
6648
+ phoneNumber,
6649
+ photoURL: data.photoURL || null,
6650
+ },
6651
+ ],
6652
+ metadata: {
6653
+ creationTime: data.createdAt || new Date().toISOString(),
6654
+ lastSignInTime: new Date().toISOString(),
6655
+ },
6656
+ };
6657
+ this.currentUser = user;
6658
+ this.storedAccessToken = data.accessToken;
6659
+ this.storedRefreshToken = data.refreshToken;
6660
+ return {
6661
+ user,
6662
+ credential: {
6663
+ providerId: this.name,
6664
+ signInMethod: 'phone-password',
6665
+ accessToken: data.accessToken,
6666
+ refreshToken: data.refreshToken,
6667
+ expiresAt: data.expiresAt,
6668
+ },
6669
+ additionalUserInfo: {
6670
+ isNewUser: data.isNewUser || isNewUser,
6671
+ providerId: this.name,
6672
+ },
6673
+ };
4917
6674
  }
4918
6675
  validatePassword(password) {
4919
- const requirements = this.config.passwordRequirements;
4920
- if (password.length < requirements.minLength) {
4921
- return `Password must be at least ${requirements.minLength} characters long`;
6676
+ const { passwordStrength } = this.config;
6677
+ if (!passwordStrength)
6678
+ return;
6679
+ const errors = [];
6680
+ if (passwordStrength.minLength && password.length < passwordStrength.minLength) {
6681
+ errors.push(`at least ${passwordStrength.minLength} characters`);
4922
6682
  }
4923
- if (requirements.requireUppercase && !/[A-Z]/.test(password)) {
4924
- return 'Password must contain at least one uppercase letter';
6683
+ if (passwordStrength.requireUppercase && !/[A-Z]/.test(password)) {
6684
+ errors.push('an uppercase letter');
4925
6685
  }
4926
- if (requirements.requireLowercase && !/[a-z]/.test(password)) {
4927
- return 'Password must contain at least one lowercase letter';
6686
+ if (passwordStrength.requireLowercase && !/[a-z]/.test(password)) {
6687
+ errors.push('a lowercase letter');
4928
6688
  }
4929
- if (requirements.requireNumbers && !/\d/.test(password)) {
4930
- return 'Password must contain at least one number';
6689
+ if (passwordStrength.requireNumbers && !/\d/.test(password)) {
6690
+ errors.push('a number');
4931
6691
  }
4932
- if (requirements.requireSpecialChars &&
4933
- !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
4934
- return 'Password must contain at least one special character';
6692
+ if (passwordStrength.requireSpecialChars && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
6693
+ errors.push('a special character');
6694
+ }
6695
+ if (errors.length > 0) {
6696
+ throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, `Password must contain ${errors.join(', ')}`);
4935
6697
  }
4936
- return null;
4937
- }
4938
- async initialize() {
4939
- // Username/Password provider doesn't require initialization
4940
- }
4941
- async isSupported() {
4942
- // Username/Password auth is supported if we have the required config
4943
- return !!this.config.apiUrl;
4944
6698
  }
4945
- async linkAccount(_options) {
4946
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for username/password authentication');
6699
+ formatPhoneNumber(phoneNumber) {
6700
+ let cleaned = phoneNumber.replace(/\D/g, '');
6701
+ if (!phoneNumber.startsWith('+')) {
6702
+ if (cleaned.length === 10) {
6703
+ cleaned = '1' + cleaned;
6704
+ }
6705
+ cleaned = this.config.countryCode.replace('+', '') + cleaned;
6706
+ }
6707
+ return '+' + cleaned;
4947
6708
  }
4948
- async unlinkAccount(_options) {
4949
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for username/password authentication');
6709
+ maskPhoneNumber(phoneNumber) {
6710
+ const digits = phoneNumber.replace(/\D/g, '');
6711
+ const lastFour = digits.slice(-4);
6712
+ return `***-***-${lastFour}`;
4950
6713
  }
4951
- async revokeAccess(_token) {
4952
- // For username/password auth, revoking access means signing out
4953
- await this.signOut();
6714
+ generateUid(phoneNumber) {
6715
+ return `phone-password:${phoneNumber.replace(/\D/g, '')}`;
4954
6716
  }
4955
6717
  }
4956
6718
 
4957
- var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
6719
+ var phonePasswordProvider = /*#__PURE__*/Object.freeze({
4958
6720
  __proto__: null,
4959
- UsernamePasswordProvider: UsernamePasswordProvider
6721
+ PhonePasswordProvider: PhonePasswordProvider
4960
6722
  });
4961
6723
 
4962
6724
  class ProviderFactory {
@@ -4974,57 +6736,32 @@ Note: This provider requires a backend service to handle authentication.
4974
6736
  case exports.AuthProvider.APPLE:
4975
6737
  return new AppleAuthProviderWeb(providerConfig);
4976
6738
  case exports.AuthProvider.MICROSOFT:
4977
- // TODO: Implement Microsoft provider
4978
- logger.warn('Microsoft provider not yet implemented');
4979
- return null;
6739
+ return new MicrosoftAuthProviderWeb(providerConfig);
4980
6740
  case exports.AuthProvider.FACEBOOK:
4981
- // TODO: Implement Facebook provider
4982
- logger.warn('Facebook provider not yet implemented');
4983
- return null;
6741
+ return new FacebookAuthProviderWeb(providerConfig);
4984
6742
  case exports.AuthProvider.GITHUB:
4985
- // TODO: Implement GitHub provider
4986
- logger.warn('GitHub provider not yet implemented');
4987
- return null;
6743
+ return new GitHubAuthProviderWeb(providerConfig);
4988
6744
  case exports.AuthProvider.SLACK:
4989
- // TODO: Implement Slack provider
4990
- logger.warn('Slack provider not yet implemented');
4991
- return null;
6745
+ return new SlackProvider(providerConfig);
4992
6746
  case exports.AuthProvider.LINKEDIN:
4993
- // TODO: Implement LinkedIn provider
4994
- logger.warn('LinkedIn provider not yet implemented');
4995
- return null;
6747
+ return new LinkedInProvider(providerConfig);
4996
6748
  case exports.AuthProvider.FIREBASE:
4997
- // TODO: Implement Firebase provider
4998
- logger.warn('Firebase provider not yet implemented');
4999
- return null;
6749
+ return new FirebaseAuthProviderWeb(providerConfig);
6750
+ // Standalone providers with their own config types
5000
6751
  case exports.AuthProvider.EMAIL_MAGIC_LINK:
5001
- // TODO: Implement Email Magic Link provider
5002
- logger.warn('Email Magic Link provider not yet implemented');
5003
- return null;
6752
+ return new MagicLinkProvider(config.options);
5004
6753
  case exports.AuthProvider.SMS:
5005
- // TODO: Implement SMS provider
5006
- logger.warn('SMS provider not yet implemented');
5007
- return null;
6754
+ return new SMSProvider(config.options);
5008
6755
  case exports.AuthProvider.EMAIL_PASSWORD:
5009
- // TODO: Implement Email/Password provider
5010
- logger.warn('Email/Password provider not yet implemented');
5011
- return null;
5012
- case exports.AuthProvider.PHONE_PASSWORD:
5013
- // TODO: Implement Phone/Password provider
5014
- logger.warn('Phone/Password provider not yet implemented');
5015
- return null;
6756
+ return new EmailPasswordProvider(config.options);
5016
6757
  case exports.AuthProvider.USERNAME_PASSWORD:
5017
- // TODO: Implement Username/Password provider
5018
- logger.warn('Username/Password provider not yet implemented');
5019
- return null;
5020
- case exports.AuthProvider.EMAIL_CODE:
5021
- // TODO: Implement Email Code provider
5022
- logger.warn('Email Code provider not yet implemented');
5023
- return null;
6758
+ return new UsernamePasswordProvider(config.options);
5024
6759
  case exports.AuthProvider.BIOMETRIC:
5025
- // TODO: Implement Biometric provider
5026
- logger.warn('Biometric provider not yet implemented');
5027
- return null;
6760
+ return new BiometricProvider(config.options);
6761
+ case exports.AuthProvider.PHONE_PASSWORD:
6762
+ return new PhonePasswordProvider(config.options);
6763
+ case exports.AuthProvider.EMAIL_CODE:
6764
+ return new EmailCodeProvider(config.options);
5028
6765
  default:
5029
6766
  logger.error(`Unknown provider: ${config.provider}`);
5030
6767
  return null;
@@ -5088,6 +6825,7 @@ Note: This provider requires a backend service to handle authentication.
5088
6825
  }
5089
6826
  }
5090
6827
  async signIn(options) {
6828
+ var _a;
5091
6829
  this.validateInitialized();
5092
6830
  const provider = this.getProvider(options.provider);
5093
6831
  try {
@@ -5097,7 +6835,7 @@ Note: This provider requires a backend service to handle authentication.
5097
6835
  this.currentProvider = options.provider;
5098
6836
  await this.storage.set('last_auth_provider', options.provider);
5099
6837
  // Setup token refresh if needed
5100
- if (this.autoRefreshToken && result.credential.refreshToken) {
6838
+ if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
5101
6839
  this.setupTokenRefresh(options.provider, result.credential);
5102
6840
  }
5103
6841
  // Forward auth state change
@@ -5123,8 +6861,9 @@ Note: This provider requires a backend service to handle authentication.
5123
6861
  // Sign out from current provider
5124
6862
  const provider = this.getProvider(this.currentProvider);
5125
6863
  await provider.signOut(options);
5126
- // Cancel token refresh
5127
- this.cancelTokenRefresh(this.currentProvider);
6864
+ // Untargeted sign-out: clear ALL refresh timers, not just the current provider's, so
6865
+ // no orphaned timers remain for previously-active providers (F-18).
6866
+ this.cancelAllTokenRefresh();
5128
6867
  // Clear current provider
5129
6868
  this.currentProvider = null;
5130
6869
  await this.storage.remove('last_auth_provider');
@@ -5140,6 +6879,8 @@ Note: This provider requires a backend service to handle authentication.
5140
6879
  this.logger.error(`Failed to sign out from ${providerId}`, error);
5141
6880
  }
5142
6881
  }
6882
+ // Defensive: clear any remaining timers (e.g. for providers that errored above).
6883
+ this.cancelAllTokenRefresh();
5143
6884
  this.currentProvider = null;
5144
6885
  await this.storage.remove('last_auth_provider');
5145
6886
  }
@@ -5157,26 +6898,39 @@ Note: This provider requires a backend service to handle authentication.
5157
6898
  const provider = this.getProvider(this.currentProvider);
5158
6899
  return provider.getCurrentUser();
5159
6900
  }
5160
- // Try to get user from any provider
5161
- for (const provider of this.providers.values()) {
5162
- const user = await provider.getCurrentUser();
5163
- if (user) {
5164
- return user;
6901
+ // Try to get user from any provider. A not-yet-initialized provider can throw from
6902
+ // getCurrentUser() (it lazily initializes), so isolate each and skip failures.
6903
+ for (const [providerId, provider] of this.providers.entries()) {
6904
+ try {
6905
+ const user = await provider.getCurrentUser();
6906
+ if (user) {
6907
+ // Remember which provider owns the active session for subsequent calls.
6908
+ this.currentProvider = providerId;
6909
+ return user;
6910
+ }
6911
+ }
6912
+ catch (error) {
6913
+ this.logger.debug(`getCurrentUser: provider ${providerId} threw; skipping`, error);
6914
+ continue;
5165
6915
  }
5166
6916
  }
5167
6917
  return null;
5168
6918
  }
5169
6919
  async refreshToken(options) {
6920
+ var _a;
5170
6921
  this.validateInitialized();
5171
6922
  const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
5172
6923
  if (!providerId) {
5173
6924
  throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for token refresh');
5174
6925
  }
5175
6926
  const provider = this.getProvider(providerId);
6927
+ if (!provider.refreshToken) {
6928
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Token refresh not supported for provider ${providerId}`);
6929
+ }
5176
6930
  try {
5177
6931
  const result = await provider.refreshToken(options);
5178
6932
  // Setup new token refresh
5179
- if (this.autoRefreshToken && result.credential.refreshToken) {
6933
+ if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
5180
6934
  this.setupTokenRefresh(providerId, result.credential);
5181
6935
  }
5182
6936
  return result;
@@ -5200,10 +6954,11 @@ Note: This provider requires a backend service to handle authentication.
5200
6954
  return handle;
5201
6955
  }
5202
6956
  async removeAllListeners() {
6957
+ var _a;
5203
6958
  this.authStateEmitter.clear();
5204
6959
  // Also clear provider listeners
5205
6960
  for (const provider of this.providers.values()) {
5206
- provider.dispose();
6961
+ (_a = provider.dispose) === null || _a === void 0 ? void 0 : _a.call(provider);
5207
6962
  }
5208
6963
  }
5209
6964
  async isSupported(options) {
@@ -5244,6 +6999,9 @@ Note: This provider requires a backend service to handle authentication.
5244
6999
  async linkAccount(options) {
5245
7000
  this.validateInitialized();
5246
7001
  const provider = this.getProvider(options.provider);
7002
+ if (!provider.linkAccount) {
7003
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking not supported for provider ${options.provider}`);
7004
+ }
5247
7005
  try {
5248
7006
  return await provider.linkAccount(options);
5249
7007
  }
@@ -5255,6 +7013,9 @@ Note: This provider requires a backend service to handle authentication.
5255
7013
  async unlinkAccount(options) {
5256
7014
  this.validateInitialized();
5257
7015
  const provider = this.getProvider(options.provider);
7016
+ if (!provider.unlinkAccount) {
7017
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking not supported for provider ${options.provider}`);
7018
+ }
5258
7019
  try {
5259
7020
  await provider.unlinkAccount(options);
5260
7021
  }
@@ -5263,65 +7024,203 @@ Note: This provider requires a backend service to handle authentication.
5263
7024
  throw AuthError.fromError(error, options.provider);
5264
7025
  }
5265
7026
  }
5266
- async sendPasswordResetEmail(_options) {
7027
+ async sendPasswordResetEmail(options) {
5267
7028
  this.validateInitialized();
5268
- // This would typically be implemented by specific providers
5269
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Password reset not implemented for current provider');
7029
+ // Try email-password provider first
7030
+ const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
7031
+ if (emailPasswordProvider && 'sendPasswordReset' in emailPasswordProvider) {
7032
+ const provider = emailPasswordProvider;
7033
+ await provider.sendPasswordReset(options.email);
7034
+ return;
7035
+ }
7036
+ // Try phone-password provider
7037
+ const phonePasswordProvider = this.providers.get(exports.AuthProvider.PHONE_PASSWORD);
7038
+ if (phonePasswordProvider && 'sendPasswordReset' in phonePasswordProvider) {
7039
+ const provider = phonePasswordProvider;
7040
+ await provider.sendPasswordReset(options.email);
7041
+ return;
7042
+ }
7043
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Password reset requires email-password or phone-password provider to be configured');
5270
7044
  }
5271
7045
  async sendEmailVerification(_options) {
5272
7046
  this.validateInitialized();
5273
- // This would typically be implemented by specific providers
5274
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email verification not implemented for current provider');
7047
+ // Email verification is typically handled by email-password provider
7048
+ const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
7049
+ if (emailPasswordProvider && 'sendEmailVerification' in emailPasswordProvider) {
7050
+ const provider = emailPasswordProvider;
7051
+ await provider.sendEmailVerification();
7052
+ return;
7053
+ }
7054
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email verification requires email-password provider to be configured');
5275
7055
  }
5276
- async sendSmsCode(_options) {
7056
+ async sendSmsCode(options) {
5277
7057
  this.validateInitialized();
5278
- // This would typically be implemented by SMS provider
5279
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication not implemented');
7058
+ // Delegate to SMS provider
7059
+ const smsProvider = this.providers.get(exports.AuthProvider.SMS);
7060
+ if (smsProvider && 'sendCode' in smsProvider) {
7061
+ const provider = smsProvider;
7062
+ await provider.sendCode(options.phoneNumber);
7063
+ return;
7064
+ }
7065
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
5280
7066
  }
5281
- async verifySmsCode(_options) {
7067
+ async verifySmsCode(options) {
5282
7068
  this.validateInitialized();
5283
- // This would typically be implemented by SMS provider
5284
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication not implemented');
7069
+ // Delegate to SMS provider
7070
+ const smsProvider = this.providers.get(exports.AuthProvider.SMS);
7071
+ if (smsProvider && 'verifyCode' in smsProvider) {
7072
+ const provider = smsProvider;
7073
+ return await provider.verifyCode(options.phoneNumber, options.code);
7074
+ }
7075
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
5285
7076
  }
5286
- async sendEmailCode(_options) {
7077
+ async sendEmailCode(options) {
5287
7078
  this.validateInitialized();
5288
- // This would typically be implemented by email code provider
5289
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication not implemented');
7079
+ // Delegate to email-code provider
7080
+ const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
7081
+ if (emailCodeProvider) {
7082
+ // The email-code provider's signIn accepts { email } to send the code
7083
+ await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email } });
7084
+ return;
7085
+ }
7086
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
5290
7087
  }
5291
- async verifyEmailCode(_options) {
7088
+ async verifyEmailCode(options) {
5292
7089
  this.validateInitialized();
5293
- // This would typically be implemented by email code provider
5294
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication not implemented');
7090
+ // Delegate to email-code provider
7091
+ const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
7092
+ if (emailCodeProvider) {
7093
+ // The email-code provider's signIn accepts { email, code } to verify
7094
+ return await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email, code: options.code } });
7095
+ }
7096
+ throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
5295
7097
  }
5296
- async updateProfile(_options) {
7098
+ async updateProfile(options) {
5297
7099
  this.validateInitialized();
5298
7100
  if (!this.currentProvider) {
5299
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No authenticated user found');
7101
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
7102
+ }
7103
+ const provider = this.providers.get(this.currentProvider);
7104
+ if (!provider) {
7105
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Current provider not found');
7106
+ }
7107
+ // Check if provider supports updateProfile
7108
+ if ('updateProfile' in provider && typeof provider.updateProfile === 'function') {
7109
+ const updateFn = provider.updateProfile;
7110
+ return await updateFn(options);
7111
+ }
7112
+ // Fallback: update cached user info locally
7113
+ const currentUser = await this.getCurrentUser();
7114
+ if (!currentUser) {
7115
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
7116
+ }
7117
+ // Update local user data
7118
+ 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 });
7119
+ // Persist the updated user so it survives a reload — providers that extend BaseAuthProvider
7120
+ // read the cached user from `${provider}_current_user` on init (F-36). Without this the
7121
+ // fallback only emitted the change in-memory and it reverted on the next page load.
7122
+ await this.persistFallbackUser(updatedUser);
7123
+ this.authStateEmitter.emit(updatedUser);
7124
+ return updatedUser;
7125
+ }
7126
+ /**
7127
+ * Writes an updated user back to storage under the same key BaseAuthProvider uses
7128
+ * (`${provider}_current_user`) for the active provider, so the local profile change survives a
7129
+ * reload even when the provider has no native `updateProfile`. Best-effort: storage failures are
7130
+ * logged, not thrown, since the in-memory update already succeeded.
7131
+ */
7132
+ async persistFallbackUser(user) {
7133
+ if (!this.currentProvider) {
7134
+ return;
7135
+ }
7136
+ try {
7137
+ await this.storage.set(`${this.currentProvider}_current_user`, user);
7138
+ }
7139
+ catch (error) {
7140
+ this.logger.error(`Failed to persist updated profile for ${this.currentProvider}`, error);
5300
7141
  }
5301
- // This would typically be implemented by specific providers
5302
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Profile update not implemented for current provider');
5303
7142
  }
5304
- async deleteAccount(_options) {
7143
+ async deleteAccount(options) {
5305
7144
  this.validateInitialized();
5306
- if (!this.currentProvider) {
5307
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No authenticated user found');
7145
+ const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
7146
+ if (!providerId) {
7147
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
7148
+ }
7149
+ const provider = this.providers.get(providerId);
7150
+ if (!provider) {
7151
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Provider not found');
5308
7152
  }
5309
- // This would typically be implemented by specific providers
5310
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account deletion not implemented for current provider');
7153
+ // Check if provider supports account deletion
7154
+ if ('deleteAccount' in provider && typeof provider.deleteAccount === 'function') {
7155
+ const deleteFn = provider.deleteAccount;
7156
+ await deleteFn();
7157
+ await this.signOut();
7158
+ return;
7159
+ }
7160
+ // If provider doesn't support deletion, revoke access and sign out
7161
+ if ('revokeAccess' in provider && typeof provider.revokeAccess === 'function') {
7162
+ const revokeFn = provider.revokeAccess;
7163
+ await revokeFn();
7164
+ }
7165
+ await this.signOut();
5311
7166
  }
5312
7167
  async getIdToken(options) {
7168
+ var _a;
5313
7169
  this.validateInitialized();
5314
7170
  const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
5315
7171
  if (!providerId) {
5316
7172
  throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for ID token');
5317
7173
  }
5318
- // This would typically be implemented by specific providers
5319
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'ID token retrieval not implemented for current provider');
5320
- }
7174
+ const provider = this.providers.get(providerId);
7175
+ if (!provider) {
7176
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, `Provider ${providerId} not configured`);
7177
+ }
7178
+ // Check if provider has getIdToken method
7179
+ if ('getIdToken' in provider && typeof provider.getIdToken === 'function') {
7180
+ const getIdTokenFn = provider.getIdToken;
7181
+ return await getIdTokenFn((_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
7182
+ }
7183
+ // Try to get ID token from stored credential. The storage layer (WebStorage/
7184
+ // CapacitorPreferencesStorage) already JSON-parses on read, so the value is the
7185
+ // parsed credential object — do NOT JSON.parse it again.
7186
+ const parsed = (await this.storage.get(`${providerId}_credential`));
7187
+ if (parsed) {
7188
+ if (parsed.idToken) {
7189
+ // Check if token needs refresh
7190
+ if ((options === null || options === void 0 ? void 0 : options.forceRefresh) ||
7191
+ (parsed.expiresAt && parsed.expiresAt < Date.now())) {
7192
+ // Try to refresh
7193
+ if (provider.refreshToken) {
7194
+ const result = await provider.refreshToken({
7195
+ provider: providerId,
7196
+ forceRefresh: true,
7197
+ });
7198
+ if (result.credential.idToken) {
7199
+ return result.credential.idToken;
7200
+ }
7201
+ }
7202
+ }
7203
+ else {
7204
+ return parsed.idToken;
7205
+ }
7206
+ }
7207
+ }
7208
+ 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.`);
7209
+ }
7210
+ /**
7211
+ * Persists provider-specific custom OAuth parameters.
7212
+ *
7213
+ * IMPORTANT (F-35): the underlying OAuth flow applies custom parameters that are passed directly
7214
+ * to {@link signIn} (`signIn({ provider, options: { customParameters } })`). The values stored
7215
+ * here are NOT automatically merged into a later `signIn` authorization URL — read them back and
7216
+ * pass them to `signIn` if you need them applied. The stored value is the raw parameters object
7217
+ * (the storage layer serializes it); it is not double JSON-encoded.
7218
+ */
5321
7219
  async setCustomParameters(options) {
5322
7220
  this.validateInitialized();
5323
- // Store custom parameters for the provider
5324
- await this.storage.set(`${options.provider}_custom_params`, JSON.stringify(options.parameters));
7221
+ // Store the raw object — WebStorage/CapacitorPreferencesStorage serialize on write, so passing
7222
+ // a pre-stringified value here would double-encode it.
7223
+ await this.storage.set(`${options.provider}_custom_params`, options.parameters);
5325
7224
  }
5326
7225
  async revokeAccess(options) {
5327
7226
  this.validateInitialized();
@@ -5330,6 +7229,9 @@ Note: This provider requires a backend service to handle authentication.
5330
7229
  throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for access revocation');
5331
7230
  }
5332
7231
  const provider = this.getProvider(providerId);
7232
+ if (!provider.revokeAccess) {
7233
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation not supported for provider ${providerId}`);
7234
+ }
5333
7235
  try {
5334
7236
  await provider.revokeAccess(options === null || options === void 0 ? void 0 : options.token);
5335
7237
  }
@@ -5355,13 +7257,18 @@ Note: This provider requires a backend service to handle authentication.
5355
7257
  // Dynamically import provider implementation
5356
7258
  const provider = await this.createProvider(config);
5357
7259
  if (provider) {
5358
- await provider.initialize();
5359
- // Forward auth state changes
5360
- provider.addAuthStateListener((user) => {
5361
- if (user) {
5362
- this.authStateEmitter.emit(user);
5363
- }
5364
- });
7260
+ // Initialize if the provider supports it
7261
+ if (provider.initialize) {
7262
+ await provider.initialize(config.options);
7263
+ }
7264
+ // Forward auth state changes if provider supports it (BaseAuthProvider only)
7265
+ if ('addAuthStateListener' in provider && typeof provider.addAuthStateListener === 'function') {
7266
+ provider.addAuthStateListener((user) => {
7267
+ if (user) {
7268
+ this.authStateEmitter.emit(user);
7269
+ }
7270
+ });
7271
+ }
5365
7272
  this.providers.set(config.provider, provider);
5366
7273
  this.logger.info(`Provider ${config.provider} initialized`);
5367
7274
  }
@@ -5384,16 +7291,34 @@ Note: This provider requires a backend service to handle authentication.
5384
7291
  }
5385
7292
  const refreshTime = credential.expiresAt - this.tokenRefreshBuffer - Date.now();
5386
7293
  if (refreshTime > 0) {
5387
- const timer = setTimeout(async () => {
7294
+ this.scheduleRefresh(provider, refreshTime);
7295
+ }
7296
+ }
7297
+ /**
7298
+ * Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
7299
+ * (2,147,483,647 ms ≈ 24.8 days). A far-future `expiresAt` would otherwise overflow the timer
7300
+ * and fire almost immediately (refresh storm). When clamped, the timer reschedules the remaining
7301
+ * wait on fire instead of refreshing early (F-17).
7302
+ */
7303
+ scheduleRefresh(provider, delayMs) {
7304
+ const MAX_TIMEOUT = 2147483647;
7305
+ const clamped = Math.min(delayMs, MAX_TIMEOUT);
7306
+ const timer = setTimeout(() => {
7307
+ const remaining = delayMs - clamped;
7308
+ if (remaining > 0) {
7309
+ this.scheduleRefresh(provider, remaining);
7310
+ return;
7311
+ }
7312
+ void (async () => {
5388
7313
  try {
5389
7314
  await this.refreshToken({ provider });
5390
7315
  }
5391
7316
  catch (error) {
5392
7317
  this.logger.error(`Auto token refresh failed for ${provider}`, error);
5393
7318
  }
5394
- }, refreshTime);
5395
- this.tokenRefreshTimers.set(provider, timer);
5396
- }
7319
+ })();
7320
+ }, clamped);
7321
+ this.tokenRefreshTimers.set(provider, timer);
5397
7322
  }
5398
7323
  cancelTokenRefresh(provider) {
5399
7324
  const timer = this.tokenRefreshTimers.get(provider);
@@ -5402,6 +7327,13 @@ Note: This provider requires a backend service to handle authentication.
5402
7327
  this.tokenRefreshTimers.delete(provider);
5403
7328
  }
5404
7329
  }
7330
+ /** Clears every active refresh timer (used on a global, untargeted sign-out). */
7331
+ cancelAllTokenRefresh() {
7332
+ for (const timer of this.tokenRefreshTimers.values()) {
7333
+ clearTimeout(timer);
7334
+ }
7335
+ this.tokenRefreshTimers.clear();
7336
+ }
5405
7337
  }
5406
7338
 
5407
7339
  var web = /*#__PURE__*/Object.freeze({
@@ -5411,8 +7343,12 @@ Note: This provider requires a backend service to handle authentication.
5411
7343
 
5412
7344
  exports.AuthError = AuthError;
5413
7345
  exports.CapacitorAuthManager = CapacitorAuthManager;
7346
+ exports.CapacitorPreferencesStorage = CapacitorPreferencesStorage;
7347
+ exports.Logger = Logger;
5414
7348
  exports.PlatformDetector = PlatformDetector;
7349
+ exports.WebStorage = WebStorage;
5415
7350
  exports.auth = auth;
7351
+ exports.defaultLogger = defaultLogger;
5416
7352
  exports.isAuthError = isAuthError;
5417
7353
 
5418
7354
  return exports;