capacitor-auth-manager 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CapacitorAuthManager.podspec +1 -1
  2. package/Readme.md +223 -103
  3. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +28 -0
  4. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +109 -15
  5. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/FacebookAuthProvider.java +389 -0
  6. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +353 -0
  7. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/MicrosoftAuthProvider.java +455 -0
  8. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +180 -0
  9. package/dist/angular.cjs.js +7017 -0
  10. package/dist/angular.cjs.js.map +1 -0
  11. package/dist/core.cjs.js +2155 -444
  12. package/dist/core.cjs.js.map +1 -1
  13. package/dist/esm/angular/auth.guard.d.ts +18 -0
  14. package/dist/esm/angular/auth.guard.js +82 -0
  15. package/dist/esm/angular/auth.guard.js.map +1 -0
  16. package/dist/esm/angular/auth.module.d.ts +18 -0
  17. package/dist/esm/angular/auth.module.js +56 -0
  18. package/dist/esm/angular/auth.module.js.map +1 -0
  19. package/dist/esm/angular/auth.service.d.ts +108 -0
  20. package/dist/esm/angular/auth.service.js +224 -0
  21. package/dist/esm/angular/auth.service.js.map +1 -0
  22. package/dist/esm/angular/index.d.ts +3 -0
  23. package/dist/esm/angular/index.js +4 -0
  24. package/dist/esm/angular/index.js.map +1 -0
  25. package/dist/esm/core/auth-manager.d.ts +61 -1
  26. package/dist/esm/core/auth-manager.js +285 -24
  27. package/dist/esm/core/auth-manager.js.map +1 -1
  28. package/dist/esm/core/platform.d.ts +7 -0
  29. package/dist/esm/core/platform.js +30 -10
  30. package/dist/esm/core/platform.js.map +1 -1
  31. package/dist/esm/core/provider-manifests.d.ts +9 -0
  32. package/dist/esm/core/provider-manifests.js +471 -0
  33. package/dist/esm/core/provider-manifests.js.map +1 -0
  34. package/dist/esm/core/provider-registry.d.ts +19 -1
  35. package/dist/esm/core/provider-registry.js +72 -480
  36. package/dist/esm/core/provider-registry.js.map +1 -1
  37. package/dist/esm/core/types.d.ts +18 -7
  38. package/dist/esm/definitions.d.ts +42 -1
  39. package/dist/esm/definitions.js +28 -0
  40. package/dist/esm/definitions.js.map +1 -1
  41. package/dist/esm/index.d.ts +4 -0
  42. package/dist/esm/index.js +6 -0
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/providers/base-provider.d.ts +3 -3
  45. package/dist/esm/providers/base-provider.js +26 -1
  46. package/dist/esm/providers/base-provider.js.map +1 -1
  47. package/dist/esm/providers/oauth-provider.d.ts +23 -2
  48. package/dist/esm/providers/oauth-provider.js +134 -17
  49. package/dist/esm/providers/oauth-provider.js.map +1 -1
  50. package/dist/esm/providers/provider-factory.d.ts +3 -1
  51. package/dist/esm/providers/provider-factory.js +29 -41
  52. package/dist/esm/providers/provider-factory.js.map +1 -1
  53. package/dist/esm/providers/web/apple-provider.d.ts +2 -1
  54. package/dist/esm/providers/web/apple-provider.js +25 -9
  55. package/dist/esm/providers/web/apple-provider.js.map +1 -1
  56. package/dist/esm/providers/web/biometric-provider.d.ts +14 -0
  57. package/dist/esm/providers/web/biometric-provider.js +116 -18
  58. package/dist/esm/providers/web/biometric-provider.js.map +1 -1
  59. package/dist/esm/providers/web/email-code-provider.d.ts +48 -0
  60. package/dist/esm/providers/web/email-code-provider.js +295 -0
  61. package/dist/esm/providers/web/email-code-provider.js.map +1 -0
  62. package/dist/esm/providers/web/email-password-provider.js +29 -28
  63. package/dist/esm/providers/web/email-password-provider.js.map +1 -1
  64. package/dist/esm/providers/web/facebook-provider.d.ts +52 -1
  65. package/dist/esm/providers/web/facebook-provider.js +2 -2
  66. package/dist/esm/providers/web/facebook-provider.js.map +1 -1
  67. package/dist/esm/providers/web/firebase-provider.d.ts +5 -3
  68. package/dist/esm/providers/web/firebase-provider.js +74 -42
  69. package/dist/esm/providers/web/firebase-provider.js.map +1 -1
  70. package/dist/esm/providers/web/github-provider.d.ts +9 -0
  71. package/dist/esm/providers/web/github-provider.js +91 -14
  72. package/dist/esm/providers/web/github-provider.js.map +1 -1
  73. package/dist/esm/providers/web/index.d.ts +2 -0
  74. package/dist/esm/providers/web/index.js +2 -0
  75. package/dist/esm/providers/web/index.js.map +1 -1
  76. package/dist/esm/providers/web/linkedin-provider.d.ts +2 -3
  77. package/dist/esm/providers/web/linkedin-provider.js +40 -14
  78. package/dist/esm/providers/web/linkedin-provider.js.map +1 -1
  79. package/dist/esm/providers/web/magic-link-provider.d.ts +3 -3
  80. package/dist/esm/providers/web/magic-link-provider.js +40 -26
  81. package/dist/esm/providers/web/magic-link-provider.js.map +1 -1
  82. package/dist/esm/providers/web/microsoft-provider.d.ts +2 -0
  83. package/dist/esm/providers/web/microsoft-provider.js +45 -20
  84. package/dist/esm/providers/web/microsoft-provider.js.map +1 -1
  85. package/dist/esm/providers/web/phone-password-provider.d.ts +66 -0
  86. package/dist/esm/providers/web/phone-password-provider.js +438 -0
  87. package/dist/esm/providers/web/phone-password-provider.js.map +1 -0
  88. package/dist/esm/providers/web/slack-provider.d.ts +2 -3
  89. package/dist/esm/providers/web/slack-provider.js +38 -14
  90. package/dist/esm/providers/web/slack-provider.js.map +1 -1
  91. package/dist/esm/providers/web/sms-provider.d.ts +3 -3
  92. package/dist/esm/providers/web/sms-provider.js +25 -18
  93. package/dist/esm/providers/web/sms-provider.js.map +1 -1
  94. package/dist/esm/providers/web/username-password-provider.js +23 -22
  95. package/dist/esm/providers/web/username-password-provider.js.map +1 -1
  96. package/dist/esm/react/hooks.d.ts +110 -0
  97. package/dist/esm/react/hooks.js +307 -0
  98. package/dist/esm/react/hooks.js.map +1 -0
  99. package/dist/esm/react/index.d.ts +2 -0
  100. package/dist/esm/react/index.js +3 -0
  101. package/dist/esm/react/index.js.map +1 -0
  102. package/dist/esm/react/types.d.ts +30 -0
  103. package/dist/esm/react/types.js +2 -0
  104. package/dist/esm/react/types.js.map +1 -0
  105. package/dist/esm/utils/auth-error.d.ts +7 -0
  106. package/dist/esm/utils/auth-error.js +31 -5
  107. package/dist/esm/utils/auth-error.js.map +1 -1
  108. package/dist/esm/utils/event-emitter.d.ts +7 -0
  109. package/dist/esm/utils/event-emitter.js +8 -2
  110. package/dist/esm/utils/event-emitter.js.map +1 -1
  111. package/dist/esm/utils/logger.d.ts +28 -1
  112. package/dist/esm/utils/logger.js +115 -1
  113. package/dist/esm/utils/logger.js.map +1 -1
  114. package/dist/esm/utils/pending-verification-store.d.ts +59 -0
  115. package/dist/esm/utils/pending-verification-store.js +103 -0
  116. package/dist/esm/utils/pending-verification-store.js.map +1 -0
  117. package/dist/esm/utils/storage.d.ts +29 -1
  118. package/dist/esm/utils/storage.js +64 -5
  119. package/dist/esm/utils/storage.js.map +1 -1
  120. package/dist/esm/vue/composables.d.ts +124 -0
  121. package/dist/esm/vue/composables.js +290 -0
  122. package/dist/esm/vue/composables.js.map +1 -0
  123. package/dist/esm/vue/index.d.ts +1 -0
  124. package/dist/esm/vue/index.js +2 -0
  125. package/dist/esm/vue/index.js.map +1 -0
  126. package/dist/esm/web.d.ts +32 -7
  127. package/dist/esm/web.js +247 -52
  128. package/dist/esm/web.js.map +1 -1
  129. package/dist/plugin.cjs.js +2606 -670
  130. package/dist/plugin.cjs.js.map +1 -1
  131. package/dist/plugin.js +2606 -670
  132. package/dist/plugin.js.map +1 -1
  133. package/dist/react.cjs.js +6972 -0
  134. package/dist/react.cjs.js.map +1 -0
  135. package/dist/vue.cjs.js +6955 -0
  136. package/dist/vue.cjs.js.map +1 -0
  137. package/ios/Plugin/AppleAuthProvider.swift +288 -0
  138. package/ios/Plugin/AuthStorage.swift +49 -1
  139. package/ios/Plugin/CapacitorAuthManager.swift +45 -23
  140. package/ios/Plugin/FacebookAuthProvider.swift +297 -0
  141. package/ios/Plugin/GitHubAuthProvider.swift +54 -0
  142. package/ios/Plugin/GoogleAuthProvider.swift +265 -0
  143. package/ios/Plugin/LinkedInAuthProvider.swift +63 -0
  144. package/ios/Plugin/MicrosoftAuthProvider.swift +315 -0
  145. package/ios/Plugin/Models.swift +4 -1
  146. package/ios/Plugin/OAuthWebProvider.swift +415 -0
  147. package/ios/Plugin/SlackAuthProvider.swift +108 -0
  148. package/package.json +60 -39
package/dist/core.cjs.js CHANGED
@@ -1,42 +1,65 @@
1
1
  'use strict';
2
2
 
3
- class EventEmitter {
4
- constructor() {
5
- this.listeners = new Set();
6
- }
7
- emit(data) {
8
- this.listeners.forEach((listener) => {
9
- try {
10
- listener(data);
11
- }
12
- catch (error) {
13
- console.error('Error in event listener:', error);
14
- }
15
- });
16
- }
17
- subscribe(listener) {
18
- this.listeners.add(listener);
19
- return () => {
20
- this.listeners.delete(listener);
21
- };
22
- }
23
- clear() {
24
- this.listeners.clear();
25
- }
26
- get listenerCount() {
27
- return this.listeners.size;
28
- }
3
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
+ /**
5
+ * Reads a default log level from the build/runtime environment WITHOUT assuming a particular
6
+ * bundler or host. Checked defensively (each access wrapped) so it is safe in:
7
+ * - Vite / bundlers that define `import.meta.env`
8
+ * - Node / SSR where `globalThis.process.env` exists
9
+ * - Plain browsers where neither is present (falls back to 'warn')
10
+ *
11
+ * Intentional omissions for a PUBLISHED LIBRARY (see F-42):
12
+ * - We do NOT patch the host application's global `console.*`. A library silencing the host's
13
+ * console would be hostile and surprising.
14
+ * - We do NOT read the host's `localStorage` for a log-level switch. The host owns its storage;
15
+ * the consumer configures logging explicitly via `auth.configure({ logLevel })` or
16
+ * `logger.setLevel()`.
17
+ */
18
+ function readEnvLogLevel() {
19
+ var _a;
20
+ const candidates = [];
21
+ try {
22
+ // import.meta.env may not exist (CJS) — guard the whole access.
23
+ const metaEnv = (_a = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('core.cjs.js', document.baseURI).href)) })) === null || _a === void 0 ? void 0 : _a.env;
24
+ if (metaEnv) {
25
+ candidates.push(metaEnv.VITE_LOG_LEVEL, metaEnv.LOG_LEVEL);
26
+ }
27
+ }
28
+ catch (_b) {
29
+ // import.meta unsupported in this environment — ignore.
30
+ }
31
+ try {
32
+ const proc = globalThis.process;
33
+ if (proc === null || proc === void 0 ? void 0 : proc.env) {
34
+ candidates.push(proc.env.VITE_LOG_LEVEL, proc.env.LOG_LEVEL);
35
+ }
36
+ }
37
+ catch (_c) {
38
+ // process not available — ignore.
39
+ }
40
+ for (const value of candidates) {
41
+ if (value === 'debug' ||
42
+ value === 'info' ||
43
+ value === 'warn' ||
44
+ value === 'error' ||
45
+ value === 'silent') {
46
+ return value;
47
+ }
48
+ }
49
+ return undefined;
29
50
  }
30
-
31
51
  class Logger {
32
52
  constructor(config) {
53
+ var _a, _b;
33
54
  this.logLevels = {
34
55
  debug: 0,
35
56
  info: 1,
36
57
  warn: 2,
37
58
  error: 3,
59
+ silent: 4,
38
60
  };
39
- this.config = config;
61
+ // An explicit logLevel from the caller wins; otherwise fall back to the env default, then 'warn'.
62
+ this.config = Object.assign(Object.assign({}, config), { logLevel: (_b = (_a = config.logLevel) !== null && _a !== void 0 ? _a : readEnvLogLevel()) !== null && _b !== void 0 ? _b : 'warn' });
40
63
  }
41
64
  shouldLog(level) {
42
65
  if (!this.config.enableLogging)
@@ -68,13 +91,110 @@ class Logger {
68
91
  console.error(this.formatMessage('error', message), error);
69
92
  }
70
93
  }
94
+ /** Verbose tracing — gated at `debug` level like {@link debug}. */
95
+ trace(message, ...args) {
96
+ if (this.shouldLog('debug')) {
97
+ console.trace(this.formatMessage('trace', message), ...args);
98
+ }
99
+ }
100
+ /** Tabular output — gated at `debug` level. Falls back to `debug` when `console.table` is absent. */
101
+ table(data, columns) {
102
+ if (this.shouldLog('debug')) {
103
+ if (typeof console.table === 'function') {
104
+ console.table(data, columns);
105
+ }
106
+ else {
107
+ console.debug(this.formatMessage('table', ''), data);
108
+ }
109
+ }
110
+ }
111
+ /** Opens a console group — gated at `debug` level. No-ops if `console.group` is absent. */
112
+ group(label) {
113
+ if (this.shouldLog('debug') && typeof console.group === 'function') {
114
+ console.group(label ? this.formatMessage('group', label) : undefined);
115
+ }
116
+ }
117
+ /** Closes a console group opened by {@link group}. */
118
+ groupEnd() {
119
+ if (this.shouldLog('debug') && typeof console.groupEnd === 'function') {
120
+ console.groupEnd();
121
+ }
122
+ }
123
+ /** Starts a timer — gated at `debug` level. No-ops if `console.time` is absent. */
124
+ time(label) {
125
+ if (this.shouldLog('debug') && typeof console.time === 'function') {
126
+ console.time(label);
127
+ }
128
+ }
129
+ /** Stops a timer started by {@link time} and logs the elapsed duration. */
130
+ timeEnd(label) {
131
+ if (this.shouldLog('debug') && typeof console.timeEnd === 'function') {
132
+ console.timeEnd(label);
133
+ }
134
+ }
71
135
  setLogLevel(level) {
72
136
  this.config.logLevel = level;
73
137
  }
138
+ /** Alias for {@link setLogLevel} matching the workspace logger convention. */
139
+ setLevel(level) {
140
+ this.config.logLevel = level;
141
+ }
142
+ getLevel() {
143
+ return this.config.logLevel;
144
+ }
74
145
  setEnabled(enabled) {
75
146
  this.config.enableLogging = enabled;
76
147
  }
77
148
  }
149
+ /**
150
+ * Shared default logger instance used by package internals that don't receive a logger via
151
+ * dependency injection (e.g. {@link EventEmitter}, {@link WebStorage} defaults, the biometric
152
+ * provider). Enabled by default at `warn` level so only warnings + errors surface unless the
153
+ * consumer raises the level. Consumers can adjust it programmatically:
154
+ *
155
+ * ```ts
156
+ * import { defaultLogger } from 'capacitor-auth-manager';
157
+ * defaultLogger.setLevel('debug');
158
+ * ```
159
+ */
160
+ const defaultLogger = new Logger({
161
+ enableLogging: true,
162
+ logLevel: 'warn',
163
+ prefix: 'CapacitorAuthManager',
164
+ });
165
+
166
+ class EventEmitter {
167
+ /**
168
+ * @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
169
+ * so emitter errors honour the package log level instead of writing to `console` directly.
170
+ */
171
+ constructor(logger = defaultLogger) {
172
+ this.listeners = new Set();
173
+ this.logger = logger;
174
+ }
175
+ emit(data) {
176
+ this.listeners.forEach((listener) => {
177
+ try {
178
+ listener(data);
179
+ }
180
+ catch (error) {
181
+ this.logger.error('Error in event listener:', error);
182
+ }
183
+ });
184
+ }
185
+ subscribe(listener) {
186
+ this.listeners.add(listener);
187
+ return () => {
188
+ this.listeners.delete(listener);
189
+ };
190
+ }
191
+ clear() {
192
+ this.listeners.clear();
193
+ }
194
+ get listenerCount() {
195
+ return this.listeners.size;
196
+ }
197
+ }
78
198
 
79
199
  var AuthProvider;
80
200
  (function (AuthProvider) {
@@ -188,11 +308,46 @@ var AuthErrorCode;
188
308
  AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
189
309
  AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
190
310
  AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
311
+ // --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
312
+ // magic-link / biometric / email-password / username-password / phone-password) throw enum
313
+ // codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
314
+ AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
315
+ AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
316
+ AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
317
+ AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
318
+ AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
319
+ AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
320
+ AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
321
+ AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
322
+ AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
323
+ AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
324
+ AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
325
+ AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
326
+ AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
327
+ AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
328
+ AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
329
+ AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
330
+ AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
331
+ AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
332
+ AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
333
+ AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
334
+ AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
335
+ AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
336
+ AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
337
+ AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
338
+ AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
191
339
  })(AuthErrorCode || (AuthErrorCode = {}));
192
340
 
193
341
  class WebStorage {
194
- constructor(persistence = AuthPersistence.LOCAL, prefix = 'cap_auth_') {
342
+ /**
343
+ * @param persistence Where to persist values (local / session / in-memory).
344
+ * @param prefix Key prefix to namespace this package's storage.
345
+ * @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
346
+ * so storage failures honour the package log level instead of writing to `console` directly.
347
+ */
348
+ constructor(persistence = AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
195
349
  this.prefix = prefix;
350
+ this.logger = logger;
196
351
  switch (persistence) {
197
352
  case AuthPersistence.SESSION:
198
353
  this.storage = window.sessionStorage;
@@ -222,7 +377,7 @@ class WebStorage {
222
377
  return null;
223
378
  }
224
379
  catch (error) {
225
- console.error('Storage get error:', error);
380
+ this.logger.error('Storage get error:', error);
226
381
  return null;
227
382
  }
228
383
  }
@@ -232,7 +387,7 @@ class WebStorage {
232
387
  this.storage.setItem(this.prefix + key, stringValue);
233
388
  }
234
389
  catch (error) {
235
- console.error('Storage set error:', error);
390
+ this.logger.error('Storage set error:', error);
236
391
  throw error;
237
392
  }
238
393
  }
@@ -241,7 +396,7 @@ class WebStorage {
241
396
  this.storage.removeItem(this.prefix + key);
242
397
  }
243
398
  catch (error) {
244
- console.error('Storage remove error:', error);
399
+ this.logger.error('Storage remove error:', error);
245
400
  }
246
401
  }
247
402
  async clear() {
@@ -256,7 +411,7 @@ class WebStorage {
256
411
  keys.forEach((key) => this.storage.removeItem(key));
257
412
  }
258
413
  catch (error) {
259
- console.error('Storage clear error:', error);
414
+ this.logger.error('Storage clear error:', error);
260
415
  }
261
416
  }
262
417
  }
