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