@@ -291,11 +446,36 @@ class AuthError extends Error {
291
446
  this.name = 'AuthError';
292
447
  this.code = code;
293
448
  this.provider = provider;
294
- this.details = details;
295
- // Maintains proper stack trace for where our error was thrown (only available on V8)
296
- if (Error.captureStackTrace) {
297
- Error.captureStackTrace(this, AuthError);
449
+ this.details = AuthError.sanitizeDetails(details);
450
+ // Maintains proper stack trace for where our error was thrown (only available on V8 engines:
451
+ // Node.js and Chromium). Typed locally so the package does not depend on @types/node globals.
452
+ const ErrorCtor = Error;
453
+ if (ErrorCtor.captureStackTrace) {
454
+ ErrorCtor.captureStackTrace(this, AuthError);
455
+ }
456
+ }
457
+ /**
458
+ * Produces a safe, shallow `details` object: redacts sensitive keys and keeps only JSON-safe
459
+ * primitives. Prevents tokens/PII embedded in a raw error or token-endpoint response body from
460
+ * being captured into AuthError.details (and thus logged or serialized via toJSON()).
461
+ */
462
+ static sanitizeDetails(input) {
463
+ if (input === null || typeof input !== 'object') {
464
+ return undefined;
465
+ }
466
+ const out = {};
467
+ for (const [key, value] of Object.entries(input)) {
468
+ if (AuthError.SENSITIVE_KEY.test(key)) {
469
+ out[key] = '[redacted]';
470
+ }
471
+ else if (value === null ||
472
+ typeof value === 'string' ||
473
+ typeof value === 'number' ||
474
+ typeof value === 'boolean') {
475
+ out[key] = value;
476
+ }
298
477
  }
478
+ return Object.keys(out).length > 0 ? out : undefined;
299
479
  }
300
480
  static fromError(error, provider) {
301
481
  if (error instanceof AuthError) {
@@ -303,7 +483,7 @@ class AuthError extends Error {
303
483
  }
304
484
  let code = AuthErrorCode.INTERNAL_ERROR;
305
485
  let message = 'An unknown error occurred';
306
- let details = error;
486
+ const details = error;
307
487
  if (error instanceof Error) {
308
488
  message = error.message;
309
489
  // Try to map common error patterns to specific error codes
@@ -338,10 +518,20 @@ class AuthError extends Error {
338
518
  };
339
519
  }
340
520
  }
521
+ AuthError.SENSITIVE_KEY = /(token|secret|password|authorization|code_verifier|client_secret|credential|api[-_]?key|cookie)/i;
341
522
 
523
+ function getPlatformWindow() {
524
+ return typeof window !== 'undefined'
525
+ ? window
526
+ : undefined;
527
+ }
342
528
  class PlatformDetector {
343
529
  static getPlatform() {
344
- if (this.platformInfo) {
530
+ // A cached NON-web result is final (native/electron never reverts to web). But a cached
531
+ // 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
532
+ // module first runs (the native bridge initializes asynchronously), so re-evaluate while
533
+ // the last verdict was 'web' to pick up a late native environment. See F-26.
534
+ if (this.platformInfo && this.platformInfo.platform !== 'web') {
345
535
  return this.platformInfo;
346
536
  }
347
537
  const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
@@ -359,11 +549,21 @@ class PlatformDetector {
359
549
  };
360
550
  return this.platformInfo;
361
551
  }
552
+ /**
553
+ * Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
554
+ * result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
555
+ * initializes late). Most callers can rely on the automatic re-check while the cached value is
556
+ * still 'web'.
557
+ */
558
+ static reset() {
559
+ this.platformInfo = null;
560
+ }
362
561
  static detectPlatform(userAgent) {
363
562
  var _a, _b;
563
+ const win = getPlatformWindow();
364
564
  // Check if running in Capacitor
365
- if (typeof window !== 'undefined' && window.Capacitor) {
366
- const capacitor = window.Capacitor;
565
+ if (win === null || win === void 0 ? void 0 : win.Capacitor) {
566
+ const capacitor = win.Capacitor;
367
567
  if (capacitor.getPlatform) {
368
568
  const platform = capacitor.getPlatform();
369
569
  if (platform === 'ios' || platform === 'android') {
@@ -372,8 +572,7 @@ class PlatformDetector {
372
572
  }
373
573
  }
374
574
  // Check if running in Electron
375
- if (typeof window !== 'undefined' &&
376
- ((_b = (_a = window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron)) {
575
+ 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) {
377
576
  return 'electron';
378
577
  }
379
578
  // Check for React Native
@@ -402,124 +601,34 @@ class PlatformDetector {
402
601
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
403
602
  }
404
603
  static isCapacitorAvailable() {
405
- return typeof window !== 'undefined' && !!window.Capacitor;
604
+ var _a;
605
+ return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
406
606
  }
407
607
  static async checkCapacitorPlugin(pluginName) {
408
- if (!this.isCapacitorAvailable()) {
608
+ var _a;
609
+ const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
610
+ if (!capacitor) {
409
611
  return false;
410
612
  }
411
613
  try {
412
- const { Capacitor } = window;
413
- return !!(Capacitor.Plugins && Capacitor.Plugins[pluginName]);
614
+ return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
414
615
  }
415
- catch (_a) {
616
+ catch (_b) {
416
617
  return false;
417
618
  }
418
619
  }
419
620
  }
420
621
  PlatformDetector.platformInfo = null;
421
622
 
422
- var _a;
423
- class ProviderRegistry {
424
- static registerManifest(manifest) {
425
- this.manifests.set(manifest.name, manifest);
426
- }
427
- static registerLoader(name, loader) {
428
- this.loaders.set(name, loader);
429
- }
430
- static getManifest(name) {
431
- return this.manifests.get(name);
432
- }
433
- static async getProvider(name, config) {
434
- var _b, _c;
435
- // Check if already loaded
436
- const existing = this.providers.get(name);
437
- if (existing) {
438
- return existing;
439
- }
440
- // Check if loader exists
441
- const loader = this.loaders.get(name);
442
- if (!loader) {
443
- const manifest = this.manifests.get(name);
444
- if (manifest) {
445
- throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
446
- }
447
- throw new Error(`Unknown provider: ${name}`);
448
- }
449
- // Check platform support
450
- const manifest = this.manifests.get(name);
451
- if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
452
- const platform = PlatformDetector.getPlatform();
453
- if (!manifest.platforms.includes(platform.platform)) {
454
- throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
455
- }
456
- }
457
- try {
458
- // Load the provider
459
- const module = await loader();
460
- const ProviderClass = module.default;
461
- // Create instance
462
- const provider = new ProviderClass(config);
463
- // Initialize if needed
464
- if (provider.initialize) {
465
- await provider.initialize(config);
466
- }
467
- // Cache the provider
468
- this.providers.set(name, provider);
469
- return provider;
470
- }
471
- catch (error) {
472
- // Check if it's a missing dependency error
473
- if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot find module')) ||
474
- ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Failed to resolve module'))) {
475
- const manifest = this.manifests.get(name);
476
- if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
477
- throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
478
- `Install the required package:\n` +
479
- `npm install ${manifest.packageName}\n\n` +
480
- `Then try again.`);
481
- }
482
- }
483
- throw error;
484
- }
485
- }
486
- static clearProvider(name) {
487
- const provider = this.providers.get(name);
488
- if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
489
- provider.dispose();
490
- }
491
- this.providers.delete(name);
492
- }
493
- static clearAll() {
494
- for (const [, provider] of this.providers) {
495
- if (provider.dispose) {
496
- provider.dispose();
497
- }
498
- }
499
- this.providers.clear();
500
- }
501
- static getAvailableProviders() {
502
- return Array.from(this.manifests.keys());
503
- }
504
- static getSupportedProviders() {
505
- const platform = PlatformDetector.getPlatform();
506
- const supported = [];
507
- for (const [name, manifest] of this.manifests) {
508
- if (!manifest.platforms ||
509
- manifest.platforms.includes(platform.platform)) {
510
- supported.push(name);
511
- }
512
- }
513
- return Promise.resolve(supported);
514
- }
515
- }
516
- _a = ProviderRegistry;
517
- ProviderRegistry.providers = new Map();
518
- ProviderRegistry.loaders = new Map();
519
- ProviderRegistry.manifests = new Map();
520
- (() => {
521
- // Register built-in provider manifests
522
- _a.registerManifest({
623
+ /**
624
+ * Built-in provider manifests (display metadata + human-readable setup instructions).
625
+ *
626
+ * Extracted from `provider-registry.ts` as a pure data module (zero logic) so the registry stays
627
+ * under the project's file-size guideline. `ProviderRegistry` imports this array and registers each
628
+ * entry in its static initializer — behaviour is unchanged (see F-40).
629
+ */
630
+ const BUILT_IN_PROVIDER_MANIFESTS = [
631
+ {
523
632
  name: 'google',
524
633
  displayName: 'Google',
525
634
  packageName: '@google/gsi',
@@ -551,8 +660,8 @@ To use Google authentication, you need to:
551
660
  scopes: { type: 'array', items: 'string' },
552
661
  hostedDomain: { type: 'string' },
553
662
  },
554
- });
555
- _a.registerManifest({
663
+ },
664
+ {
556
665
  name: 'apple',
557
666
  displayName: 'Apple',
558
667
  setupInstructions: `
@@ -580,8 +689,8 @@ To use Apple authentication:
580
689
  redirectUri: { type: 'string', required: true },
581
690
  scopes: { type: 'array', items: 'string' },
582
691
  },
583
- });
584
- _a.registerManifest({
692
+ },
693
+ {
585
694
  name: 'firebase',
586
695
  displayName: 'Firebase Auth',
587
696
  packageName: 'firebase',
@@ -615,8 +724,8 @@ To use Firebase authentication:
615
724
  authDomain: { type: 'string', required: true },
616
725
  projectId: { type: 'string', required: true },
617
726
  },
618
- });
619
- _a.registerManifest({
727
+ },
728
+ {
620
729
  name: 'microsoft',
621
730
  displayName: 'Microsoft',
622
731
  packageName: '@azure/msal-browser',
@@ -650,8 +759,8 @@ To use Microsoft authentication:
650
759
  redirectUri: { type: 'string' },
651
760
  scopes: { type: 'array', items: 'string' },
652
761
  },
653
- });
654
- _a.registerManifest({
762
+ },
763
+ {
655
764
  name: 'facebook',
656
765
  displayName: 'Facebook',
657
766
  setupInstructions: `
@@ -664,7 +773,7 @@ To use Facebook authentication:
664
773
  - Configure OAuth redirect URIs
665
774
 
666
775
  2. Add Facebook SDK to your HTML:
667
- <script async defer crossorigin="anonymous"
776
+ <script async defer crossorigin="anonymous"
668
777
  src="https://connect.facebook.net/en_US/sdk.js"></script>
669
778
 
670
779
  3. Configure the provider:
@@ -683,8 +792,8 @@ To use Facebook authentication:
683
792
  version: { type: 'string' },
684
793
  scopes: { type: 'array', items: 'string' },
685
794
  },
686
- });
687
- _a.registerManifest({
795
+ },
796
+ {
688
797
  name: 'github',
689
798
  displayName: 'GitHub',
690
799
  setupInstructions: `
@@ -713,9 +822,8 @@ Note: You'll need a backend service to exchange the authorization code for an ac
713
822
  redirectUri: { type: 'string' },
714
823
  scopes: { type: 'array', items: 'string' },
715
824
  },
716
- });
717
- // Register all new provider manifests
718
- _a.registerManifest({
825
+ },
826
+ {
719
827
  name: 'magic-link',
720
828
  displayName: 'Email Magic Link',
721
829
  setupInstructions: `
@@ -742,8 +850,8 @@ To use Email Magic Link authentication:
742
850
  verifyUrl: { type: 'string' },
743
851
  redirectUrl: { type: 'string' },
744
852
  },
745
- });
746
- _a.registerManifest({
853
+ },
854
+ {
747
855
  name: 'sms',
748
856
  displayName: 'SMS Authentication',
749
857
  setupInstructions: `
@@ -772,8 +880,8 @@ To use SMS authentication:
772
880
  countryCode: { type: 'string' },
773
881
  codeLength: { type: 'number' },
774
882
  },
775
- });
776
- _a.registerManifest({
883
+ },
884
+ {
777
885
  name: 'email-password',
778
886
  displayName: 'Email & Password',
779
887
  setupInstructions: `
@@ -800,8 +908,8 @@ To use Email/Password authentication:
800
908
  apiUrl: { type: 'string', required: true },
801
909
  passwordRequirements: { type: 'object' },
802
910
  },
803
- });
804
- _a.registerManifest({
911
+ },
912
+ {
805
913
  name: 'biometric',
806
914
  displayName: 'Biometric Authentication',
807
915
  packageName: 'capacitor-biometric-authentication',
@@ -830,8 +938,8 @@ Note: Users must first authenticate with another method before enabling biometri
830
938
  title: { type: 'string' },
831
939
  subtitle: { type: 'string' },
832
940
  },
833
- });
834
- _a.registerManifest({
941
+ },
942
+ {
835
943
  name: 'slack',
836
944
  displayName: 'Slack',
837
945
  setupInstructions: `
@@ -874,8 +982,8 @@ Note: Slack OAuth requires a backend service to exchange the authorization code
874
982
  scopes: { type: 'array', items: 'string' },
875
983
  teamId: { type: 'string' },
876
984
  },
877
- });
878
- _a.registerManifest({
985
+ },
986
+ {
879
987
  name: 'linkedin',
880
988
  displayName: 'LinkedIn',
881
989
  setupInstructions: `
@@ -919,8 +1027,8 @@ The redirect URI must be HTTPS in production (LinkedIn requirement).
919
1027
  redirectUri: { type: 'string', required: true },
920
1028
  scopes: { type: 'array', items: 'string' },
921
1029
  },
922
- });
923
- _a.registerManifest({
1030
+ },
1031
+ {
924
1032
  name: 'username-password',
925
1033
  displayName: 'Username & Password',
926
1034
  setupInstructions: `
@@ -980,7 +1088,153 @@ Note: This provider requires a backend service to handle authentication.
980
1088
  passwordRequirements: { type: 'object' },
981
1089
  allowSignUp: { type: 'boolean' },
982
1090
  },
983
- });
1091
+ },
1092
+ ];
1093
+
1094
+ var _a;
1095
+ class ProviderRegistry {
1096
+ static registerManifest(manifest) {
1097
+ this.manifests.set(manifest.name, manifest);
1098
+ }
1099
+ static registerLoader(name, loader) {
1100
+ this.loaders.set(name, loader);
1101
+ }
1102
+ static getManifest(name) {
1103
+ return this.manifests.get(name);
1104
+ }
1105
+ static canonicalName(name) {
1106
+ var _b;
1107
+ return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
1108
+ }
1109
+ static async getProvider(name, options, deps) {
1110
+ var _b, _c, _d, _e;
1111
+ const key = this.canonicalName(name);
1112
+ // Check if already loaded
1113
+ const existing = this.providers.get(key);
1114
+ if (existing) {
1115
+ return existing;
1116
+ }
1117
+ // Check if loader exists
1118
+ const loader = this.loaders.get(key);
1119
+ if (!loader) {
1120
+ const manifest = this.manifests.get(key);
1121
+ if (manifest) {
1122
+ throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
1123
+ }
1124
+ throw new Error(`Unknown provider: ${name}`);
1125
+ }
1126
+ // Check platform support
1127
+ const manifest = this.manifests.get(key);
1128
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
1129
+ const platform = PlatformDetector.getPlatform();
1130
+ if (!manifest.platforms.includes(platform.platform)) {
1131
+ throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
1132
+ }
1133
+ }
1134
+ try {
1135
+ // Load the provider class
1136
+ const module = await loader();
1137
+ const ProviderClass = module.default;
1138
+ // Build the constructor argument. BaseAuthProvider subclasses need a full
1139
+ // BaseProviderConfig ({ provider, options, storage, logger, persistence });
1140
+ // standalone providers take their options object directly.
1141
+ const storage = (_b = deps === null || deps === void 0 ? void 0 : deps.storage) !== null && _b !== void 0 ? _b : new WebStorage(AuthPersistence.LOCAL);
1142
+ const logger = (_c = deps === null || deps === void 0 ? void 0 : deps.logger) !== null && _c !== void 0 ? _c : new Logger({
1143
+ enableLogging: false,
1144
+ logLevel: 'warn',
1145
+ prefix: 'AuthManager',
1146
+ });
1147
+ const constructorArg = this.STANDALONE_PROVIDERS.has(key)
1148
+ ? (options !== null && options !== void 0 ? options : {})
1149
+ : {
1150
+ provider: key,
1151
+ options: (options !== null && options !== void 0 ? options : {}),
1152
+ storage,
1153
+ logger,
1154
+ persistence: deps === null || deps === void 0 ? void 0 : deps.persistence,
1155
+ };
1156
+ // Create instance
1157
+ const provider = new ProviderClass(constructorArg);
1158
+ // Initialize if supported (BaseAuthProvider.initialize takes no arguments)
1159
+ if (provider.initialize) {
1160
+ await provider.initialize();
1161
+ }
1162
+ // Cache the provider under its canonical key
1163
+ this.providers.set(key, provider);
1164
+ return provider;
1165
+ }
1166
+ catch (error) {
1167
+ // Check if it's a missing dependency error
1168
+ if (((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot find module')) ||
1169
+ ((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to resolve module'))) {
1170
+ const manifest = this.manifests.get(this.canonicalName(name));
1171
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
1172
+ throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
1173
+ `Install the required package:\n` +
1174
+ `npm install ${manifest.packageName}\n\n` +
1175
+ `Then try again.`);
1176
+ }
1177
+ }
1178
+ throw error;
1179
+ }
1180
+ }
1181
+ static clearProvider(name) {
1182
+ const key = this.canonicalName(name);
1183
+ const provider = this.providers.get(key);
1184
+ if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
1185
+ provider.dispose();
1186
+ }
1187
+ this.providers.delete(key);
1188
+ }
1189
+ static clearAll() {
1190
+ for (const [, provider] of this.providers) {
1191
+ if (provider.dispose) {
1192
+ provider.dispose();
1193
+ }
1194
+ }
1195
+ this.providers.clear();
1196
+ }
1197
+ static getAvailableProviders() {
1198
+ return Array.from(this.manifests.keys());
1199
+ }
1200
+ static getSupportedProviders() {
1201
+ const platform = PlatformDetector.getPlatform();
1202
+ const supported = [];
1203
+ for (const [name, manifest] of this.manifests) {
1204
+ if (!manifest.platforms ||
1205
+ manifest.platforms.includes(platform.platform)) {
1206
+ supported.push(name);
1207
+ }
1208
+ }
1209
+ return Promise.resolve(supported);
1210
+ }
1211
+ }
1212
+ _a = ProviderRegistry;
1213
+ ProviderRegistry.providers = new Map();
1214
+ ProviderRegistry.loaders = new Map();
1215
+ ProviderRegistry.manifests = new Map();
1216
+ /** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
1217
+ ProviderRegistry.STANDALONE_PROVIDERS = new Set([
1218
+ 'magic-link',
1219
+ 'sms',
1220
+ 'email-password',
1221
+ 'username-password',
1222
+ 'biometric',
1223
+ 'phone-password',
1224
+ 'email-code',
1225
+ ]);
1226
+ /** Maps AuthProvider enum values (some underscored) to the registered hyphenated loader keys. */
1227
+ ProviderRegistry.NAME_ALIASES = {
1228
+ email_magic_link: 'magic-link',
1229
+ username_password: 'username-password',
1230
+ phone_password: 'phone-password',
1231
+ email_code: 'email-code',
1232
+ };
1233
+ (() => {
1234
+ // Register built-in provider manifests (data lives in provider-manifests.ts — F-40).
1235
+ for (const manifest of BUILT_IN_PROVIDER_MANIFESTS) {
1236
+ _a.registerManifest(manifest);
1237
+ }
984
1238
  // Register provider loaders
985
1239
  _a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
986
1240
  default: m.GoogleAuthProviderWeb,
@@ -1021,8 +1275,31 @@ Note: This provider requires a backend service to handle authentication.
1021
1275
  _a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
1022
1276
  default: m.UsernamePasswordProvider,
1023
1277
  })));
1278
+ _a.registerLoader('email-code', () => Promise.resolve().then(function () { return emailCodeProvider; }).then((m) => ({
1279
+ default: m.EmailCodeProvider,
1280
+ })));
1281
+ _a.registerLoader('phone-password', () => Promise.resolve().then(function () { return phonePasswordProvider; }).then((m) => ({
1282
+ default: m.PhonePasswordProvider,
1283
+ })));
1024
1284
  })();
1025
1285
 
1286
+ /**
1287
+ * Maps the config's persistence literal to the {@link AuthPersistence} enum WebStorage expects.
1288
+ * Critically, `'memory'` maps to {@link AuthPersistence.NONE} (`'none'`) — previously the literal
1289
+ * was cast via `as any` and fell through WebStorage's switch to localStorage, silently breaking
1290
+ * in-memory persistence.
1291
+ */
1292
+ function toAuthPersistence(persistence) {
1293
+ switch (persistence) {
1294
+ case 'session':
1295
+ return AuthPersistence.SESSION;
1296
+ case 'memory':
1297
+ return AuthPersistence.NONE;
1298
+ case 'local':
1299
+ default:
1300
+ return AuthPersistence.LOCAL;
1301
+ }
1302
+ }
1026
1303
  class AuthManagerCore {
1027
1304
  constructor() {
1028
1305
  this.state = {
@@ -1035,12 +1312,14 @@ class AuthManagerCore {
1035
1312
  this.config = {};
1036
1313
  this.isInitialized = false;
1037
1314
  this.tokenRefreshTimers = new Map();
1038
- this.storage = new WebStorage('local');
1315
+ this.initPromise = null;
1039
1316
  this.logger = new Logger({
1040
1317
  enableLogging: false,
1041
1318
  logLevel: 'info',
1042
1319
  prefix: 'AuthManager',
1043
1320
  });
1321
+ this.storage = new WebStorage(AuthPersistence.LOCAL, undefined, this.logger);
1322
+ this.currentPersistence = 'local';
1044
1323
  // Auto-initialize on first use
1045
1324
  if (typeof window !== 'undefined') {
1046
1325
  this.initialize().catch((err) => {
@@ -1052,6 +1331,11 @@ class AuthManagerCore {
1052
1331
  if (this.isInitialized && !config) {
1053
1332
  return;
1054
1333
  }
1334
+ // Coalesce concurrent first-time initialization (e.g. the constructor's auto-init
1335
+ // racing with an explicit initialize()) so restoreAuthState does not run twice.
1336
+ if (this.initPromise && !config) {
1337
+ return this.initPromise;
1338
+ }
1055
1339
  if (config) {
1056
1340
  this.config = Object.assign(Object.assign({}, this.config), config);
1057
1341
  }
@@ -1062,12 +1346,21 @@ class AuthManagerCore {
1062
1346
  if (this.config.logLevel) {
1063
1347
  this.logger.setLogLevel(this.config.logLevel);
1064
1348
  }
1065
- // Configure persistence
1066
- if (this.config.persistence) {
1067
- this.storage = new WebStorage(this.config.persistence);
1349
+ // A custom storage backend (e.g. secure native storage) takes precedence. Otherwise only
1350
+ // recreate storage when persistence actually changes (don't discard in-memory state on a
1351
+ // no-op re-initialize).
1352
+ if (this.config.storage) {
1353
+ this.storage = this.config.storage;
1354
+ this.currentPersistence = 'custom';
1355
+ }
1356
+ else if (this.config.persistence &&
1357
+ this.config.persistence !== this.currentPersistence) {
1358
+ this.storage = new WebStorage(toAuthPersistence(this.config.persistence), undefined, this.logger);
1359
+ this.currentPersistence = this.config.persistence;
1068
1360
  }
1069
1361
  // Restore auth state
1070
- await this.restoreAuthState();
1362
+ this.initPromise = this.restoreAuthState();
1363
+ await this.initPromise;
1071
1364
  this.isInitialized = true;
1072
1365
  this.logger.info('Auth manager initialized');
1073
1366
  }
@@ -1079,12 +1372,23 @@ class AuthManagerCore {
1079
1372
  if (config.logLevel) {
1080
1373
  this.logger.setLogLevel(config.logLevel);
1081
1374
  }
1082
- if (config.persistence) {
1083
- this.storage = new WebStorage(config.persistence);
1375
+ if (config.storage) {
1376
+ this.storage = config.storage;
1377
+ this.currentPersistence = 'custom';
1378
+ }
1379
+ else if (config.persistence &&
1380
+ config.persistence !== this.currentPersistence) {
1381
+ this.storage = new WebStorage(toAuthPersistence(config.persistence), undefined, this.logger);
1382
+ this.currentPersistence = config.persistence;
1383
+ }
1384
+ // Now that providers may be configured, (re)attempt session restore so a persisted
1385
+ // session is rehydrated even when the singleton auto-initialized before configure().
1386
+ if (config.providers && Object.keys(config.providers).length > 0) {
1387
+ void this.restoreAuthState();
1084
1388
  }
1085
1389
  }
1086
1390
  async signIn(providerOrOptions) {
1087
- var _a;
1391
+ var _a, _b, _c;
1088
1392
  await this.ensureInitialized();
1089
1393
  let providerName;
1090
1394
  let signInOptions = {};
@@ -1110,10 +1414,12 @@ class AuthManagerCore {
1110
1414
  throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
1111
1415
  }
1112
1416
  // Get provider instance
1113
- const provider = await ProviderRegistry.getProvider(providerName, providerConfig);
1114
- // Sign in
1417
+ const provider = await ProviderRegistry.getProvider(providerName, providerConfig, this.getProviderDeps());
1418
+ // Sign in. Credentials are spread to the top level (where credential providers read
1419
+ // email/password/phoneNumber/username) AND kept nested under `credentials` for
1420
+ // providers that read them there.
1115
1421
  this.logger.info(`Signing in with ${providerName}`);
1116
- const result = await provider.signIn(Object.assign(Object.assign({}, signInOptions.options), { credentials: signInOptions.credentials }));
1422
+ const result = await provider.signIn(Object.assign(Object.assign(Object.assign({}, signInOptions.options), ((_b = signInOptions.credentials) !== null && _b !== void 0 ? _b : {})), { credentials: signInOptions.credentials }));
1117
1423
  // Update state
1118
1424
  this.updateState({
1119
1425
  user: result.user,
@@ -1128,7 +1434,7 @@ class AuthManagerCore {
1128
1434
  credential: result.credential,
1129
1435
  });
1130
1436
  // Setup token refresh
1131
- if (this.config.autoRefreshToken && result.credential.refreshToken) {
1437
+ if (this.config.autoRefreshToken && ((_c = result.credential) === null || _c === void 0 ? void 0 : _c.refreshToken)) {
1132
1438
  this.setupTokenRefresh(providerName, result.credential);
1133
1439
  }
1134
1440
  return result;
@@ -1151,11 +1457,17 @@ class AuthManagerCore {
1151
1457
  try {
1152
1458
  // Get provider instance
1153
1459
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
1154
- const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig);
1460
+ const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig, this.getProviderDeps());
1155
1461
  // Sign out
1156
1462
  await providerInstance.signOut(options);
1157
- // Clear token refresh
1158
- this.clearTokenRefresh(provider);
1463
+ // Clear token refresh. When no specific provider was targeted, clear ALL refresh timers
1464
+ // (not just the active provider's) so a global sign-out leaves no orphaned timers behind.
1465
+ if (options === null || options === void 0 ? void 0 : options.provider) {
1466
+ this.clearTokenRefresh(provider);
1467
+ }
1468
+ else {
1469
+ this.clearAllTokenRefresh();
1470
+ }
1159
1471
  // Clear state
1160
1472
  this.updateState({
1161
1473
  user: null,
@@ -1186,7 +1498,7 @@ class AuthManagerCore {
1186
1498
  return this.state.provider;
1187
1499
  }
1188
1500
  async refreshToken(provider) {
1189
- var _a;
1501
+ var _a, _b;
1190
1502
  await this.ensureInitialized();
1191
1503
  const targetProvider = provider || this.state.provider;
1192
1504
  if (!targetProvider) {
@@ -1194,7 +1506,7 @@ class AuthManagerCore {
1194
1506
  }
1195
1507
  try {
1196
1508
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
1197
- const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig);
1509
+ const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig, this.getProviderDeps());
1198
1510
  if (!providerInstance.refreshToken) {
1199
1511
  throw new AuthError('auth/operation-not-supported', `Provider '${targetProvider}' does not support token refresh`);
1200
1512
  }
@@ -1202,7 +1514,7 @@ class AuthManagerCore {
1202
1514
  // Update user
1203
1515
  this.updateState({ user: result.user });
1204
1516
  // Setup new token refresh
1205
- if (this.config.autoRefreshToken && result.credential.refreshToken) {
1517
+ if (this.config.autoRefreshToken && ((_b = result.credential) === null || _b === void 0 ? void 0 : _b.refreshToken)) {
1206
1518
  this.setupTokenRefresh(targetProvider, result.credential);
1207
1519
  }
1208
1520
  return result;
@@ -1212,6 +1524,177 @@ class AuthManagerCore {
1212
1524
  throw AuthError.fromError(error);
1213
1525
  }
1214
1526
  }
1527
+ /**
1528
+ * Links an additional auth credential to the current account, delegating to the resolved
1529
+ * provider's optional `linkAccount`. Throws `OPERATION_NOT_ALLOWED` if the provider doesn't
1530
+ * implement it. Mirrors `CapacitorAuthManagerWeb.linkAccount` so React/Vue/Angular consumers
1531
+ * reach the same capability through the `auth` singleton.
1532
+ */
1533
+ async linkAccount(options) {
1534
+ await this.ensureInitialized();
1535
+ const providerName = typeof options.provider === 'string'
1536
+ ? options.provider
1537
+ : AuthProvider[options.provider];
1538
+ const provider = await this.resolveProvider(providerName);
1539
+ if (typeof provider.linkAccount !== 'function') {
1540
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `linkAccount not supported for ${providerName}`);
1541
+ }
1542
+ try {
1543
+ const result = await provider.linkAccount(options);
1544
+ this.updateState({ user: result.user });
1545
+ return result;
1546
+ }
1547
+ catch (error) {
1548
+ this.logger.error(`Account linking failed for ${providerName}`, error);
1549
+ throw AuthError.fromError(error);
1550
+ }
1551
+ }
1552
+ /**
1553
+ * Unlinks a provider credential from the current account via the resolved provider's optional
1554
+ * `unlinkAccount`. Throws `OPERATION_NOT_ALLOWED` if unsupported.
1555
+ */
1556
+ async unlinkAccount(options) {
1557
+ await this.ensureInitialized();
1558
+ const providerName = typeof options.provider === 'string'
1559
+ ? options.provider
1560
+ : AuthProvider[options.provider];
1561
+ const provider = await this.resolveProvider(providerName);
1562
+ if (typeof provider.unlinkAccount !== 'function') {
1563
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `unlinkAccount not supported for ${providerName}`);
1564
+ }
1565
+ try {
1566
+ await provider.unlinkAccount(options);
1567
+ }
1568
+ catch (error) {
1569
+ this.logger.error(`Account unlinking failed for ${providerName}`, error);
1570
+ throw AuthError.fromError(error);
1571
+ }
1572
+ }
1573
+ /**
1574
+ * Revokes the access/refresh token for a provider (current provider when `provider` is omitted),
1575
+ * delegating to the provider's optional `revokeAccess`. Throws `OPERATION_NOT_ALLOWED` if
1576
+ * unsupported.
1577
+ */
1578
+ async revokeAccess(token, provider) {
1579
+ await this.ensureInitialized();
1580
+ const targetProvider = provider || this.state.provider;
1581
+ if (!targetProvider) {
1582
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to revoke access for');
1583
+ }
1584
+ const providerInstance = await this.resolveProvider(targetProvider);
1585
+ if (typeof providerInstance.revokeAccess !== 'function') {
1586
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `revokeAccess not supported for ${targetProvider}`);
1587
+ }
1588
+ try {
1589
+ await providerInstance.revokeAccess(token);
1590
+ }
1591
+ catch (error) {
1592
+ this.logger.error(`Access revocation failed for ${targetProvider}`, error);
1593
+ throw AuthError.fromError(error);
1594
+ }
1595
+ }
1596
+ /**
1597
+ * Returns the current ID token for a provider (current provider when `provider` is omitted) by
1598
+ * delegating to the provider's optional `getIdToken`. Throws `OPERATION_NOT_ALLOWED` if the
1599
+ * provider doesn't issue/expose ID tokens.
1600
+ */
1601
+ async getIdToken(options) {
1602
+ var _a;
1603
+ await this.ensureInitialized();
1604
+ const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1605
+ ? typeof options.provider === 'string'
1606
+ ? options.provider
1607
+ : AuthProvider[options.provider]
1608
+ : undefined) || this.state.provider;
1609
+ if (!targetProvider) {
1610
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to get an ID token for');
1611
+ }
1612
+ const provider = await this.resolveProvider(targetProvider);
1613
+ const getIdTokenFn = provider.getIdToken;
1614
+ if (typeof getIdTokenFn !== 'function') {
1615
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `getIdToken not supported for ${targetProvider}`);
1616
+ }
1617
+ try {
1618
+ return await getIdTokenFn.call(provider, (_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
1619
+ }
1620
+ catch (error) {
1621
+ this.logger.error(`getIdToken failed for ${targetProvider}`, error);
1622
+ throw AuthError.fromError(error);
1623
+ }
1624
+ }
1625
+ /**
1626
+ * Updates the signed-in user's profile via the current provider's optional `updateProfile`.
1627
+ * Throws `OPERATION_NOT_ALLOWED` if the provider doesn't implement it.
1628
+ */
1629
+ async updateProfile(options) {
1630
+ await this.ensureInitialized();
1631
+ const targetProvider = this.state.provider;
1632
+ if (!targetProvider) {
1633
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
1634
+ }
1635
+ const provider = await this.resolveProvider(targetProvider);
1636
+ const updateFn = provider.updateProfile;
1637
+ if (typeof updateFn !== 'function') {
1638
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `updateProfile not supported for ${targetProvider}`);
1639
+ }
1640
+ try {
1641
+ const updatedUser = await updateFn.call(provider, options);
1642
+ this.updateState({ user: updatedUser });
1643
+ return updatedUser;
1644
+ }
1645
+ catch (error) {
1646
+ this.logger.error(`updateProfile failed for ${targetProvider}`, error);
1647
+ throw AuthError.fromError(error);
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Deletes the current account via the provider's optional `deleteAccount` (current provider when
1652
+ * `provider` is omitted), then clears local state. Throws `OPERATION_NOT_ALLOWED` if the provider
1653
+ * doesn't implement it.
1654
+ */
1655
+ async deleteAccount(options) {
1656
+ await this.ensureInitialized();
1657
+ const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
1658
+ ? typeof options.provider === 'string'
1659
+ ? options.provider
1660
+ : AuthProvider[options.provider]
1661
+ : undefined) || this.state.provider;
1662
+ if (!targetProvider) {
1663
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
1664
+ }
1665
+ const provider = await this.resolveProvider(targetProvider);
1666
+ const deleteFn = provider.deleteAccount;
1667
+ if (typeof deleteFn !== 'function') {
1668
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
1669
+ }
1670
+ try {
1671
+ await deleteFn.call(provider);
1672
+ // Account deleted server-side: clear local session + timers.
1673
+ this.clearTokenRefresh(targetProvider);
1674
+ this.updateState({
1675
+ user: null,
1676
+ isAuthenticated: false,
1677
+ provider: null,
1678
+ });
1679
+ await this.storage.remove('auth_state');
1680
+ }
1681
+ catch (error) {
1682
+ this.logger.error(`deleteAccount failed for ${targetProvider}`, error);
1683
+ throw AuthError.fromError(error);
1684
+ }
1685
+ }
1686
+ /**
1687
+ * Whether a provider has been supplied to `configure()`/`initialize()`. Public accessor so
1688
+ * adapters (React/Vue/Angular) no longer reach into the private `config` via `as any`.
1689
+ */
1690
+ isProviderConfigured(name) {
1691
+ var _a;
1692
+ return !!((_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name]);
1693
+ }
1694
+ /** Names of every provider supplied to `configure()`/`initialize()`. */
1695
+ getConfiguredProviders() {
1696
+ return this.config.providers ? Object.keys(this.config.providers) : [];
1697
+ }
1215
1698
  onAuthStateChange(listener) {
1216
1699
  // Immediately call with current state
1217
1700
  listener(this.getAuthState());
@@ -1233,6 +1716,18 @@ class AuthManagerCore {
1233
1716
  await this.initialize();
1234
1717
  }
1235
1718
  }
1719
+ getProviderDeps() {
1720
+ return { storage: this.storage, logger: this.logger };
1721
+ }
1722
+ /**
1723
+ * Resolves a provider instance through the registry, threading the configured options and the
1724
+ * manager's shared storage/logger. Shared by the capability methods (link/unlink/revoke/
1725
+ * getIdToken/updateProfile/deleteAccount).
1726
+ */
1727
+ async resolveProvider(name) {
1728
+ var _a;
1729
+ return ProviderRegistry.getProvider(name, (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name], this.getProviderDeps());
1730
+ }
1236
1731
  updateState(partial) {
1237
1732
  this.state = Object.assign(Object.assign({}, this.state), partial);
1238
1733
  this.stateEmitter.emit(this.state);
@@ -1246,7 +1741,7 @@ class AuthManagerCore {
1246
1741
  const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
1247
1742
  if (providerConfig) {
1248
1743
  try {
1249
- const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig);
1744
+ const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
1250
1745
  const currentUser = await provider.getCurrentUser();
1251
1746
  if (currentUser) {
1252
1747
  this.updateState({
@@ -1280,16 +1775,35 @@ class AuthManagerCore {
1280
1775
  const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
1281
1776
  const refreshTime = credential.expiresAt - buffer - Date.now();
1282
1777
  if (refreshTime > 0) {
1283
- const timer = setTimeout(async () => {
1778
+ this.scheduleRefresh(provider, refreshTime, credential);
1779
+ }
1780
+ }
1781
+ /**
1782
+ * Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
1783
+ * (2,147,483,647 ms ≈ 24.8 days). Without clamping, a far-future `expiresAt` overflows the
1784
+ * timer and fires almost immediately, causing a refresh storm. When clamped, the timer simply
1785
+ * re-schedules the remaining wait on fire instead of refreshing early.
1786
+ */
1787
+ scheduleRefresh(provider, delayMs, credential) {
1788
+ const MAX_TIMEOUT = 2147483647;
1789
+ const clamped = Math.min(delayMs, MAX_TIMEOUT);
1790
+ const timer = setTimeout(() => {
1791
+ const remaining = delayMs - clamped;
1792
+ if (remaining > 0) {
1793
+ // We hit the clamp ceiling — reschedule the rest rather than refreshing prematurely.
1794
+ this.scheduleRefresh(provider, remaining, credential);
1795
+ return;
1796
+ }
1797
+ void (async () => {
1284
1798
  try {
1285
1799
  await this.refreshToken(provider);
1286
1800
  }
1287
1801
  catch (error) {
1288
1802
  this.logger.error(`Auto token refresh failed for ${provider}`, error);
1289
1803
  }
1290
- }, refreshTime);
1291
- this.tokenRefreshTimers.set(provider, timer);
1292
- }
1804
+ })();
1805
+ }, clamped);
1806
+ this.tokenRefreshTimers.set(provider, timer);
1293
1807
  }
1294
1808
  clearTokenRefresh(provider) {
1295
1809
  const timer = this.tokenRefreshTimers.get(provider);
@@ -1298,6 +1812,13 @@ class AuthManagerCore {
1298
1812
  this.tokenRefreshTimers.delete(provider);
1299
1813
  }
1300
1814
  }
1815
+ /** Clears every active refresh timer (used on a global, untargeted sign-out). */
1816
+ clearAllTokenRefresh() {
1817
+ for (const timer of this.tokenRefreshTimers.values()) {
1818
+ clearTimeout(timer);
1819
+ }
1820
+ this.tokenRefreshTimers.clear();
1821
+ }
1301
1822
  dispose() {
1302
1823
  // Clear all timers
1303
1824
  for (const timer of this.tokenRefreshTimers.values()) {
@@ -1327,6 +1848,19 @@ class BaseAuthProvider {
1327
1848
  this.persistence = config.persistence || AuthPersistence.LOCAL;
1328
1849
  this.authStateEmitter = new EventEmitter();
1329
1850
  }
1851
+ // Capability methods with concrete defaults: providers that support these operations override
1852
+ // them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
1853
+ // across every provider (see AuthProviderInterface, where they are optional). Marking them
1854
+ // abstract previously forced every subclass to re-implement them just to throw.
1855
+ async linkAccount(_options) {
1856
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support account linking`, this.provider);
1857
+ }
1858
+ async unlinkAccount(_options) {
1859
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support account unlinking`, this.provider);
1860
+ }
1861
+ async revokeAccess(_token) {
1862
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Provider ${this.provider} does not support access revocation`, this.provider);
1863
+ }
1330
1864
  async getCurrentUser() {
1331
1865
  if (!this.isInitialized) {
1332
1866
  await this.initialize();
@@ -1404,7 +1938,19 @@ class BaseAuthProvider {
1404
1938
  };
1405
1939
  }
1406
1940
  generateUniqueId() {
1407
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1941
+ // Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
1942
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
1943
+ return crypto.randomUUID();
1944
+ }
1945
+ const bytes = new Uint8Array(16);
1946
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
1947
+ crypto.getRandomValues(bytes);
1948
+ }
1949
+ let hex = '';
1950
+ for (let i = 0; i < bytes.length; i++) {
1951
+ hex += bytes[i].toString(16).padStart(2, '0');
1952
+ }
1953
+ return `${Date.now()}-${hex}`;
1408
1954
  }
1409
1955
  isTokenExpired(expiresAt) {
1410
1956
  if (!expiresAt)
@@ -1432,11 +1978,26 @@ class OAuthProvider extends BaseAuthProvider {
1432
1978
  // Generate state and nonce for security
1433
1979
  const state = this.generateSecureRandomString();
1434
1980
  const nonce = this.generateSecureRandomString();
1435
- // Store state and nonce for validation
1981
+ // PKCE (RFC 7636) — default on; requires Web Crypto 'subtle' (HTTPS / localhost).
1982
+ let codeVerifier;
1983
+ let codeChallenge;
1984
+ if (config.pkceEnabled !== false) {
1985
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
1986
+ codeVerifier = this.generateCodeVerifier();
1987
+ codeChallenge = await this.generateCodeChallenge(codeVerifier);
1988
+ }
1989
+ else {
1990
+ this.logger.warn(`PKCE skipped for ${this.provider}: Web Crypto 'subtle' is unavailable (insecure context). Serve over HTTPS to enable PKCE.`);
1991
+ }
1992
+ }
1993
+ // Store state, nonce, and PKCE verifier for validation
1436
1994
  await this.storage.set(`${this.provider}_oauth_state`, state);
1437
1995
  await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
1996
+ if (codeVerifier) {
1997
+ await this.storage.set(`${this.provider}_oauth_verifier`, codeVerifier);
1998
+ }
1438
1999
  // Build authorization URL
1439
- const authUrl = this.buildAuthorizationUrl(config, state, nonce, options);
2000
+ const authUrl = this.buildAuthorizationUrl(config, state, nonce, options, codeChallenge);
1440
2001
  // Perform the OAuth flow (platform-specific implementation)
1441
2002
  const authResponse = await this.openAuthorizationUrl(authUrl);
1442
2003
  // Validate response
@@ -1445,7 +2006,10 @@ class OAuthProvider extends BaseAuthProvider {
1445
2006
  if (!authResponse.code) {
1446
2007
  throw new AuthError(AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
1447
2008
  }
1448
- const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
2009
+ const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config, codeVerifier);
2010
+ // Validate the ID token's nonce + expiry (replay protection). NOTE: the signature is
2011
+ // NOT verified client-side — always re-validate ID tokens on your backend.
2012
+ this.validateIdToken(tokenResponse.id_token, nonce);
1449
2013
  // Parse user information
1450
2014
  const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
1451
2015
  // Create AuthUser and AuthCredential
@@ -1464,31 +2028,47 @@ class OAuthProvider extends BaseAuthProvider {
1464
2028
  // Clean up temporary storage
1465
2029
  await this.storage.remove(`${this.provider}_oauth_state`);
1466
2030
  await this.storage.remove(`${this.provider}_oauth_nonce`);
2031
+ await this.storage.remove(`${this.provider}_oauth_verifier`);
1467
2032
  }
1468
2033
  }
1469
- buildAuthorizationUrl(config, state, nonce, options) {
2034
+ buildAuthorizationUrl(config, state, nonce, options, codeChallenge) {
1470
2035
  var _a, _b, _c, _d;
1471
- const params = new URLSearchParams(Object.assign({ client_id: config.clientId, redirect_uri: config.redirectUri, response_type: config.responseType || 'code', state,
1472
- nonce }, config.additionalParams));
1473
- // Add scopes
1474
- const scopes = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) || config.scopes || [];
1475
- if (scopes.length > 0) {
1476
- params.set('scope', scopes.join(' '));
2036
+ const params = new URLSearchParams();
2037
+ // Developer-supplied params FIRST, so the security-critical params set below cannot be
2038
+ // overridden by additionalParams / customParameters.
2039
+ if (config.additionalParams) {
2040
+ for (const [key, value] of Object.entries(config.additionalParams)) {
2041
+ params.set(key, value);
2042
+ }
1477
2043
  }
1478
- // Add custom parameters
1479
- if ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.customParameters) {
1480
- Object.entries(options.options.customParameters).forEach(([key, value]) => {
2044
+ if ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.customParameters) {
2045
+ for (const [key, value] of Object.entries(options.options.customParameters)) {
1481
2046
  params.set(key, value);
1482
- });
2047
+ }
2048
+ }
2049
+ // Scopes
2050
+ const scopes = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.scopes) || config.scopes || [];
2051
+ if (scopes.length > 0) {
2052
+ params.set('scope', scopes.join(' '));
1483
2053
  }
1484
- // Add login hint if provided
2054
+ // Login hint / prompt
1485
2055
  if ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) {
1486
2056
  params.set('login_hint', options.options.loginHint);
1487
2057
  }
1488
- // Add prompt if provided
1489
2058
  if ((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) {
1490
2059
  params.set('prompt', options.options.prompt);
1491
2060
  }
2061
+ // Security-critical parameters — set LAST so custom params cannot override them.
2062
+ params.set('client_id', config.clientId);
2063
+ params.set('redirect_uri', config.redirectUri);
2064
+ params.set('response_type', config.responseType || 'code');
2065
+ params.set('state', state);
2066
+ params.set('nonce', nonce);
2067
+ if (codeChallenge) {
2068
+ params.set('code_challenge', codeChallenge);
2069
+ params.set('code_challenge_method', 'S256');
2070
+ }
2071
+ this.assertSecureEndpoint(config.authorizationEndpoint);
1492
2072
  return `${config.authorizationEndpoint}?${params.toString()}`;
1493
2073
  }
1494
2074
  async validateOAuthResponse(response, expectedState, _expectedNonce) {
@@ -1500,16 +2080,21 @@ class OAuthProvider extends BaseAuthProvider {
1500
2080
  }
1501
2081
  // Nonce validation is done after ID token is received
1502
2082
  }
1503
- async exchangeCodeForTokens(code, config) {
2083
+ async exchangeCodeForTokens(code, config, codeVerifier) {
1504
2084
  const params = new URLSearchParams({
1505
2085
  grant_type: config.grantType || 'authorization_code',
1506
2086
  code,
1507
2087
  redirect_uri: config.redirectUri,
1508
2088
  client_id: config.clientId,
1509
2089
  });
2090
+ if (codeVerifier) {
2091
+ params.set('code_verifier', codeVerifier);
2092
+ }
1510
2093
  if (config.clientSecret) {
2094
+ this.warnClientSecretInBrowser();
1511
2095
  params.set('client_secret', config.clientSecret);
1512
2096
  }
2097
+ this.assertSecureEndpoint(config.tokenEndpoint);
1513
2098
  try {
1514
2099
  const response = await fetch(config.tokenEndpoint, {
1515
2100
  method: 'POST',
@@ -1546,8 +2131,10 @@ class OAuthProvider extends BaseAuthProvider {
1546
2131
  client_id: config.clientId,
1547
2132
  });
1548
2133
  if (config.clientSecret) {
2134
+ this.warnClientSecretInBrowser();
1549
2135
  params.set('client_secret', config.clientSecret);
1550
2136
  }
2137
+ this.assertSecureEndpoint(config.tokenEndpoint);
1551
2138
  const response = await fetch(config.tokenEndpoint, {
1552
2139
  method: 'POST',
1553
2140
  headers: {
@@ -1594,8 +2181,10 @@ class OAuthProvider extends BaseAuthProvider {
1594
2181
  client_id: config.clientId,
1595
2182
  });
1596
2183
  if (config.clientSecret) {
2184
+ this.warnClientSecretInBrowser();
1597
2185
  params.set('client_secret', config.clientSecret);
1598
2186
  }
2187
+ this.assertSecureEndpoint(config.revokeEndpoint);
1599
2188
  await fetch(config.revokeEndpoint, {
1600
2189
  method: 'POST',
1601
2190
  headers: {
@@ -1682,6 +2271,80 @@ class OAuthProvider extends BaseAuthProvider {
1682
2271
  }
1683
2272
  return result;
1684
2273
  }
2274
+ /** RFC 7636 PKCE code verifier: 64 chars from the unreserved set [A-Za-z0-9]. */
2275
+ generateCodeVerifier() {
2276
+ return this.generateSecureRandomString(64);
2277
+ }
2278
+ /** Derives the S256 PKCE code challenge: base64url(SHA-256(verifier)). */
2279
+ async generateCodeChallenge(verifier) {
2280
+ const data = new TextEncoder().encode(verifier);
2281
+ const digest = await crypto.subtle.digest('SHA-256', data);
2282
+ return this.base64UrlEncode(new Uint8Array(digest));
2283
+ }
2284
+ base64UrlEncode(bytes) {
2285
+ let binary = '';
2286
+ for (let i = 0; i < bytes.length; i++) {
2287
+ binary += String.fromCharCode(bytes[i]);
2288
+ }
2289
+ return btoa(binary)
2290
+ .replace(/\+/g, '-')
2291
+ .replace(/\//g, '_')
2292
+ .replace(/=+$/, '');
2293
+ }
2294
+ /** Decodes a JWT payload without verifying the signature. Returns null if malformed. */
2295
+ decodeJwtPayload(token) {
2296
+ try {
2297
+ const parts = token.split('.');
2298
+ if (parts.length < 2) {
2299
+ return null;
2300
+ }
2301
+ let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
2302
+ const pad = payload.length % 4;
2303
+ if (pad) {
2304
+ payload += '='.repeat(4 - pad);
2305
+ }
2306
+ return JSON.parse(atob(payload));
2307
+ }
2308
+ catch (_a) {
2309
+ return null;
2310
+ }
2311
+ }
2312
+ /**
2313
+ * Validates the ID token's nonce (replay protection) and expiry. The signature is NOT
2314
+ * verified client-side — always re-validate ID tokens on your backend before trusting them.
2315
+ */
2316
+ validateIdToken(idToken, expectedNonce) {
2317
+ if (!idToken) {
2318
+ return;
2319
+ }
2320
+ const payload = this.decodeJwtPayload(idToken);
2321
+ if (!payload) {
2322
+ return;
2323
+ }
2324
+ if (payload.nonce !== undefined && payload.nonce !== expectedNonce) {
2325
+ throw new AuthError(AuthErrorCode.INVALID_NONCE, 'OIDC nonce mismatch in ID token', this.provider);
2326
+ }
2327
+ if (typeof payload.exp === 'number' && payload.exp * 1000 < Date.now()) {
2328
+ throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'ID token is expired', this.provider);
2329
+ }
2330
+ }
2331
+ warnClientSecretInBrowser() {
2332
+ this.logger.warn(`${this.provider}: a client secret was supplied to a browser-facing provider. Secrets ` +
2333
+ `placed in client config ship in the JS bundle and are recoverable by end users. Use a ` +
2334
+ `backend token-exchange proxy (set tokenEndpoint to your server) instead.`);
2335
+ }
2336
+ assertSecureEndpoint(url) {
2337
+ try {
2338
+ const parsed = new URL(url);
2339
+ const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
2340
+ if (parsed.protocol !== 'https:' && !isLocalhost) {
2341
+ this.logger.warn(`${this.provider}: endpoint ${url} is not HTTPS — credentials/tokens may be sent in cleartext.`);
2342
+ }
2343
+ }
2344
+ catch (_a) {
2345
+ // Malformed URL: let the subsequent fetch surface the error.
2346
+ }
2347
+ }
1685
2348
  }
1686
2349
 
1687
2350
  class GoogleAuthProviderWeb extends OAuthProvider {
@@ -2040,8 +2703,8 @@ class AppleAuthProviderWeb extends OAuthProvider {
2040
2703
  const response = await window.AppleID.auth.signIn(signInConfig);
2041
2704
  // Validate response
2042
2705
  await this.validateAppleResponse(response, state, nonce);
2043
- // Parse user information from response
2044
- const user = this.createAppleAuthUser(response);
2706
+ // Parse user information from response (validates ID token nonce + expiry first)
2707
+ const user = this.createAppleAuthUser(response, nonce);
2045
2708
  const credential = this.createAppleCredential(response);
2046
2709
  // Save user and credential
2047
2710
  await this.setCurrentUser(user);
@@ -2075,6 +2738,12 @@ class AppleAuthProviderWeb extends OAuthProvider {
2075
2738
  throw AuthError.fromError(error, this.provider);
2076
2739
  }
2077
2740
  }
2741
+ async refreshToken(_options) {
2742
+ // Apple's JS (web) Sign In flow never issues a refresh token, so the inherited
2743
+ // OAuthProvider.refreshToken() would fail with a confusing "No refresh token available".
2744
+ // Surface an explicit, accurate error instead: callers must re-authenticate.
2745
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Apple web sign-in does not issue refresh tokens; re-authenticate instead.', this.provider);
2746
+ }
2078
2747
  async isSupported() {
2079
2748
  // Check if we're in a browser environment
2080
2749
  if (typeof window === 'undefined' || typeof document === 'undefined') {
@@ -2155,19 +2824,29 @@ class AppleAuthProviderWeb extends OAuthProvider {
2155
2824
  // ID token validation with nonce would be done here
2156
2825
  // For production, you should validate the ID token on your backend
2157
2826
  }
2158
- createAppleAuthUser(response) {
2827
+ createAppleAuthUser(response, expectedNonce) {
2159
2828
  var _a, _b, _c;
2160
2829
  const user = response.user || {};
2161
2830
  const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
2162
- // Parse ID token claims (in production, do this on backend)
2831
+ // Validate the ID token's nonce (replay protection) and expiry BEFORE trusting any
2832
+ // claims. The signature is NOT verified client-side — always re-validate on your backend.
2833
+ // Defensive: only enforce the nonce when both an expected nonce and a token nonce exist.
2163
2834
  let claims = {};
2164
2835
  if (idToken) {
2165
- try {
2166
- const payload = idToken.split('.')[1];
2167
- claims = JSON.parse(atob(payload));
2836
+ const payload = this.decodeJwtPayload(idToken);
2837
+ if (payload) {
2838
+ claims = payload;
2839
+ if (expectedNonce &&
2840
+ claims.nonce !== undefined &&
2841
+ claims.nonce !== expectedNonce) {
2842
+ throw new AuthError(AuthErrorCode.INVALID_NONCE, 'Apple ID token nonce does not match the expected value', this.provider);
2843
+ }
2844
+ if (typeof claims.exp === 'number' && claims.exp * 1000 < Date.now()) {
2845
+ throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Apple ID token is expired', this.provider);
2846
+ }
2168
2847
  }
2169
- catch (error) {
2170
- this.logger.error('Failed to parse ID token', error);
2848
+ else {
2849
+ this.logger.error('Failed to decode Apple ID token payload');
2171
2850
  }
2172
2851
  }
2173
2852
  return {
@@ -2240,11 +2919,16 @@ var appleProvider = /*#__PURE__*/Object.freeze({
2240
2919
  class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2241
2920
  constructor() {
2242
2921
  super(...arguments);
2922
+ this.msalConfig = {};
2243
2923
  this.clientId = '';
2244
2924
  this.authority = '';
2245
2925
  this.redirectUri = '';
2246
2926
  this.scopes = [];
2247
2927
  }
2928
+ /** Reads the host-page MSAL SDK, casting the `window` boundary exactly once. */
2929
+ getMsal() {
2930
+ return window.msal;
2931
+ }
2248
2932
  async initialize() {
2249
2933
  const options = this.options;
2250
2934
  if (!options.clientId) {
@@ -2256,7 +2940,7 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2256
2940
  this.redirectUri = options.redirectUri || window.location.origin;
2257
2941
  this.scopes = options.scopes || ['openid', 'profile', 'email'];
2258
2942
  // Check if MSAL is available
2259
- const msal = window.msal;
2943
+ const msal = this.getMsal();
2260
2944
  if (!msal) {
2261
2945
  throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Microsoft Authentication Library (MSAL) is not loaded. Please include the MSAL script in your HTML.', this.provider);
2262
2946
  }
@@ -2303,9 +2987,22 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2303
2987
  }
2304
2988
  }
2305
2989
  async signIn(options) {
2990
+ var _a, _b, _c, _d;
2306
2991
  this.validateInitialized();
2307
2992
  try {
2308
- const loginRequest = Object.assign({ scopes: this.scopes }, options);
2993
+ // Build the MSAL login request EXPLICITLY from the standard options shape — spreading
2994
+ // raw `options` here would leak junk (provider, credentials, …) into MSAL and ignore
2995
+ // per-sign-in scopes. Honour per-call scopes/loginHint/prompt, fall back to configured
2996
+ // scopes, and omit undefined keys.
2997
+ const loginRequest = {
2998
+ 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,
2999
+ };
3000
+ if (((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) !== undefined) {
3001
+ loginRequest.loginHint = options.options.loginHint;
3002
+ }
3003
+ if (((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) !== undefined) {
3004
+ loginRequest.prompt = options.options.prompt;
3005
+ }
2309
3006
  // Try popup first, fallback to redirect
2310
3007
  let response;
2311
3008
  try {
@@ -2324,10 +3021,11 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2324
3021
  }
2325
3022
  catch (error) {
2326
3023
  this.logger.error('Microsoft sign in failed', error);
2327
- if (error.errorCode === 'user_cancelled') {
3024
+ const err = error;
3025
+ if (err.errorCode === 'user_cancelled') {
2328
3026
  throw new AuthError(AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
2329
3027
  }
2330
- throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${error.message}`, this.provider);
3028
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${err.message}`, this.provider);
2331
3029
  }
2332
3030
  }
2333
3031
  async signOut(options) {
@@ -2373,15 +3071,16 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2373
3071
  }
2374
3072
  catch (error) {
2375
3073
  this.logger.error('Token refresh failed', error);
2376
- if (error.errorCode === 'interaction_required') {
3074
+ const err = error;
3075
+ if (err.errorCode === 'interaction_required') {
2377
3076
  // Need user interaction, trigger sign in
2378
3077
  return await this.signIn();
2379
3078
  }
2380
- throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${error.message}`, this.provider);
3079
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${err.message}`, this.provider);
2381
3080
  }
2382
3081
  }
2383
3082
  async isSupported() {
2384
- return typeof window !== 'undefined' && !!window.msal;
3083
+ return typeof window !== 'undefined' && !!this.getMsal();
2385
3084
  }
2386
3085
  async linkAccount() {
2387
3086
  // Microsoft doesn't support account linking in the same way
@@ -2411,32 +3110,37 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2411
3110
  scope: response.scopes.join(' '),
2412
3111
  };
2413
3112
  await this.saveCredential(credential);
2414
- return this.createAuthResult(user, credential, ((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser) || false);
3113
+ return this.createAuthResult(user, credential, Boolean((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser));
2415
3114
  }
2416
3115
  createUserFromMSALAccount(account) {
2417
3116
  const idTokenClaims = account.idTokenClaims || {};
3117
+ const claim = (key) => {
3118
+ const value = idTokenClaims[key];
3119
+ return typeof value === 'string' ? value : undefined;
3120
+ };
3121
+ const iat = idTokenClaims.iat;
2418
3122
  return {
2419
- uid: account.localAccountId || account.homeAccountId,
2420
- email: idTokenClaims.email || account.username,
3123
+ uid: account.localAccountId || account.homeAccountId || '',
3124
+ email: claim('email') || account.username || null,
2421
3125
  emailVerified: !!idTokenClaims.email_verified,
2422
- displayName: account.name || idTokenClaims.name,
2423
- photoURL: idTokenClaims.picture || null,
2424
- phoneNumber: idTokenClaims.phone_number || null,
3126
+ displayName: account.name || claim('name') || null,
3127
+ photoURL: claim('picture') || null,
3128
+ phoneNumber: claim('phone_number') || null,
2425
3129
  isAnonymous: false,
2426
- tenantId: account.tenantId,
3130
+ tenantId: account.tenantId || null,
2427
3131
  providerData: [
2428
3132
  {
2429
3133
  providerId: this.provider,
2430
- uid: account.localAccountId,
2431
- displayName: account.name,
2432
- email: account.username,
3134
+ uid: account.localAccountId || '',
3135
+ displayName: account.name || null,
3136
+ email: account.username || null,
2433
3137
  phoneNumber: null,
2434
- photoURL: idTokenClaims.picture || null,
3138
+ photoURL: claim('picture') || null,
2435
3139
  },
2436
3140
  ],
2437
3141
  metadata: {
2438
- creationTime: idTokenClaims.iat
2439
- ? new Date(idTokenClaims.iat * 1000).toISOString()
3142
+ creationTime: typeof iat === 'number'
3143
+ ? new Date(iat * 1000).toISOString()
2440
3144
  : undefined,
2441
3145
  lastSignInTime: new Date().toISOString(),
2442
3146
  },
@@ -2534,7 +3238,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
2534
3238
  checkLoginStatus() {
2535
3239
  return new Promise((resolve) => {
2536
3240
  window.FB.getLoginStatus(async (response) => {
2537
- if (response.status === 'connected') {
3241
+ if (response.status === 'connected' && response.authResponse) {
2538
3242
  await this.handleAuthResponse(response.authResponse);
2539
3243
  }
2540
3244
  resolve();
@@ -2589,7 +3293,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
2589
3293
  // Facebook access tokens are short-lived and need to be refreshed via re-authentication
2590
3294
  return new Promise((resolve, reject) => {
2591
3295
  window.FB.getLoginStatus(async (response) => {
2592
- if (response.status === 'connected') {
3296
+ if (response.status === 'connected' && response.authResponse) {
2593
3297
  try {
2594
3298
  const result = await this.handleAuthResponse(response.authResponse, true);
2595
3299
  resolve(result);
@@ -2709,6 +3413,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2709
3413
  this.scopes = [];
2710
3414
  this.authWindow = null;
2711
3415
  this.authPromise = null;
3416
+ /** Bound 'message' handler reference so it can be removed in dispose(). */
3417
+ this.boundAuthMessageHandler = null;
3418
+ /** Active popup-closed polling interval, tracked so it is cleared on every exit path. */
3419
+ this.popupCheckInterval = null;
3420
+ /** CSRF state from the most recent sign-in, forwarded to the proxy for re-verification. */
3421
+ this.lastState = null;
2712
3422
  }
2713
3423
  async initialize() {
2714
3424
  const options = this.options;
@@ -2719,8 +3429,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2719
3429
  this.redirectUri =
2720
3430
  options.redirectUri || window.location.origin + '/auth/github/callback';
2721
3431
  this.scopes = options.scopes || ['read:user', 'user:email'];
2722
- // Set up message listener for OAuth callback
2723
- window.addEventListener('message', this.handleAuthMessage.bind(this));
3432
+ this.tokenExchangeProxy =
3433
+ options.tokenExchangeProxy || options.tokenEndpoint;
3434
+ // Set up message listener for OAuth callback. Keep the bound reference so the exact
3435
+ // same function can be removed in dispose() (a fresh `.bind()` would not match).
3436
+ this.boundAuthMessageHandler = this.handleAuthMessage.bind(this);
3437
+ window.addEventListener('message', this.boundAuthMessageHandler);
2724
3438
  // Check for stored session
2725
3439
  await this.loadCurrentUser();
2726
3440
  this.isInitialized = true;
@@ -2731,6 +3445,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2731
3445
  return new Promise((resolve, reject) => {
2732
3446
  this.authPromise = { resolve, reject };
2733
3447
  const state = this.generateState();
3448
+ this.lastState = state;
2734
3449
  const authUrl = this.buildAuthUrl(state);
2735
3450
  // Open GitHub OAuth in a popup window
2736
3451
  const width = 600;
@@ -2743,11 +3458,13 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2743
3458
  reject(new AuthError(AuthErrorCode.POPUP_BLOCKED, 'Popup window was blocked. Please allow popups for this site.', this.provider));
2744
3459
  return;
2745
3460
  }
2746
- // Check if popup is closed
2747
- const checkInterval = setInterval(() => {
3461
+ // Check if popup is closed. Track the interval so the success path
3462
+ // (handleAuthMessage) and dispose() can also clear it — otherwise it leaks.
3463
+ this.clearPopupCheckInterval();
3464
+ this.popupCheckInterval = setInterval(() => {
2748
3465
  var _a;
2749
3466
  if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
2750
- clearInterval(checkInterval);
3467
+ this.clearPopupCheckInterval();
2751
3468
  if (this.authPromise) {
2752
3469
  this.authPromise = null;
2753
3470
  reject(new AuthError(AuthErrorCode.USER_CANCELLED, 'User closed the authentication window', this.provider));
@@ -2756,6 +3473,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2756
3473
  }, 1000);
2757
3474
  });
2758
3475
  }
3476
+ clearPopupCheckInterval() {
3477
+ if (this.popupCheckInterval !== null) {
3478
+ clearInterval(this.popupCheckInterval);
3479
+ this.popupCheckInterval = null;
3480
+ }
3481
+ }
2759
3482
  async signOut(options) {
2760
3483
  this.validateInitialized();
2761
3484
  try {
@@ -2834,6 +3557,8 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2834
3557
  if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) !== 'github-auth-callback') {
2835
3558
  return;
2836
3559
  }
3560
+ // The callback arrived — stop polling for a closed popup (success path cleanup).
3561
+ this.clearPopupCheckInterval();
2837
3562
  if (this.authWindow) {
2838
3563
  this.authWindow.close();
2839
3564
  this.authWindow = null;
@@ -2876,9 +3601,44 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2876
3601
  reject(AuthError.fromError(error, this.provider));
2877
3602
  }
2878
3603
  }
2879
- async exchangeCodeForToken(_code) {
2880
- // NOTE: This should be done server-side in production to keep client secret secure
2881
- throw new AuthError(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);
3604
+ async exchangeCodeForToken(code) {
3605
+ // GitHub does NOT permit browser-side code→token exchange (it needs the client secret
3606
+ // and blocks CORS), so the exchange must run on a developer-supplied backend proxy.
3607
+ if (!this.tokenExchangeProxy) {
3608
+ throw new AuthError(AuthErrorCode.MISSING_CONFIG, 'GitHub sign-in requires a backend token-exchange proxy. Set `tokenExchangeProxy` ' +
3609
+ '(or `tokenEndpoint`) in the GitHub provider config to a server endpoint that ' +
3610
+ 'exchanges the authorization code for an access token. See the GitHub provider ' +
3611
+ 'setup guide / docs/providers for an example.', this.provider);
3612
+ }
3613
+ let response;
3614
+ try {
3615
+ response = await fetch(this.tokenExchangeProxy, {
3616
+ method: 'POST',
3617
+ headers: {
3618
+ 'Content-Type': 'application/json',
3619
+ Accept: 'application/json',
3620
+ },
3621
+ body: JSON.stringify({
3622
+ code,
3623
+ redirectUri: this.redirectUri,
3624
+ state: this.lastState,
3625
+ }),
3626
+ });
3627
+ }
3628
+ catch (error) {
3629
+ throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach the GitHub token-exchange proxy', this.provider, error);
3630
+ }
3631
+ const data = (await response
3632
+ .json()
3633
+ .catch(() => null));
3634
+ if (!response.ok || !data || !data.access_token) {
3635
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `GitHub token exchange failed${(data === null || data === void 0 ? void 0 : data.error_description)
3636
+ ? `: ${data.error_description}`
3637
+ : (data === null || data === void 0 ? void 0 : data.error)
3638
+ ? `: ${data.error}`
3639
+ : ''}`, this.provider);
3640
+ }
3641
+ return Object.assign(Object.assign({}, data), { access_token: data.access_token });
2882
3642
  }
2883
3643
  async fetchUserData(accessToken) {
2884
3644
  const response = await fetch('https://api.github.com/user', {
@@ -2905,6 +3665,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2905
3665
  return await response.json();
2906
3666
  }
2907
3667
  async createUserFromGitHubData(userData, accessToken) {
3668
+ var _a, _b, _c, _d, _e, _f;
2908
3669
  // Get primary email
2909
3670
  const emails = await this.fetchUserEmails(accessToken);
2910
3671
  const primaryEmail = emails.find((e) => e.primary) || emails[0];
@@ -2935,15 +3696,35 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
2935
3696
  },
2936
3697
  customClaims: {
2937
3698
  login: userData.login,
2938
- company: userData.company,
2939
- location: userData.location,
2940
- bio: userData.bio,
2941
- public_repos: userData.public_repos,
2942
- followers: userData.followers,
2943
- following: userData.following,
3699
+ company: (_a = userData.company) !== null && _a !== void 0 ? _a : null,
3700
+ location: (_b = userData.location) !== null && _b !== void 0 ? _b : null,
3701
+ bio: (_c = userData.bio) !== null && _c !== void 0 ? _c : null,
3702
+ public_repos: (_d = userData.public_repos) !== null && _d !== void 0 ? _d : null,
3703
+ followers: (_e = userData.followers) !== null && _e !== void 0 ? _e : null,
3704
+ following: (_f = userData.following) !== null && _f !== void 0 ? _f : null,
2944
3705
  },
2945
3706
  };
2946
3707
  }
3708
+ dispose() {
3709
+ // Remove the global 'message' listener added in initialize() so it doesn't leak across
3710
+ // repeated init/dispose cycles, and stop any active popup-polling interval.
3711
+ if (this.boundAuthMessageHandler) {
3712
+ window.removeEventListener('message', this.boundAuthMessageHandler);
3713
+ this.boundAuthMessageHandler = null;
3714
+ }
3715
+ this.clearPopupCheckInterval();
3716
+ if (this.authWindow) {
3717
+ try {
3718
+ this.authWindow.close();
3719
+ }
3720
+ catch (_a) {
3721
+ // window already closed / cross-origin — safe to ignore
3722
+ }
3723
+ this.authWindow = null;
3724
+ }
3725
+ this.authPromise = null;
3726
+ super.dispose();
3727
+ }
2947
3728
  }
2948
3729
 
2949
3730
  var githubProvider = /*#__PURE__*/Object.freeze({
@@ -2956,6 +3737,11 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
2956
3737
  super(...arguments);
2957
3738
  this.unsubscribeAuth = null;
2958
3739
  }
3740
+ /** Reads the host-page Firebase SDK, casting the `window` boundary exactly once. */
3741
+ getFirebase() {
3742
+ return window
3743
+ .firebase;
3744
+ }
2959
3745
  async initialize() {
2960
3746
  const options = this.options;
2961
3747
  if (!options.apiKey || !options.authDomain || !options.projectId) {
@@ -2963,7 +3749,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
2963
3749
  }
2964
3750
  try {
2965
3751
  // Check if Firebase is available
2966
- const firebase = window.firebase;
3752
+ const firebase = this.getFirebase();
2967
3753
  if (!firebase) {
2968
3754
  throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded. Please include the Firebase scripts in your HTML.', this.provider);
2969
3755
  }
@@ -3011,73 +3797,88 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
3011
3797
  }
3012
3798
  }
3013
3799
  getPersistenceMode() {
3014
- const firebase = window.firebase;
3800
+ const firebase = this.getFirebase();
3801
+ const persistence = firebase === null || firebase === void 0 ? void 0 : firebase.auth.Auth.Persistence;
3015
3802
  switch (this.persistence) {
3016
3803
  case 'session':
3017
- return firebase.auth.Auth.Persistence.SESSION;
3804
+ return persistence === null || persistence === void 0 ? void 0 : persistence.SESSION;
3018
3805
  case 'none':
3019
- return firebase.auth.Auth.Persistence.NONE;
3806
+ return persistence === null || persistence === void 0 ? void 0 : persistence.NONE;
3020
3807
  default:
3021
- return firebase.auth.Auth.Persistence.LOCAL;
3808
+ return persistence === null || persistence === void 0 ? void 0 : persistence.LOCAL;
3022
3809
  }
3023
3810
  }
3024
3811
  async signIn(options) {
3812
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3025
3813
  this.validateInitialized();
3026
- const signInOptions = options || {};
3814
+ // The manager spreads credentials to the top level AND nests them under `credentials`,
3815
+ // and spreads `options.*` (scopes, prompt, etc.) to the top level too. Derive the
3816
+ // Firebase sub-method from the STANDARD shape instead of an undocumented `options.method`.
3817
+ const raw = options || {};
3818
+ const nestedOptions = raw.options || {};
3819
+ const credentials = raw.credentials || {};
3820
+ // email/password may arrive nested under `credentials` or spread to the top level.
3821
+ const email = ((_a = credentials.email) !== null && _a !== void 0 ? _a : raw.email);
3822
+ const password = ((_b = credentials.password) !== null && _b !== void 0 ? _b : raw.password);
3823
+ const scopes = ((_c = nestedOptions.scopes) !== null && _c !== void 0 ? _c : raw.scopes);
3824
+ const firebaseOptions = this.options;
3825
+ const method = ((_e = (_d = nestedOptions.method) !== null && _d !== void 0 ? _d : raw.method) !== null && _e !== void 0 ? _e : (email && password
3826
+ ? 'email'
3827
+ : firebaseOptions.defaultMethod || 'google'));
3828
+ const signInOptions = { method, email, password, scopes };
3829
+ const firebase = this.getFirebase();
3830
+ if (!firebase) {
3831
+ throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
3832
+ }
3833
+ const applyScopes = (provider) => {
3834
+ if (signInOptions.scopes) {
3835
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3836
+ }
3837
+ };
3027
3838
  try {
3028
3839
  let firebaseUser;
3029
3840
  let credential;
3030
3841
  let additionalUserInfo;
3031
3842
  // Determine sign-in method
3032
3843
  if (signInOptions.method === 'google') {
3033
- const provider = new window.firebase.auth.GoogleAuthProvider();
3034
- if (signInOptions.scopes) {
3035
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3036
- }
3844
+ const provider = new firebase.auth.GoogleAuthProvider();
3845
+ applyScopes(provider);
3037
3846
  const result = await this.firebaseAuth.signInWithPopup(provider);
3038
3847
  firebaseUser = result.user;
3039
3848
  credential = result.credential;
3040
- additionalUserInfo = result.additionalUserInfo;
3849
+ additionalUserInfo = (_f = result.additionalUserInfo) !== null && _f !== void 0 ? _f : {};
3041
3850
  }
3042
3851
  else if (signInOptions.method === 'facebook') {
3043
- const provider = new window.firebase.auth.FacebookAuthProvider();
3044
- if (signInOptions.scopes) {
3045
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3046
- }
3852
+ const provider = new firebase.auth.FacebookAuthProvider();
3853
+ applyScopes(provider);
3047
3854
  const result = await this.firebaseAuth.signInWithPopup(provider);
3048
3855
  firebaseUser = result.user;
3049
3856
  credential = result.credential;
3050
- additionalUserInfo = result.additionalUserInfo;
3857
+ additionalUserInfo = (_g = result.additionalUserInfo) !== null && _g !== void 0 ? _g : {};
3051
3858
  }
3052
3859
  else if (signInOptions.method === 'github') {
3053
- const provider = new window.firebase.auth.GithubAuthProvider();
3054
- if (signInOptions.scopes) {
3055
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3056
- }
3860
+ const provider = new firebase.auth.GithubAuthProvider();
3861
+ applyScopes(provider);
3057
3862
  const result = await this.firebaseAuth.signInWithPopup(provider);
3058
3863
  firebaseUser = result.user;
3059
3864
  credential = result.credential;
3060
- additionalUserInfo = result.additionalUserInfo;
3865
+ additionalUserInfo = (_h = result.additionalUserInfo) !== null && _h !== void 0 ? _h : {};
3061
3866
  }
3062
3867
  else if (signInOptions.method === 'microsoft') {
3063
- const provider = new window.firebase.auth.OAuthProvider('microsoft.com');
3064
- if (signInOptions.scopes) {
3065
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3066
- }
3868
+ const provider = new firebase.auth.OAuthProvider('microsoft.com');
3869
+ applyScopes(provider);
3067
3870
  const result = await this.firebaseAuth.signInWithPopup(provider);
3068
3871
  firebaseUser = result.user;
3069
3872
  credential = result.credential;
3070
- additionalUserInfo = result.additionalUserInfo;
3873
+ additionalUserInfo = (_j = result.additionalUserInfo) !== null && _j !== void 0 ? _j : {};
3071
3874
  }
3072
3875
  else if (signInOptions.method === 'apple') {
3073
- const provider = new window.firebase.auth.OAuthProvider('apple.com');
3074
- if (signInOptions.scopes) {
3075
- signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3076
- }
3876
+ const provider = new firebase.auth.OAuthProvider('apple.com');
3877
+ applyScopes(provider);
3077
3878
  const result = await this.firebaseAuth.signInWithPopup(provider);
3078
3879
  firebaseUser = result.user;
3079
3880
  credential = result.credential;
3080
- additionalUserInfo = result.additionalUserInfo;
3881
+ additionalUserInfo = (_k = result.additionalUserInfo) !== null && _k !== void 0 ? _k : {};
3081
3882
  }
3082
3883
  else if (signInOptions.method === 'email' &&
3083
3884
  signInOptions.email &&
@@ -3109,11 +3910,12 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
3109
3910
  }
3110
3911
  catch (error) {
3111
3912
  this.logger.error('Firebase sign in failed', error);
3112
- if (error.code === 'auth/popup-closed-by-user' ||
3113
- error.code === 'auth/cancelled-popup-request') {
3913
+ const err = error;
3914
+ if (err.code === 'auth/popup-closed-by-user' ||
3915
+ err.code === 'auth/cancelled-popup-request') {
3114
3916
  throw new AuthError(AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
3115
3917
  }
3116
- throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${error.message}`, this.provider);
3918
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${err.message}`, this.provider);
3117
3919
  }
3118
3920
  }
3119
3921
  async signOut(options) {
@@ -3157,24 +3959,33 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
3157
3959
  }
3158
3960
  }
3159
3961
  async isSupported() {
3160
- return typeof window !== 'undefined' && !!window.firebase;
3962
+ return typeof window !== 'undefined' && !!this.getFirebase();
3161
3963
  }
3162
3964
  async linkAccount(options) {
3965
+ var _a, _b, _c, _d;
3163
3966
  this.validateInitialized();
3164
3967
  const currentUser = this.firebaseAuth.currentUser;
3165
3968
  if (!currentUser) {
3166
3969
  throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active session to link account to', this.provider);
3167
3970
  }
3971
+ const firebase = this.getFirebase();
3972
+ if (!firebase) {
3973
+ throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
3974
+ }
3975
+ // `method`/`email`/`password` may arrive nested under credentials or in provider options.
3976
+ const raw = options;
3977
+ const creds = (_a = raw.credentials) !== null && _a !== void 0 ? _a : {};
3978
+ const method = ((_b = raw.method) !== null && _b !== void 0 ? _b : creds.method);
3979
+ const linkEmail = ((_c = creds.email) !== null && _c !== void 0 ? _c : raw.email);
3980
+ const linkPassword = ((_d = creds.password) !== null && _d !== void 0 ? _d : raw.password);
3168
3981
  try {
3169
3982
  let result;
3170
- if (options.method === 'google') {
3171
- const provider = new window.firebase.auth.GoogleAuthProvider();
3983
+ if (method === 'google') {
3984
+ const provider = new firebase.auth.GoogleAuthProvider();
3172
3985
  result = await currentUser.linkWithPopup(provider);
3173
3986
  }
3174
- else if (options.method === 'email' &&
3175
- options.email &&
3176
- options.password) {
3177
- const credential = window.firebase.auth.EmailAuthProvider.credential(options.email, options.password);
3987
+ else if (method === 'email' && linkEmail && linkPassword) {
3988
+ const credential = firebase.auth.EmailAuthProvider.credential(linkEmail, linkPassword);
3178
3989
  result = await currentUser.linkWithCredential(credential);
3179
3990
  }
3180
3991
  else {
@@ -3185,6 +3996,8 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
3185
3996
  return this.createAuthResult(user, authCredential, false, 'link');
3186
3997
  }
3187
3998
  catch (error) {
3999
+ if (error instanceof AuthError)
4000
+ throw error;
3188
4001
  throw new AuthError(AuthErrorCode.INTERNAL_ERROR, `Failed to link account: ${error.message}`, this.provider);
3189
4002
  }
3190
4003
  }
@@ -3195,7 +4008,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
3195
4008
  throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active session', this.provider);
3196
4009
  }
3197
4010
  try {
3198
- await currentUser.unlink(options.providerId);
4011
+ await currentUser.unlink(options.provider);
3199
4012
  }
3200
4013
  catch (error) {
3201
4014
  throw new AuthError(AuthErrorCode.INTERNAL_ERROR, `Failed to unlink account: ${error.message}`, this.provider);
@@ -3259,10 +4072,116 @@ var firebaseProvider = /*#__PURE__*/Object.freeze({
3259
4072
  FirebaseAuthProviderWeb: FirebaseAuthProviderWeb
3260
4073
  });
3261
4074
 
4075
+ class PendingVerificationStore {
4076
+ /**
4077
+ * @param namespace Provider namespace (e.g. `'sms'`, `'email-code'`, `'magic-link'`). Keys are
4078
+ * stored under `cap_auth_pending_<namespace>` so providers never collide.
4079
+ */
4080
+ constructor(namespace) {
4081
+ /** In-memory mirror so the store works in SSR / private-mode where localStorage is unavailable. */
4082
+ this.memory = new Map();
4083
+ this.storageKey = `cap_auth_pending_${namespace}`;
4084
+ }
4085
+ getLocalStorage() {
4086
+ try {
4087
+ return typeof localStorage !== 'undefined' ? localStorage : null;
4088
+ }
4089
+ catch (_a) {
4090
+ // Access to localStorage can throw (e.g. sandboxed iframe) — fall back to memory only.
4091
+ return null;
4092
+ }
4093
+ }
4094
+ readAll() {
4095
+ const ls = this.getLocalStorage();
4096
+ if (!ls) {
4097
+ return Object.fromEntries(this.memory);
4098
+ }
4099
+ try {
4100
+ const raw = ls.getItem(this.storageKey);
4101
+ if (!raw)
4102
+ return {};
4103
+ const parsed = JSON.parse(raw);
4104
+ return parsed && typeof parsed === 'object' ? parsed : {};
4105
+ }
4106
+ catch (error) {
4107
+ defaultLogger.warn(`PendingVerificationStore: failed to read ${this.storageKey}`, error);
4108
+ return {};
4109
+ }
4110
+ }
4111
+ writeAll(all) {
4112
+ const ls = this.getLocalStorage();
4113
+ if (!ls) {
4114
+ this.memory.clear();
4115
+ for (const [k, v] of Object.entries(all))
4116
+ this.memory.set(k, v);
4117
+ return;
4118
+ }
4119
+ try {
4120
+ ls.setItem(this.storageKey, JSON.stringify(all));
4121
+ }
4122
+ catch (error) {
4123
+ defaultLogger.warn(`PendingVerificationStore: failed to write ${this.storageKey}`, error);
4124
+ }
4125
+ }
4126
+ /**
4127
+ * Stores (or replaces) the pending record for `key` (phone / email / magic-link token). Other
4128
+ * expired entries in the namespace are pruned here to bound storage growth.
4129
+ */
4130
+ set(key, record) {
4131
+ const all = this.readAll();
4132
+ this.pruneExpired(all, key);
4133
+ all[key] = record;
4134
+ this.writeAll(all);
4135
+ }
4136
+ /**
4137
+ * Returns the pending record for `key`, or null if absent. Does NOT filter by expiry — the
4138
+ * caller owns the expiry decision so it can throw a precise error and clean up itself.
4139
+ */
4140
+ get(key) {
4141
+ var _a;
4142
+ const all = this.readAll();
4143
+ return (_a = all[key]) !== null && _a !== void 0 ? _a : null;
4144
+ }
4145
+ /** Removes the pending record for `key` (e.g. after a successful or expired verification). */
4146
+ delete(key) {
4147
+ const all = this.readAll();
4148
+ if (key in all) {
4149
+ delete all[key];
4150
+ this.writeAll(all);
4151
+ }
4152
+ }
4153
+ /** Clears every pending record in this namespace. */
4154
+ clear() {
4155
+ const ls = this.getLocalStorage();
4156
+ this.memory.clear();
4157
+ if (ls) {
4158
+ try {
4159
+ ls.removeItem(this.storageKey);
4160
+ }
4161
+ catch (error) {
4162
+ defaultLogger.warn(`PendingVerificationStore: failed to clear ${this.storageKey}`, error);
4163
+ }
4164
+ }
4165
+ }
4166
+ pruneExpired(all, exceptKey) {
4167
+ const now = Date.now();
4168
+ for (const [k, v] of Object.entries(all)) {
4169
+ if (k !== exceptKey && now > v.expires) {
4170
+ delete all[k];
4171
+ }
4172
+ }
4173
+ return all;
4174
+ }
4175
+ }
4176
+
3262
4177
  class MagicLinkProvider {
3263
4178
  constructor(config) {
3264
4179
  this.name = 'magic-link';
3265
- this.pendingVerification = new Map();
4180
+ // Persisted (SSR-guarded localStorage) so a magic link clicked from an email — which opens a
4181
+ // FRESH page load with empty in-memory state — can still find its pending entry to verify
4182
+ // against. Keyed by the link token (already present in the callback URL); we store only the
4183
+ // email + expiry, never any additional secret (see PendingVerificationStore + F-11).
4184
+ this.pendingVerification = new PendingVerificationStore('magic-link');
3266
4185
  // Initialize with config
3267
4186
  this.config = config;
3268
4187
  // Check for magic link callback on initialization
@@ -3270,15 +4189,17 @@ class MagicLinkProvider {
3270
4189
  }
3271
4190
  async signIn(options) {
3272
4191
  if (!(options === null || options === void 0 ? void 0 : options.email)) {
3273
- throw new AuthError('EMAIL_REQUIRED', 'Email is required for magic link authentication');
4192
+ throw new AuthError(AuthErrorCode.EMAIL_REQUIRED, 'Email is required for magic link authentication');
3274
4193
  }
3275
4194
  try {
3276
4195
  // Send magic link to email
3277
4196
  const token = this.generateToken();
3278
4197
  const magicLink = this.generateMagicLink(token);
3279
- // Store pending verification
4198
+ // Store pending verification (persisted; email + expiry only, keyed by the link token).
3280
4199
  this.pendingVerification.set(token, {
3281
- email: options.email,
4200
+ identifier: options.email,
4201
+ sessionId: token,
4202
+ attempts: 0,
3282
4203
  expires: Date.now() + 15 * 60 * 1000, // 15 minutes
3283
4204
  });
3284
4205
  // Send email via backend API
@@ -3295,7 +4216,7 @@ class MagicLinkProvider {
3295
4216
  }),
3296
4217
  });
3297
4218
  if (!response.ok) {
3298
- throw new AuthError('SEND_LINK_FAILED', 'Failed to send magic link');
4219
+ throw new AuthError(AuthErrorCode.SEND_LINK_FAILED, 'Failed to send magic link');
3299
4220
  }
3300
4221
  // Return partial auth result for pending state
3301
4222
  const tempUser = {
@@ -3329,18 +4250,22 @@ class MagicLinkProvider {
3329
4250
  };
3330
4251
  }
3331
4252
  catch (error) {
3332
- throw new AuthError('MAGIC_LINK_ERROR', error.message || 'Failed to send magic link');
4253
+ if (error instanceof AuthError)
4254
+ throw error;
4255
+ throw new AuthError(AuthErrorCode.SEND_LINK_FAILED, error.message || 'Failed to send magic link');
3333
4256
  }
3334
4257
  }
3335
4258
  async verifyMagicLink(token) {
3336
4259
  const pending = this.pendingVerification.get(token);
3337
4260
  if (!pending) {
3338
- throw new AuthError('INVALID_TOKEN', 'Invalid or expired magic link');
4261
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Invalid or expired magic link');
3339
4262
  }
3340
4263
  if (Date.now() > pending.expires) {
3341
4264
  this.pendingVerification.delete(token);
3342
- throw new AuthError('TOKEN_EXPIRED', 'Magic link has expired');
4265
+ throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Magic link has expired');
3343
4266
  }
4267
+ // The persisted record stores the email under `identifier`.
4268
+ const email = pending.identifier;
3344
4269
  try {
3345
4270
  // Verify token with backend if configured
3346
4271
  if (this.config.verifyUrl) {
@@ -3351,27 +4276,27 @@ class MagicLinkProvider {
3351
4276
  },
3352
4277
  body: JSON.stringify({
3353
4278
  token,
3354
- email: pending.email,
4279
+ email: email,
3355
4280
  clientId: this.config.clientId,
3356
4281
  }),
3357
4282
  });
3358
4283
  if (!response.ok) {
3359
- throw new AuthError('VERIFICATION_FAILED', 'Failed to verify magic link');
4284
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, 'Failed to verify magic link');
3360
4285
  }
3361
4286
  const data = await response.json();
3362
4287
  // Create user from verified data
3363
4288
  const user = {
3364
- uid: data.uid || this.generateUid(pending.email),
3365
- email: pending.email,
3366
- displayName: data.displayName || pending.email.split('@')[0],
4289
+ uid: data.uid || this.generateUid(email),
4290
+ email: email,
4291
+ displayName: data.displayName || email.split('@')[0],
3367
4292
  photoURL: data.photoURL || null,
3368
4293
  emailVerified: true,
3369
4294
  providerData: [
3370
4295
  {
3371
4296
  providerId: this.name,
3372
- uid: data.uid || pending.email,
3373
- displayName: data.displayName || pending.email.split('@')[0],
3374
- email: pending.email,
4297
+ uid: data.uid || email,
4298
+ displayName: data.displayName || email.split('@')[0],
4299
+ email: email,
3375
4300
  phoneNumber: null,
3376
4301
  photoURL: data.photoURL || null,
3377
4302
  },
@@ -3400,17 +4325,17 @@ class MagicLinkProvider {
3400
4325
  else {
3401
4326
  // Simple verification without backend
3402
4327
  const user = {
3403
- uid: this.generateUid(pending.email),
3404
- email: pending.email,
3405
- displayName: pending.email.split('@')[0],
4328
+ uid: this.generateUid(email),
4329
+ email: email,
4330
+ displayName: email.split('@')[0],
3406
4331
  photoURL: null,
3407
4332
  emailVerified: true,
3408
4333
  providerData: [
3409
4334
  {
3410
4335
  providerId: this.name,
3411
- uid: pending.email,
3412
- displayName: pending.email.split('@')[0],
3413
- email: pending.email,
4336
+ uid: email,
4337
+ displayName: email.split('@')[0],
4338
+ email: email,
3414
4339
  phoneNumber: null,
3415
4340
  photoURL: null,
3416
4341
  },
@@ -3437,7 +4362,9 @@ class MagicLinkProvider {
3437
4362
  }
3438
4363
  }
3439
4364
  catch (error) {
3440
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify magic link');
4365
+ if (error instanceof AuthError)
4366
+ throw error;
4367
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify magic link');
3441
4368
  }
3442
4369
  }
3443
4370
  async signOut() {
@@ -3449,7 +4376,7 @@ class MagicLinkProvider {
3449
4376
  return null;
3450
4377
  }
3451
4378
  async refreshToken() {
3452
- throw new AuthError('NOT_SUPPORTED', 'Token refresh is not supported for magic link authentication');
4379
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Token refresh is not supported for magic link authentication');
3453
4380
  }
3454
4381
  generateToken() {
3455
4382
  const array = new Uint8Array(32);
@@ -3507,10 +4434,10 @@ class MagicLinkProvider {
3507
4434
  return !!this.config.sendLinkUrl;
3508
4435
  }
3509
4436
  async linkAccount(_options) {
3510
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for magic link authentication');
4437
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for magic link authentication');
3511
4438
  }
3512
4439
  async unlinkAccount(_options) {
3513
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for magic link authentication');
4440
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for magic link authentication');
3514
4441
  }
3515
4442
  async revokeAccess(_token) {
3516
4443
  // Magic link doesn't have persistent access to revoke
@@ -3526,14 +4453,17 @@ var magicLinkProvider = /*#__PURE__*/Object.freeze({
3526
4453
  class SMSProvider {
3527
4454
  constructor(config) {
3528
4455
  this.name = 'sms';
3529
- this.pendingVerifications = new Map();
4456
+ // Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
4457
+ // page change between sending and verifying the code. Only non-secret metadata is stored —
4458
+ // never the SMS code itself (see PendingVerificationStore + F-11).
4459
+ this.pendingVerifications = new PendingVerificationStore('sms');
3530
4460
  this.MAX_ATTEMPTS = 3;
3531
4461
  // Initialize with config
3532
4462
  this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, config);
3533
4463
  }
3534
4464
  async signIn(options) {
3535
4465
  if (!(options === null || options === void 0 ? void 0 : options.phoneNumber)) {
3536
- throw new AuthError('PHONE_REQUIRED', 'Phone number is required for SMS authentication');
4466
+ throw new AuthError(AuthErrorCode.PHONE_REQUIRED, 'Phone number is required for SMS authentication');
3537
4467
  }
3538
4468
  // If code is provided, verify it
3539
4469
  if (options.code) {
@@ -3552,7 +4482,7 @@ class SMSProvider {
3552
4482
  const timeSinceLastResend = Date.now() - existing.lastResent;
3553
4483
  if (timeSinceLastResend < this.config.resendDelay) {
3554
4484
  const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
3555
- throw new AuthError('RESEND_DELAY', `Please wait ${waitTime} seconds before requesting a new code`);
4485
+ throw new AuthError(AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
3556
4486
  }
3557
4487
  }
3558
4488
  // Send SMS code via backend
@@ -3569,12 +4499,12 @@ class SMSProvider {
3569
4499
  });
3570
4500
  if (!response.ok) {
3571
4501
  const error = await response.json().catch(() => ({}));
3572
- throw new AuthError('SEND_CODE_FAILED', error.message || 'Failed to send SMS code');
4502
+ throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
3573
4503
  }
3574
4504
  const data = await response.json();
3575
- // Store pending verification
4505
+ // Store pending verification (persisted; metadata only, never the code).
3576
4506
  this.pendingVerifications.set(formattedPhone, {
3577
- phoneNumber: formattedPhone,
4507
+ identifier: formattedPhone,
3578
4508
  sessionId: data.sessionId,
3579
4509
  expires: Date.now() + 10 * 60 * 1000, // 10 minutes
3580
4510
  attempts: 0,
@@ -3617,26 +4547,27 @@ class SMSProvider {
3617
4547
  catch (error) {
3618
4548
  if (error instanceof AuthError)
3619
4549
  throw error;
3620
- throw new AuthError('SMS_ERROR', error.message || 'Failed to send SMS code');
4550
+ throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
3621
4551
  }
3622
4552
  }
3623
4553
  async verifyCode(phoneNumber, code) {
3624
4554
  const formattedPhone = this.formatPhoneNumber(phoneNumber);
3625
4555
  const pending = this.pendingVerifications.get(formattedPhone);
3626
4556
  if (!pending) {
3627
- throw new AuthError('NO_PENDING_VERIFICATION', 'No pending SMS verification found');
4557
+ throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending SMS verification found');
3628
4558
  }
3629
4559
  if (Date.now() > pending.expires) {
3630
4560
  this.pendingVerifications.delete(formattedPhone);
3631
- throw new AuthError('CODE_EXPIRED', 'SMS code has expired');
4561
+ throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'SMS code has expired');
3632
4562
  }
3633
4563
  if (pending.attempts >= this.MAX_ATTEMPTS) {
3634
4564
  this.pendingVerifications.delete(formattedPhone);
3635
- throw new AuthError('TOO_MANY_ATTEMPTS', 'Too many failed attempts');
4565
+ throw new AuthError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts');
3636
4566
  }
3637
4567
  try {
3638
- // Increment attempts
4568
+ // Increment attempts and persist the bump (so the count survives a reload mid-flow).
3639
4569
  pending.attempts++;
4570
+ this.pendingVerifications.set(formattedPhone, pending);
3640
4571
  // Verify code with backend
3641
4572
  const response = await fetch(this.config.verifyCodeUrl, {
3642
4573
  method: 'POST',
@@ -3653,9 +4584,9 @@ class SMSProvider {
3653
4584
  if (!response.ok) {
3654
4585
  const error = await response.json().catch(() => ({}));
3655
4586
  if (response.status === 401) {
3656
- throw new AuthError('INVALID_CODE', 'Invalid SMS code');
4587
+ throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid SMS code');
3657
4588
  }
3658
- throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to verify SMS code');
4589
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
3659
4590
  }
3660
4591
  const data = await response.json();
3661
4592
  // Create user from verified data
@@ -3701,7 +4632,7 @@ class SMSProvider {
3701
4632
  catch (error) {
3702
4633
  if (error instanceof AuthError)
3703
4634
  throw error;
3704
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify SMS code');
4635
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
3705
4636
  }
3706
4637
  }
3707
4638
  async signOut() {
@@ -3713,8 +4644,9 @@ class SMSProvider {
3713
4644
  return null;
3714
4645
  }
3715
4646
  async refreshToken(_options) {
3716
- // Token refresh would be implemented based on backend requirements
3717
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh is not yet implemented for SMS authentication');
4647
+ // SMS code authentication is single-use and has no refresh flow; the user must request
4648
+ // a new verification code rather than refresh a token.
4649
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication does not support token refresh; request a new code instead.');
3718
4650
  }
3719
4651
  formatPhoneNumber(phoneNumber) {
3720
4652
  // Remove all non-numeric characters
@@ -3766,10 +4698,10 @@ class SMSProvider {
3766
4698
  return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
3767
4699
  }
3768
4700
  async linkAccount(_options) {
3769
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for SMS authentication');
4701
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for SMS authentication');
3770
4702
  }
3771
4703
  async unlinkAccount(_options) {
3772
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for SMS authentication');
4704
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for SMS authentication');
3773
4705
  }
3774
4706
  async revokeAccess(_token) {
3775
4707
  // SMS auth doesn't have persistent access to revoke
@@ -3799,7 +4731,7 @@ class EmailPasswordProvider {
3799
4731
  }
3800
4732
  async signIn(options) {
3801
4733
  if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3802
- throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
4734
+ throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
3803
4735
  }
3804
4736
  try {
3805
4737
  const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
@@ -3816,9 +4748,9 @@ class EmailPasswordProvider {
3816
4748
  if (!response.ok) {
3817
4749
  const error = await response.json().catch(() => ({}));
3818
4750
  if (response.status === 401) {
3819
- throw new AuthError('INVALID_CREDENTIALS', 'Invalid email or password');
4751
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid email or password');
3820
4752
  }
3821
- throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
4753
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
3822
4754
  }
3823
4755
  const data = await response.json();
3824
4756
  // Create user object
@@ -3865,24 +4797,24 @@ class EmailPasswordProvider {
3865
4797
  catch (error) {
3866
4798
  if (error instanceof AuthError)
3867
4799
  throw error;
3868
- throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with email and password');
4800
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with email and password');
3869
4801
  }
3870
4802
  }
3871
4803
  async signUp(options) {
3872
4804
  if (!this.config.allowSignUp) {
3873
- throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
4805
+ throw new AuthError(AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
3874
4806
  }
3875
4807
  if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3876
- throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
4808
+ throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
3877
4809
  }
3878
4810
  // Validate email
3879
4811
  if (!this.isValidEmail(options.email)) {
3880
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
4812
+ throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
3881
4813
  }
3882
4814
  // Validate password
3883
4815
  const passwordError = this.validatePassword(options.password);
3884
4816
  if (passwordError) {
3885
- throw new AuthError('WEAK_PASSWORD', passwordError);
4817
+ throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
3886
4818
  }
3887
4819
  try {
3888
4820
  const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
@@ -3901,9 +4833,9 @@ class EmailPasswordProvider {
3901
4833
  if (!response.ok) {
3902
4834
  const error = await response.json().catch(() => ({}));
3903
4835
  if (response.status === 409) {
3904
- throw new AuthError('EMAIL_EXISTS', 'Email already in use');
4836
+ throw new AuthError(AuthErrorCode.EMAIL_ALREADY_IN_USE, 'Email already in use');
3905
4837
  }
3906
- throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
4838
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
3907
4839
  }
3908
4840
  const data = await response.json();
3909
4841
  // Create user object
@@ -3950,7 +4882,7 @@ class EmailPasswordProvider {
3950
4882
  catch (error) {
3951
4883
  if (error instanceof AuthError)
3952
4884
  throw error;
3953
- throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
4885
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
3954
4886
  }
3955
4887
  }
3956
4888
  async signOut() {
@@ -3980,7 +4912,7 @@ class EmailPasswordProvider {
3980
4912
  }
3981
4913
  async refreshToken(_options) {
3982
4914
  if (!this.refreshTokenValue) {
3983
- throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
4915
+ throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
3984
4916
  }
3985
4917
  try {
3986
4918
  const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
@@ -3994,7 +4926,7 @@ class EmailPasswordProvider {
3994
4926
  }),
3995
4927
  });
3996
4928
  if (!response.ok) {
3997
- throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
4929
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
3998
4930
  }
3999
4931
  const data = await response.json();
4000
4932
  // Update tokens
@@ -4016,17 +4948,17 @@ class EmailPasswordProvider {
4016
4948
  catch (error) {
4017
4949
  if (error instanceof AuthError)
4018
4950
  throw error;
4019
- throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
4951
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
4020
4952
  }
4021
4953
  }
4022
4954
  async updatePassword(currentPassword, newPassword) {
4023
4955
  if (!this.currentUser || !this.authToken) {
4024
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
4956
+ throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
4025
4957
  }
4026
4958
  // Validate new password
4027
4959
  const passwordError = this.validatePassword(newPassword);
4028
4960
  if (passwordError) {
4029
- throw new AuthError('WEAK_PASSWORD', passwordError);
4961
+ throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
4030
4962
  }
4031
4963
  try {
4032
4964
  const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
@@ -4044,20 +4976,20 @@ class EmailPasswordProvider {
4044
4976
  if (!response.ok) {
4045
4977
  const error = await response.json().catch(() => ({}));
4046
4978
  if (response.status === 401) {
4047
- throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
4979
+ throw new AuthError(AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
4048
4980
  }
4049
- throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
4981
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4050
4982
  }
4051
4983
  }
4052
4984
  catch (error) {
4053
4985
  if (error instanceof AuthError)
4054
4986
  throw error;
4055
- throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
4987
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4056
4988
  }
4057
4989
  }
4058
4990
  async sendPasswordResetEmail(email) {
4059
4991
  if (!this.isValidEmail(email)) {
4060
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
4992
+ throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
4061
4993
  }
4062
4994
  try {
4063
4995
  const response = await fetch(`${this.config.apiUrl}/auth/reset-password`, {
@@ -4072,21 +5004,21 @@ class EmailPasswordProvider {
4072
5004
  });
4073
5005
  if (!response.ok) {
4074
5006
  const error = await response.json().catch(() => ({}));
4075
- throw new AuthError('RESET_FAILED', error.message || 'Failed to send reset email');
5007
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send reset email');
4076
5008
  }
4077
5009
  }
4078
5010
  catch (error) {
4079
5011
  if (error instanceof AuthError)
4080
5012
  throw error;
4081
- throw new AuthError('RESET_ERROR', error.message || 'Failed to send password reset email');
5013
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset email');
4082
5014
  }
4083
5015
  }
4084
5016
  async sendEmailVerification() {
4085
5017
  if (!this.currentUser || !this.authToken) {
4086
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
5018
+ throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
4087
5019
  }
4088
5020
  if (this.currentUser.emailVerified) {
4089
- throw new AuthError('ALREADY_VERIFIED', 'Email already verified');
5021
+ throw new AuthError(AuthErrorCode.EMAIL_ALREADY_VERIFIED, 'Email already verified');
4090
5022
  }
4091
5023
  try {
4092
5024
  const response = await fetch(`${this.config.apiUrl}/auth/verify-email`, {
@@ -4101,13 +5033,13 @@ class EmailPasswordProvider {
4101
5033
  });
4102
5034
  if (!response.ok) {
4103
5035
  const error = await response.json().catch(() => ({}));
4104
- throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to send verification email');
5036
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
4105
5037
  }
4106
5038
  }
4107
5039
  catch (error) {
4108
5040
  if (error instanceof AuthError)
4109
5041
  throw error;
4110
- throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to send verification email');
5042
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
4111
5043
  }
4112
5044
  }
4113
5045
  isValidEmail(email) {
@@ -4142,10 +5074,10 @@ class EmailPasswordProvider {
4142
5074
  return !!this.config.apiUrl;
4143
5075
  }
4144
5076
  async linkAccount(_options) {
4145
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for email/password authentication');
5077
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for email/password authentication');
4146
5078
  }
4147
5079
  async unlinkAccount(_options) {
4148
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for email/password authentication');
5080
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for email/password authentication');
4149
5081
  }
4150
5082
  async revokeAccess(_token) {
4151
5083
  // For email/password auth, revoking access means signing out
@@ -4162,6 +5094,7 @@ class BiometricProvider {
4162
5094
  constructor(config = {}) {
4163
5095
  this.name = 'biometric';
4164
5096
  this.biometricAuth = null;
5097
+ this.cryptoKeyPromise = null;
4165
5098
  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);
4166
5099
  this.storageKey =
4167
5100
  config.storageKey || 'capacitor-auth-biometric-credentials';
@@ -4175,31 +5108,31 @@ class BiometricProvider {
4175
5108
  this.biometricAuth = BiometricAuth;
4176
5109
  }
4177
5110
  catch (_a) {
4178
- console.warn('Biometric authentication plugin not available');
5111
+ defaultLogger.warn('Biometric authentication plugin not available');
4179
5112
  }
4180
5113
  }
4181
5114
  async signIn(_options) {
4182
5115
  var _a, _b, _c;
4183
5116
  if (!this.biometricAuth) {
4184
- throw new AuthError('BIOMETRIC_NOT_AVAILABLE', 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
5117
+ throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
4185
5118
  }
4186
5119
  try {
4187
5120
  // Check if biometry is available
4188
5121
  const checkResult = await this.biometricAuth.checkBiometry();
4189
5122
  if (!checkResult.isAvailable) {
4190
- throw new AuthError('BIOMETRIC_NOT_AVAILABLE', checkResult.reason ||
5123
+ throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, checkResult.reason ||
4191
5124
  'Biometric authentication is not available on this device');
4192
5125
  }
4193
5126
  // Check if we have stored credentials
4194
5127
  const storedCredentials = await this.getStoredCredentials();
4195
5128
  if (!storedCredentials) {
4196
- throw new AuthError('NO_STORED_CREDENTIALS', 'No stored credentials found. Please sign in with another method first.');
5129
+ throw new AuthError(AuthErrorCode.NO_STORED_CREDENTIALS, 'No stored credentials found. Please sign in with another method first.');
4197
5130
  }
4198
5131
  // Check if recent auth is required
4199
5132
  if (this.config.requireRecentAuth) {
4200
5133
  const timeSinceLastAuth = Date.now() - storedCredentials.lastAuthTime;
4201
5134
  if (timeSinceLastAuth > this.config.recentAuthTimeout) {
4202
- throw new AuthError('AUTH_EXPIRED', 'Authentication expired. Please sign in with another method.');
5135
+ throw new AuthError(AuthErrorCode.REQUIRES_RECENT_LOGIN, 'Authentication expired. Please sign in with another method.');
4203
5136
  }
4204
5137
  }
4205
5138
  // Perform biometric authentication
@@ -4235,17 +5168,17 @@ class BiometricProvider {
4235
5168
  throw error;
4236
5169
  // Handle biometric errors
4237
5170
  if (error.code === 'userCancel' || ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('cancel'))) {
4238
- throw new AuthError('USER_CANCELLED', 'Authentication cancelled by user');
5171
+ throw new AuthError(AuthErrorCode.USER_CANCELLED, 'Authentication cancelled by user');
4239
5172
  }
4240
5173
  else if (error.code === 'biometryLockout' ||
4241
5174
  ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('lockout'))) {
4242
- throw new AuthError('BIOMETRY_LOCKOUT', 'Too many failed attempts. Biometry is locked.');
5175
+ throw new AuthError(AuthErrorCode.BIOMETRIC_LOCKOUT, 'Too many failed attempts. Biometry is locked.');
4243
5176
  }
4244
5177
  else if (error.code === 'biometryNotEnrolled' ||
4245
5178
  ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('enrolled'))) {
4246
- throw new AuthError('NOT_ENROLLED', 'No biometric credentials are enrolled');
5179
+ throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_ENROLLED, 'No biometric credentials are enrolled');
4247
5180
  }
4248
- throw new AuthError('BIOMETRIC_ERROR', error.message || 'Biometric authentication failed');
5181
+ throw new AuthError(AuthErrorCode.BIOMETRIC_AUTHENTICATION_FAILED, error.message || 'Biometric authentication failed');
4249
5182
  }
4250
5183
  }
4251
5184
  async signOut() {
@@ -4309,6 +5242,8 @@ class BiometricProvider {
4309
5242
  return true;
4310
5243
  }
4311
5244
  async getStoredCredentials() {
5245
+ if (typeof localStorage === 'undefined')
5246
+ return null;
4312
5247
  try {
4313
5248
  const stored = localStorage.getItem(this.storageKey);
4314
5249
  if (!stored)
@@ -4321,25 +5256,118 @@ class BiometricProvider {
4321
5256
  }
4322
5257
  }
4323
5258
  async storeCredentials(credentials) {
5259
+ if (typeof localStorage === 'undefined') {
5260
+ throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric credential storage is unavailable in this environment');
5261
+ }
4324
5262
  try {
4325
5263
  const encrypted = await this.encrypt(JSON.stringify(credentials));
4326
5264
  localStorage.setItem(this.storageKey, encrypted);
4327
5265
  }
4328
- catch (_a) {
4329
- throw new AuthError('STORAGE_ERROR', 'Failed to store credentials');
5266
+ catch (error) {
5267
+ throw new AuthError(AuthErrorCode.STORAGE_ERROR, 'Failed to store credentials', undefined, { cause: String(error) });
4330
5268
  }
4331
5269
  }
4332
5270
  async clearStoredCredentials() {
4333
- localStorage.removeItem(this.storageKey);
5271
+ if (typeof localStorage !== 'undefined') {
5272
+ localStorage.removeItem(this.storageKey);
5273
+ }
5274
+ }
5275
+ /**
5276
+ * Persistent, non-extractable AES-GCM key kept in IndexedDB so it cannot be read back out by
5277
+ * script — stored biometric credentials are therefore not recoverable by simply reading
5278
+ * localStorage (unlike the previous base64 encoding).
5279
+ */
5280
+ getEncryptionKey() {
5281
+ if (!this.cryptoKeyPromise) {
5282
+ this.cryptoKeyPromise = (async () => {
5283
+ const existing = await this.loadKeyFromIndexedDb();
5284
+ if (existing)
5285
+ return existing;
5286
+ const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
5287
+ await this.saveKeyToIndexedDb(key);
5288
+ return key;
5289
+ })();
5290
+ }
5291
+ return this.cryptoKeyPromise;
5292
+ }
5293
+ openKeyDb() {
5294
+ return new Promise((resolve, reject) => {
5295
+ const req = indexedDB.open('capacitor-auth-keys', 1);
5296
+ req.onupgradeneeded = () => req.result.createObjectStore('keys');
5297
+ req.onsuccess = () => resolve(req.result);
5298
+ req.onerror = () => reject(req.error);
5299
+ });
4334
5300
  }
4335
- // Simple encryption/decryption (in production, use proper encryption)
4336
- async encrypt(data) {
4337
- // In a real implementation, use Web Crypto API or similar
4338
- return btoa(data);
5301
+ async loadKeyFromIndexedDb() {
5302
+ if (typeof indexedDB === 'undefined')
5303
+ return null;
5304
+ try {
5305
+ const db = await this.openKeyDb();
5306
+ return await new Promise((resolve) => {
5307
+ const tx = db.transaction('keys', 'readonly');
5308
+ const req = tx.objectStore('keys').get(this.storageKey);
5309
+ req.onsuccess = () => { var _a; return resolve((_a = req.result) !== null && _a !== void 0 ? _a : null); };
5310
+ req.onerror = () => resolve(null);
5311
+ });
5312
+ }
5313
+ catch (_a) {
5314
+ return null;
5315
+ }
4339
5316
  }
4340
- async decrypt(data) {
4341
- // In a real implementation, use Web Crypto API or similar
4342
- return atob(data);
5317
+ async saveKeyToIndexedDb(key) {
5318
+ if (typeof indexedDB === 'undefined')
5319
+ return;
5320
+ try {
5321
+ const db = await this.openKeyDb();
5322
+ await new Promise((resolve) => {
5323
+ const tx = db.transaction('keys', 'readwrite');
5324
+ tx.objectStore('keys').put(key, this.storageKey);
5325
+ tx.oncomplete = () => resolve();
5326
+ tx.onerror = () => resolve();
5327
+ });
5328
+ }
5329
+ catch (_a) {
5330
+ // Best-effort: a fresh key is generated next time if persistence fails.
5331
+ }
5332
+ }
5333
+ /**
5334
+ * Encrypts with AES-GCM (Web Crypto). Falls back to base64 ONLY when Web Crypto / IndexedDB
5335
+ * are unavailable (insecure context); the `b64:`/`aes:` prefix tells decrypt() the format.
5336
+ */
5337
+ async encrypt(data) {
5338
+ if (typeof crypto === 'undefined' ||
5339
+ !crypto.subtle ||
5340
+ typeof indexedDB === 'undefined') {
5341
+ return `b64:${btoa(data)}`;
5342
+ }
5343
+ const key = await this.getEncryptionKey();
5344
+ const iv = crypto.getRandomValues(new Uint8Array(12));
5345
+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(data));
5346
+ const packed = new Uint8Array(iv.length + ciphertext.byteLength);
5347
+ packed.set(iv, 0);
5348
+ packed.set(new Uint8Array(ciphertext), iv.length);
5349
+ let binary = '';
5350
+ for (let i = 0; i < packed.length; i++) {
5351
+ binary += String.fromCharCode(packed[i]);
5352
+ }
5353
+ return `aes:${btoa(binary)}`;
5354
+ }
5355
+ async decrypt(data) {
5356
+ if (data.startsWith('aes:')) {
5357
+ const key = await this.getEncryptionKey();
5358
+ const binary = atob(data.slice(4));
5359
+ const bytes = new Uint8Array(binary.length);
5360
+ for (let i = 0; i < binary.length; i++) {
5361
+ bytes[i] = binary.charCodeAt(i);
5362
+ }
5363
+ const iv = bytes.slice(0, 12);
5364
+ const ciphertext = bytes.slice(12);
5365
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
5366
+ return new TextDecoder().decode(plaintext);
5367
+ }
5368
+ // Legacy (older versions) or insecure-context fallback: base64-encoded payload.
5369
+ const payload = data.startsWith('b64:') ? data.slice(4) : data;
5370
+ return atob(payload);
4343
5371
  }
4344
5372
  async initialize() {
4345
5373
  // Biometric provider is initialized in constructor
@@ -4351,7 +5379,7 @@ class BiometricProvider {
4351
5379
  return result.available;
4352
5380
  }
4353
5381
  async linkAccount(_options) {
4354
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for biometric authentication');
5382
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for biometric authentication');
4355
5383
  }
4356
5384
  async unlinkAccount(_options) {
4357
5385
  // Unlinking biometric auth means clearing stored credentials
@@ -4388,9 +5416,9 @@ class SlackProvider extends OAuthProvider {
4388
5416
  async signIn(options) {
4389
5417
  return this.performOAuthFlow(options);
4390
5418
  }
4391
- async refreshToken(_options) {
4392
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for Slack provider');
4393
- }
5419
+ // Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
5420
+ // Note: Slack's OAuth 2.0 for public web apps typically doesn't issue refresh tokens.
5421
+ // If no refresh token is available, the base class will throw "No refresh token available".
4394
5422
  getOAuthConfig() {
4395
5423
  return {
4396
5424
  clientId: this.clientId,
@@ -4401,15 +5429,39 @@ class SlackProvider extends OAuthProvider {
4401
5429
  additionalParams: this.teamId ? { team: this.teamId } : {},
4402
5430
  };
4403
5431
  }
4404
- async parseUserFromTokenResponse(_response) {
4405
- // In a real implementation, you would parse the user info from the token response
4406
- // or make an additional API call to get user details
5432
+ async parseUserFromTokenResponse(response) {
5433
+ var _a;
5434
+ const accessToken = response.access_token;
5435
+ if (!accessToken) {
5436
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Slack token response did not include an access token; cannot fetch the user profile.', this.provider);
5437
+ }
5438
+ // Fetch the real profile via Slack's OpenID Connect userInfo endpoint.
5439
+ // https://api.slack.com/methods/openid.connect.userInfo
5440
+ let res;
5441
+ try {
5442
+ res = await fetch('https://slack.com/api/openid.connect.userInfo', {
5443
+ method: 'GET',
5444
+ headers: {
5445
+ Authorization: `Bearer ${accessToken}`,
5446
+ Accept: 'application/json',
5447
+ },
5448
+ });
5449
+ }
5450
+ catch (error) {
5451
+ throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach Slack userInfo endpoint', this.provider, error);
5452
+ }
5453
+ // Slack returns HTTP 200 with `{ ok: false, error }` on API-level failures.
5454
+ const data = (await res.json().catch(() => null));
5455
+ if (!res.ok || !data || data.ok === false || !data.sub) {
5456
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, `Failed to fetch Slack user profile${(data === null || data === void 0 ? void 0 : data.error) ? `: ${data.error}` : ''}`, this.provider);
5457
+ }
4407
5458
  return {
4408
- id: 'U1234567890',
4409
- email: 'user@workspace.slack.com',
4410
- name: 'Slack User',
4411
- picture: 'https://ui-avatars.com/api/?name=Slack+User',
4412
- email_verified: true,
5459
+ id: data.sub,
5460
+ sub: data.sub,
5461
+ email: data.email,
5462
+ email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
5463
+ name: data.name,
5464
+ picture: data.picture,
4413
5465
  isNewUser: false,
4414
5466
  };
4415
5467
  }
@@ -4455,10 +5507,10 @@ class SlackProvider extends OAuthProvider {
4455
5507
  return true;
4456
5508
  }
4457
5509
  async linkAccount(_options) {
4458
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for Slack provider');
5510
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for Slack provider');
4459
5511
  }
4460
5512
  async unlinkAccount(_options) {
4461
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for Slack provider');
5513
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for Slack provider');
4462
5514
  }
4463
5515
  async revokeAccess(token) {
4464
5516
  await super.revokeAccess(token);
@@ -4497,9 +5549,10 @@ class LinkedInProvider extends OAuthProvider {
4497
5549
  await this.clearStoredData();
4498
5550
  await this.setCurrentUser(null);
4499
5551
  }
4500
- async refreshToken(_options) {
4501
- throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for LinkedIn provider');
4502
- }
5552
+ // Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
5553
+ // Note: LinkedIn's OAuth 2.0 issues long-lived access tokens (60 days) and typically
5554
+ // doesn't provide refresh tokens for web apps. If no refresh token is available,
5555
+ // the base class will throw "No refresh token available".
4503
5556
  getOAuthConfig() {
4504
5557
  return {
4505
5558
  clientId: this.clientId,
@@ -4509,15 +5562,40 @@ class LinkedInProvider extends OAuthProvider {
4509
5562
  scopes: this.scopes,
4510
5563
  };
4511
5564
  }
4512
- async parseUserFromTokenResponse(_response) {
4513
- // In a real implementation, you would parse the user info from the token response
4514
- // or make an additional API call to get user details
5565
+ async parseUserFromTokenResponse(response) {
5566
+ var _a;
5567
+ const accessToken = response.access_token;
5568
+ if (!accessToken) {
5569
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'LinkedIn token response did not include an access token; cannot fetch the user profile.', this.provider);
5570
+ }
5571
+ // Fetch the real profile via LinkedIn's OpenID Connect userinfo endpoint.
5572
+ // https://learn.microsoft.com/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2
5573
+ let res;
5574
+ try {
5575
+ res = await fetch('https://api.linkedin.com/v2/userinfo', {
5576
+ method: 'GET',
5577
+ headers: {
5578
+ Authorization: `Bearer ${accessToken}`,
5579
+ Accept: 'application/json',
5580
+ },
5581
+ });
5582
+ }
5583
+ catch (error) {
5584
+ throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach LinkedIn userinfo endpoint', this.provider, error);
5585
+ }
5586
+ const data = (await res
5587
+ .json()
5588
+ .catch(() => null));
5589
+ if (!res.ok || !data || !data.sub) {
5590
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Failed to fetch LinkedIn user profile', this.provider);
5591
+ }
4515
5592
  return {
4516
- id: 'linkedin_user_123',
4517
- email: 'user@linkedin.com',
4518
- name: 'LinkedIn User',
4519
- picture: 'https://ui-avatars.com/api/?name=LinkedIn+User',
4520
- email_verified: true,
5593
+ id: data.sub,
5594
+ sub: data.sub,
5595
+ email: data.email,
5596
+ email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
5597
+ name: data.name,
5598
+ picture: data.picture,
4521
5599
  isNewUser: false,
4522
5600
  };
4523
5601
  }
@@ -4564,10 +5642,10 @@ class LinkedInProvider extends OAuthProvider {
4564
5642
  return true;
4565
5643
  }
4566
5644
  async linkAccount(_options) {
4567
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for LinkedIn provider');
5645
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for LinkedIn provider');
4568
5646
  }
4569
5647
  async unlinkAccount(_options) {
4570
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for LinkedIn provider');
5648
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for LinkedIn provider');
4571
5649
  }
4572
5650
  async revokeAccess(token) {
4573
5651
  await super.revokeAccess(token);
@@ -4589,7 +5667,7 @@ class UsernamePasswordProvider {
4589
5667
  }
4590
5668
  async signIn(options) {
4591
5669
  if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4592
- throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
5670
+ throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
4593
5671
  }
4594
5672
  try {
4595
5673
  const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
@@ -4606,9 +5684,9 @@ class UsernamePasswordProvider {
4606
5684
  if (!response.ok) {
4607
5685
  const error = await response.json().catch(() => ({}));
4608
5686
  if (response.status === 401) {
4609
- throw new AuthError('INVALID_CREDENTIALS', 'Invalid username or password');
5687
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid username or password');
4610
5688
  }
4611
- throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
5689
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
4612
5690
  }
4613
5691
  const data = await response.json();
4614
5692
  // Create user object
@@ -4656,29 +5734,29 @@ class UsernamePasswordProvider {
4656
5734
  catch (error) {
4657
5735
  if (error instanceof AuthError)
4658
5736
  throw error;
4659
- throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with username and password');
5737
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with username and password');
4660
5738
  }
4661
5739
  }
4662
5740
  async signUp(options) {
4663
5741
  if (!this.config.allowSignUp) {
4664
- throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
5742
+ throw new AuthError(AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
4665
5743
  }
4666
5744
  if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4667
- throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
5745
+ throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
4668
5746
  }
4669
5747
  // Validate username
4670
5748
  const usernameError = this.validateUsername(options.username);
4671
5749
  if (usernameError) {
4672
- throw new AuthError('INVALID_USERNAME', usernameError);
5750
+ throw new AuthError(AuthErrorCode.INVALID_USERNAME, usernameError);
4673
5751
  }
4674
5752
  // Validate password
4675
5753
  const passwordError = this.validatePassword(options.password);
4676
5754
  if (passwordError) {
4677
- throw new AuthError('WEAK_PASSWORD', passwordError);
5755
+ throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
4678
5756
  }
4679
5757
  // Validate email if provided
4680
5758
  if (options.email && !this.isValidEmail(options.email)) {
4681
- throw new AuthError('INVALID_EMAIL', 'Invalid email address');
5759
+ throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
4682
5760
  }
4683
5761
  try {
4684
5762
  const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
@@ -4698,9 +5776,9 @@ class UsernamePasswordProvider {
4698
5776
  if (!response.ok) {
4699
5777
  const error = await response.json().catch(() => ({}));
4700
5778
  if (response.status === 409) {
4701
- throw new AuthError('USERNAME_EXISTS', 'Username already taken');
5779
+ throw new AuthError(AuthErrorCode.USERNAME_ALREADY_EXISTS, 'Username already taken');
4702
5780
  }
4703
- throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
5781
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
4704
5782
  }
4705
5783
  const data = await response.json();
4706
5784
  // Create user object
@@ -4748,7 +5826,7 @@ class UsernamePasswordProvider {
4748
5826
  catch (error) {
4749
5827
  if (error instanceof AuthError)
4750
5828
  throw error;
4751
- throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
5829
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
4752
5830
  }
4753
5831
  }
4754
5832
  async signOut() {
@@ -4778,7 +5856,7 @@ class UsernamePasswordProvider {
4778
5856
  }
4779
5857
  async refreshToken(_options) {
4780
5858
  if (!this.refreshTokenValue) {
4781
- throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
5859
+ throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
4782
5860
  }
4783
5861
  try {
4784
5862
  const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
@@ -4792,7 +5870,7 @@ class UsernamePasswordProvider {
4792
5870
  }),
4793
5871
  });
4794
5872
  if (!response.ok) {
4795
- throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
5873
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
4796
5874
  }
4797
5875
  const data = await response.json();
4798
5876
  // Update tokens
@@ -4814,17 +5892,17 @@ class UsernamePasswordProvider {
4814
5892
  catch (error) {
4815
5893
  if (error instanceof AuthError)
4816
5894
  throw error;
4817
- throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
5895
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
4818
5896
  }
4819
5897
  }
4820
5898
  async updatePassword(currentPassword, newPassword) {
4821
5899
  if (!this.currentUser || !this.authToken) {
4822
- throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
5900
+ throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
4823
5901
  }
4824
5902
  // Validate new password
4825
5903
  const passwordError = this.validatePassword(newPassword);
4826
5904
  if (passwordError) {
4827
- throw new AuthError('WEAK_PASSWORD', passwordError);
5905
+ throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
4828
5906
  }
4829
5907
  try {
4830
5908
  const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
@@ -4842,15 +5920,15 @@ class UsernamePasswordProvider {
4842
5920
  if (!response.ok) {
4843
5921
  const error = await response.json().catch(() => ({}));
4844
5922
  if (response.status === 401) {
4845
- throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
5923
+ throw new AuthError(AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
4846
5924
  }
4847
- throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
5925
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4848
5926
  }
4849
5927
  }
4850
5928
  catch (error) {
4851
5929
  if (error instanceof AuthError)
4852
5930
  throw error;
4853
- throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
5931
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
4854
5932
  }
4855
5933
  }
4856
5934
  async checkUsernameAvailability(username) {
@@ -4930,10 +6008,10 @@ class UsernamePasswordProvider {
4930
6008
  return !!this.config.apiUrl;
4931
6009
  }
4932
6010
  async linkAccount(_options) {
4933
- throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for username/password authentication');
6011
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for username/password authentication');
4934
6012
  }
4935
6013
  async unlinkAccount(_options) {
4936
- throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for username/password authentication');
6014
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for username/password authentication');
4937
6015
  }
4938
6016
  async revokeAccess(_token) {
4939
6017
  // For username/password auth, revoking access means signing out
@@ -4946,6 +6024,639 @@ var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
4946
6024
  UsernamePasswordProvider: UsernamePasswordProvider
4947
6025
  });
4948
6026
 
6027
+ class EmailCodeProvider {
6028
+ constructor(config) {
6029
+ this.name = 'email-code';
6030
+ // Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
6031
+ // page change between sending and verifying the code. Only non-secret metadata is stored —
6032
+ // never the verification code itself (see PendingVerificationStore + F-11).
6033
+ this.pendingVerifications = new PendingVerificationStore('email-code');
6034
+ this.MAX_ATTEMPTS = 3;
6035
+ this.config = Object.assign({ codeLength: 6, resendDelay: 60000, codeExpiration: 10 * 60 * 1000 }, config);
6036
+ }
6037
+ async signIn(options) {
6038
+ if (!(options === null || options === void 0 ? void 0 : options.email)) {
6039
+ throw new AuthError(AuthErrorCode.EMAIL_REQUIRED, 'Email is required for email code authentication');
6040
+ }
6041
+ // Validate email format
6042
+ if (!this.isValidEmail(options.email)) {
6043
+ throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Please enter a valid email address');
6044
+ }
6045
+ // If code is provided, verify it
6046
+ if (options.code) {
6047
+ return this.verifyCode(options.email, options.code);
6048
+ }
6049
+ // Otherwise, send code
6050
+ return this.sendCode(options.email);
6051
+ }
6052
+ async sendCode(email) {
6053
+ try {
6054
+ const normalizedEmail = email.toLowerCase().trim();
6055
+ // Check if we can resend
6056
+ const existing = this.pendingVerifications.get(normalizedEmail);
6057
+ if (existing && existing.lastResent) {
6058
+ const timeSinceLastResend = Date.now() - existing.lastResent;
6059
+ if (timeSinceLastResend < this.config.resendDelay) {
6060
+ const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
6061
+ throw new AuthError(AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
6062
+ }
6063
+ }
6064
+ // Send email code via backend
6065
+ const response = await fetch(this.config.sendCodeUrl, {
6066
+ method: 'POST',
6067
+ headers: {
6068
+ 'Content-Type': 'application/json',
6069
+ },
6070
+ body: JSON.stringify({
6071
+ email: normalizedEmail,
6072
+ clientId: this.config.clientId,
6073
+ codeLength: this.config.codeLength,
6074
+ }),
6075
+ });
6076
+ if (!response.ok) {
6077
+ const error = await response.json().catch(() => ({}));
6078
+ throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6079
+ }
6080
+ const data = await response.json();
6081
+ // Store pending verification (persisted; metadata only, never the code).
6082
+ this.pendingVerifications.set(normalizedEmail, {
6083
+ identifier: normalizedEmail,
6084
+ sessionId: data.sessionId,
6085
+ expires: Date.now() + this.config.codeExpiration,
6086
+ attempts: 0,
6087
+ lastResent: Date.now(),
6088
+ });
6089
+ // Return partial auth result for pending state
6090
+ const tempUser = {
6091
+ uid: `email-code-pending:${data.sessionId}`,
6092
+ email: normalizedEmail,
6093
+ displayName: normalizedEmail.split('@')[0],
6094
+ photoURL: null,
6095
+ phoneNumber: null,
6096
+ emailVerified: false,
6097
+ providerData: [],
6098
+ metadata: {
6099
+ creationTime: new Date().toISOString(),
6100
+ lastSignInTime: new Date().toISOString(),
6101
+ },
6102
+ };
6103
+ return {
6104
+ user: tempUser,
6105
+ credential: {
6106
+ providerId: this.name,
6107
+ signInMethod: 'email-code',
6108
+ accessToken: data.sessionId,
6109
+ },
6110
+ additionalUserInfo: {
6111
+ isNewUser: false,
6112
+ providerId: this.name,
6113
+ profile: {
6114
+ email: normalizedEmail,
6115
+ sessionId: data.sessionId,
6116
+ message: `Verification code sent to ${this.maskEmail(normalizedEmail)}`,
6117
+ pending: true,
6118
+ },
6119
+ },
6120
+ };
6121
+ }
6122
+ catch (error) {
6123
+ if (error instanceof AuthError)
6124
+ throw error;
6125
+ throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6126
+ }
6127
+ }
6128
+ async verifyCode(email, code) {
6129
+ const normalizedEmail = email.toLowerCase().trim();
6130
+ const pending = this.pendingVerifications.get(normalizedEmail);
6131
+ if (!pending) {
6132
+ throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending email verification found. Please request a new code.');
6133
+ }
6134
+ if (Date.now() > pending.expires) {
6135
+ this.pendingVerifications.delete(normalizedEmail);
6136
+ throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
6137
+ }
6138
+ if (pending.attempts >= this.MAX_ATTEMPTS) {
6139
+ this.pendingVerifications.delete(normalizedEmail);
6140
+ throw new AuthError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts. Please request a new code.');
6141
+ }
6142
+ try {
6143
+ // Increment attempts and persist the bump (so the count survives a reload mid-flow).
6144
+ pending.attempts++;
6145
+ this.pendingVerifications.set(normalizedEmail, pending);
6146
+ // Verify code with backend
6147
+ const response = await fetch(this.config.verifyCodeUrl, {
6148
+ method: 'POST',
6149
+ headers: {
6150
+ 'Content-Type': 'application/json',
6151
+ },
6152
+ body: JSON.stringify({
6153
+ email: normalizedEmail,
6154
+ code,
6155
+ sessionId: pending.sessionId,
6156
+ clientId: this.config.clientId,
6157
+ }),
6158
+ });
6159
+ if (!response.ok) {
6160
+ const error = await response.json().catch(() => ({}));
6161
+ if (response.status === 401) {
6162
+ throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid verification code');
6163
+ }
6164
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
6165
+ }
6166
+ const data = await response.json();
6167
+ // Create user from verified data
6168
+ const user = {
6169
+ uid: data.uid || this.generateUid(normalizedEmail),
6170
+ email: normalizedEmail,
6171
+ displayName: data.displayName || normalizedEmail.split('@')[0],
6172
+ photoURL: data.photoURL || null,
6173
+ phoneNumber: data.phoneNumber || null,
6174
+ emailVerified: true,
6175
+ providerData: [
6176
+ {
6177
+ providerId: this.name,
6178
+ uid: data.uid || normalizedEmail,
6179
+ displayName: data.displayName || normalizedEmail.split('@')[0],
6180
+ email: normalizedEmail,
6181
+ phoneNumber: null,
6182
+ photoURL: data.photoURL || null,
6183
+ },
6184
+ ],
6185
+ metadata: {
6186
+ creationTime: data.createdAt || new Date().toISOString(),
6187
+ lastSignInTime: new Date().toISOString(),
6188
+ },
6189
+ };
6190
+ // Clean up pending verification
6191
+ this.pendingVerifications.delete(normalizedEmail);
6192
+ return {
6193
+ user,
6194
+ credential: {
6195
+ providerId: this.name,
6196
+ signInMethod: 'email-code',
6197
+ accessToken: data.accessToken,
6198
+ refreshToken: data.refreshToken,
6199
+ expiresAt: data.expiresAt,
6200
+ },
6201
+ additionalUserInfo: {
6202
+ isNewUser: data.isNewUser || false,
6203
+ providerId: this.name,
6204
+ },
6205
+ };
6206
+ }
6207
+ catch (error) {
6208
+ if (error instanceof AuthError)
6209
+ throw error;
6210
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
6211
+ }
6212
+ }
6213
+ async signOut() {
6214
+ this.pendingVerifications.clear();
6215
+ }
6216
+ async getCurrentUser() {
6217
+ return null;
6218
+ }
6219
+ async refreshToken(_options) {
6220
+ // Email code authentication is single-use and has no refresh flow; the user must request
6221
+ // a new verification code rather than refresh a token.
6222
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication does not support token refresh; request a new code instead.');
6223
+ }
6224
+ async initialize() {
6225
+ // Email code provider doesn't require initialization
6226
+ }
6227
+ async isSupported() {
6228
+ return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
6229
+ }
6230
+ async linkAccount(_options) {
6231
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for email code authentication');
6232
+ }
6233
+ async unlinkAccount(_options) {
6234
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for email code authentication');
6235
+ }
6236
+ async revokeAccess(_token) {
6237
+ this.pendingVerifications.clear();
6238
+ }
6239
+ // Public method to resend code
6240
+ async resendCode(email) {
6241
+ return this.sendCode(email);
6242
+ }
6243
+ // Public method to check if can resend
6244
+ canResendCode(email) {
6245
+ const normalizedEmail = email.toLowerCase().trim();
6246
+ const pending = this.pendingVerifications.get(normalizedEmail);
6247
+ if (!pending || !pending.lastResent) {
6248
+ return { canResend: true };
6249
+ }
6250
+ const timeSinceLastResend = Date.now() - pending.lastResent;
6251
+ if (timeSinceLastResend < this.config.resendDelay) {
6252
+ return {
6253
+ canResend: false,
6254
+ waitTime: Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000),
6255
+ };
6256
+ }
6257
+ return { canResend: true };
6258
+ }
6259
+ isValidEmail(email) {
6260
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
6261
+ return emailRegex.test(email);
6262
+ }
6263
+ maskEmail(email) {
6264
+ const [local, domain] = email.split('@');
6265
+ if (local.length <= 2) {
6266
+ return `${local[0]}***@${domain}`;
6267
+ }
6268
+ return `${local[0]}***${local[local.length - 1]}@${domain}`;
6269
+ }
6270
+ generateUid(email) {
6271
+ return `email-code:${email.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
6272
+ }
6273
+ }
6274
+
6275
+ var emailCodeProvider = /*#__PURE__*/Object.freeze({
6276
+ __proto__: null,
6277
+ EmailCodeProvider: EmailCodeProvider
6278
+ });
6279
+
6280
+ class PhonePasswordProvider {
6281
+ constructor(config) {
6282
+ this.name = 'phone-password';
6283
+ this.pendingVerifications = new Map();
6284
+ this.currentUser = null;
6285
+ this.storedAccessToken = null;
6286
+ this.storedRefreshToken = null;
6287
+ this.config = Object.assign({ countryCode: '+1', requirePhoneVerification: false, passwordStrength: {
6288
+ minLength: 8,
6289
+ requireUppercase: true,
6290
+ requireLowercase: true,
6291
+ requireNumbers: true,
6292
+ requireSpecialChars: false,
6293
+ } }, config);
6294
+ }
6295
+ async signIn(options) {
6296
+ const credentials = options === null || options === void 0 ? void 0 : options.credentials;
6297
+ if (!(credentials === null || credentials === void 0 ? void 0 : credentials.phoneNumber) || !(credentials === null || credentials === void 0 ? void 0 : credentials.password)) {
6298
+ throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Phone number and password are required');
6299
+ }
6300
+ const formattedPhone = this.formatPhoneNumber(credentials.phoneNumber);
6301
+ // Handle sign up flow
6302
+ if (options === null || options === void 0 ? void 0 : options.isSignUp) {
6303
+ return this.signUp(formattedPhone, credentials.password);
6304
+ }
6305
+ // Handle phone verification if code is provided
6306
+ if (credentials.code && this.config.requirePhoneVerification) {
6307
+ return this.verifyPhone(formattedPhone, credentials.code, credentials.password);
6308
+ }
6309
+ // Standard sign in
6310
+ return this.performSignIn(formattedPhone, credentials.password);
6311
+ }
6312
+ async performSignIn(phoneNumber, password) {
6313
+ try {
6314
+ const response = await fetch(this.config.signInUrl, {
6315
+ method: 'POST',
6316
+ headers: {
6317
+ 'Content-Type': 'application/json',
6318
+ },
6319
+ body: JSON.stringify({
6320
+ phoneNumber,
6321
+ password,
6322
+ clientId: this.config.clientId,
6323
+ }),
6324
+ });
6325
+ if (!response.ok) {
6326
+ const error = await response.json().catch(() => ({}));
6327
+ if (response.status === 401) {
6328
+ throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid phone number or password');
6329
+ }
6330
+ if (response.status === 403) {
6331
+ throw new AuthError(AuthErrorCode.PHONE_NOT_VERIFIED, 'Please verify your phone number first');
6332
+ }
6333
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
6334
+ }
6335
+ const data = await response.json();
6336
+ return this.createAuthResult(data, phoneNumber);
6337
+ }
6338
+ catch (error) {
6339
+ if (error instanceof AuthError)
6340
+ throw error;
6341
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
6342
+ }
6343
+ }
6344
+ async signUp(phoneNumber, password) {
6345
+ // Validate password strength
6346
+ this.validatePassword(password);
6347
+ try {
6348
+ const response = await fetch(this.config.signUpUrl, {
6349
+ method: 'POST',
6350
+ headers: {
6351
+ 'Content-Type': 'application/json',
6352
+ },
6353
+ body: JSON.stringify({
6354
+ phoneNumber,
6355
+ password,
6356
+ clientId: this.config.clientId,
6357
+ }),
6358
+ });
6359
+ if (!response.ok) {
6360
+ const error = await response.json().catch(() => ({}));
6361
+ if (response.status === 409) {
6362
+ throw new AuthError(AuthErrorCode.PHONE_NUMBER_ALREADY_EXISTS, 'An account with this phone number already exists');
6363
+ }
6364
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
6365
+ }
6366
+ const data = await response.json();
6367
+ // If phone verification is required, send verification code
6368
+ if (this.config.requirePhoneVerification && this.config.sendVerificationUrl) {
6369
+ await this.sendVerificationCode(phoneNumber);
6370
+ return {
6371
+ user: {
6372
+ uid: `phone-pending:${data.sessionId || phoneNumber}`,
6373
+ email: null,
6374
+ displayName: this.maskPhoneNumber(phoneNumber),
6375
+ photoURL: null,
6376
+ phoneNumber,
6377
+ emailVerified: false,
6378
+ providerData: [],
6379
+ metadata: {
6380
+ creationTime: new Date().toISOString(),
6381
+ lastSignInTime: new Date().toISOString(),
6382
+ },
6383
+ },
6384
+ credential: {
6385
+ providerId: this.name,
6386
+ signInMethod: 'phone-password',
6387
+ accessToken: data.sessionId,
6388
+ },
6389
+ additionalUserInfo: {
6390
+ isNewUser: true,
6391
+ providerId: this.name,
6392
+ profile: {
6393
+ phoneNumber,
6394
+ message: 'Phone verification required. Check your SMS.',
6395
+ pending: true,
6396
+ },
6397
+ },
6398
+ };
6399
+ }
6400
+ return this.createAuthResult(data, phoneNumber, true);
6401
+ }
6402
+ catch (error) {
6403
+ if (error instanceof AuthError)
6404
+ throw error;
6405
+ throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
6406
+ }
6407
+ }
6408
+ async sendVerificationCode(phoneNumber) {
6409
+ if (!this.config.sendVerificationUrl) {
6410
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
6411
+ }
6412
+ const response = await fetch(this.config.sendVerificationUrl, {
6413
+ method: 'POST',
6414
+ headers: {
6415
+ 'Content-Type': 'application/json',
6416
+ },
6417
+ body: JSON.stringify({
6418
+ phoneNumber,
6419
+ clientId: this.config.clientId,
6420
+ }),
6421
+ });
6422
+ if (!response.ok) {
6423
+ const error = await response.json().catch(() => ({}));
6424
+ throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
6425
+ }
6426
+ const data = await response.json();
6427
+ this.pendingVerifications.set(phoneNumber, {
6428
+ phoneNumber,
6429
+ sessionId: data.sessionId,
6430
+ expires: Date.now() + 10 * 60 * 1000, // 10 minutes
6431
+ });
6432
+ }
6433
+ async verifyPhone(phoneNumber, code, password) {
6434
+ if (!this.config.verifyPhoneUrl) {
6435
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
6436
+ }
6437
+ const pending = this.pendingVerifications.get(phoneNumber);
6438
+ if (!pending) {
6439
+ throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending phone verification found');
6440
+ }
6441
+ if (Date.now() > pending.expires) {
6442
+ this.pendingVerifications.delete(phoneNumber);
6443
+ throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
6444
+ }
6445
+ try {
6446
+ const response = await fetch(this.config.verifyPhoneUrl, {
6447
+ method: 'POST',
6448
+ headers: {
6449
+ 'Content-Type': 'application/json',
6450
+ },
6451
+ body: JSON.stringify({
6452
+ phoneNumber,
6453
+ code,
6454
+ password,
6455
+ sessionId: pending.sessionId,
6456
+ clientId: this.config.clientId,
6457
+ }),
6458
+ });
6459
+ if (!response.ok) {
6460
+ const error = await response.json().catch(() => ({}));
6461
+ if (response.status === 401) {
6462
+ throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid verification code');
6463
+ }
6464
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
6465
+ }
6466
+ const data = await response.json();
6467
+ this.pendingVerifications.delete(phoneNumber);
6468
+ return this.createAuthResult(data, phoneNumber);
6469
+ }
6470
+ catch (error) {
6471
+ if (error instanceof AuthError)
6472
+ throw error;
6473
+ throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
6474
+ }
6475
+ }
6476
+ async signOut() {
6477
+ this.currentUser = null;
6478
+ this.storedAccessToken = null;
6479
+ this.storedRefreshToken = null;
6480
+ this.pendingVerifications.clear();
6481
+ }
6482
+ async getCurrentUser() {
6483
+ return this.currentUser;
6484
+ }
6485
+ async refreshToken(_options) {
6486
+ if (!this.storedRefreshToken || !this.config.refreshTokenUrl) {
6487
+ throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available or refresh URL not configured');
6488
+ }
6489
+ try {
6490
+ const response = await fetch(this.config.refreshTokenUrl, {
6491
+ method: 'POST',
6492
+ headers: {
6493
+ 'Content-Type': 'application/json',
6494
+ },
6495
+ body: JSON.stringify({
6496
+ refreshToken: this.storedRefreshToken,
6497
+ clientId: this.config.clientId,
6498
+ }),
6499
+ });
6500
+ if (!response.ok) {
6501
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Token refresh failed');
6502
+ }
6503
+ const data = await response.json();
6504
+ this.storedAccessToken = data.accessToken;
6505
+ if (data.refreshToken) {
6506
+ this.storedRefreshToken = data.refreshToken;
6507
+ }
6508
+ if (!this.currentUser) {
6509
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No current user');
6510
+ }
6511
+ return {
6512
+ user: this.currentUser,
6513
+ credential: {
6514
+ providerId: this.name,
6515
+ signInMethod: 'phone-password',
6516
+ accessToken: data.accessToken,
6517
+ refreshToken: data.refreshToken || this.storedRefreshToken,
6518
+ expiresAt: data.expiresAt,
6519
+ },
6520
+ additionalUserInfo: {
6521
+ isNewUser: false,
6522
+ providerId: this.name,
6523
+ },
6524
+ };
6525
+ }
6526
+ catch (error) {
6527
+ if (error instanceof AuthError)
6528
+ throw error;
6529
+ throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Token refresh failed');
6530
+ }
6531
+ }
6532
+ async initialize() {
6533
+ // Phone password provider doesn't require initialization
6534
+ }
6535
+ async isSupported() {
6536
+ return !!(this.config.signInUrl && this.config.signUpUrl);
6537
+ }
6538
+ async linkAccount(_options) {
6539
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for phone/password authentication');
6540
+ }
6541
+ async unlinkAccount(_options) {
6542
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for phone/password authentication');
6543
+ }
6544
+ async revokeAccess(_token) {
6545
+ await this.signOut();
6546
+ }
6547
+ getAccessToken() {
6548
+ return this.storedAccessToken;
6549
+ }
6550
+ async sendPasswordReset(phoneNumber) {
6551
+ if (!this.config.resetPasswordUrl) {
6552
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Password reset URL not configured');
6553
+ }
6554
+ const formattedPhone = this.formatPhoneNumber(phoneNumber);
6555
+ const response = await fetch(this.config.resetPasswordUrl, {
6556
+ method: 'POST',
6557
+ headers: {
6558
+ 'Content-Type': 'application/json',
6559
+ },
6560
+ body: JSON.stringify({
6561
+ phoneNumber: formattedPhone,
6562
+ clientId: this.config.clientId,
6563
+ }),
6564
+ });
6565
+ if (!response.ok) {
6566
+ const error = await response.json().catch(() => ({}));
6567
+ throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset');
6568
+ }
6569
+ }
6570
+ createAuthResult(data, phoneNumber, isNewUser = false) {
6571
+ const user = {
6572
+ uid: data.uid || this.generateUid(phoneNumber),
6573
+ email: data.email || null,
6574
+ displayName: data.displayName || phoneNumber,
6575
+ photoURL: data.photoURL || null,
6576
+ phoneNumber,
6577
+ emailVerified: false,
6578
+ providerData: [
6579
+ {
6580
+ providerId: this.name,
6581
+ uid: data.uid || phoneNumber,
6582
+ displayName: data.displayName || phoneNumber,
6583
+ email: data.email || null,
6584
+ phoneNumber,
6585
+ photoURL: data.photoURL || null,
6586
+ },
6587
+ ],
6588
+ metadata: {
6589
+ creationTime: data.createdAt || new Date().toISOString(),
6590
+ lastSignInTime: new Date().toISOString(),
6591
+ },
6592
+ };
6593
+ this.currentUser = user;
6594
+ this.storedAccessToken = data.accessToken;
6595
+ this.storedRefreshToken = data.refreshToken;
6596
+ return {
6597
+ user,
6598
+ credential: {
6599
+ providerId: this.name,
6600
+ signInMethod: 'phone-password',
6601
+ accessToken: data.accessToken,
6602
+ refreshToken: data.refreshToken,
6603
+ expiresAt: data.expiresAt,
6604
+ },
6605
+ additionalUserInfo: {
6606
+ isNewUser: data.isNewUser || isNewUser,
6607
+ providerId: this.name,
6608
+ },
6609
+ };
6610
+ }
6611
+ validatePassword(password) {
6612
+ const { passwordStrength } = this.config;
6613
+ if (!passwordStrength)
6614
+ return;
6615
+ const errors = [];
6616
+ if (passwordStrength.minLength && password.length < passwordStrength.minLength) {
6617
+ errors.push(`at least ${passwordStrength.minLength} characters`);
6618
+ }
6619
+ if (passwordStrength.requireUppercase && !/[A-Z]/.test(password)) {
6620
+ errors.push('an uppercase letter');
6621
+ }
6622
+ if (passwordStrength.requireLowercase && !/[a-z]/.test(password)) {
6623
+ errors.push('a lowercase letter');
6624
+ }
6625
+ if (passwordStrength.requireNumbers && !/\d/.test(password)) {
6626
+ errors.push('a number');
6627
+ }
6628
+ if (passwordStrength.requireSpecialChars && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
6629
+ errors.push('a special character');
6630
+ }
6631
+ if (errors.length > 0) {
6632
+ throw new AuthError(AuthErrorCode.WEAK_PASSWORD, `Password must contain ${errors.join(', ')}`);
6633
+ }
6634
+ }
6635
+ formatPhoneNumber(phoneNumber) {
6636
+ let cleaned = phoneNumber.replace(/\D/g, '');
6637
+ if (!phoneNumber.startsWith('+')) {
6638
+ if (cleaned.length === 10) {
6639
+ cleaned = '1' + cleaned;
6640
+ }
6641
+ cleaned = this.config.countryCode.replace('+', '') + cleaned;
6642
+ }
6643
+ return '+' + cleaned;
6644
+ }
6645
+ maskPhoneNumber(phoneNumber) {
6646
+ const digits = phoneNumber.replace(/\D/g, '');
6647
+ const lastFour = digits.slice(-4);
6648
+ return `***-***-${lastFour}`;
6649
+ }
6650
+ generateUid(phoneNumber) {
6651
+ return `phone-password:${phoneNumber.replace(/\D/g, '')}`;
6652
+ }
6653
+ }
6654
+
6655
+ var phonePasswordProvider = /*#__PURE__*/Object.freeze({
6656
+ __proto__: null,
6657
+ PhonePasswordProvider: PhonePasswordProvider
6658
+ });
6659
+
4949
6660
  exports.PlatformDetector = PlatformDetector;
4950
6661
  exports.ProviderRegistry = ProviderRegistry;
4951
6662
  exports.auth = auth;