capacitor-auth-manager 1.0.0 → 2.1.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 (96) hide show
  1. package/Readme.md +395 -441
  2. package/dist/core.cjs.js +4952 -0
  3. package/dist/core.cjs.js.map +1 -0
  4. package/dist/esm/capacitor-plugin.d.ts +3 -0
  5. package/dist/esm/capacitor-plugin.js +7 -0
  6. package/dist/esm/capacitor-plugin.js.map +1 -0
  7. package/dist/esm/core/auth-manager.d.ts +33 -0
  8. package/dist/esm/core/auth-manager.js +296 -0
  9. package/dist/esm/core/auth-manager.js.map +1 -0
  10. package/dist/esm/core/index.d.ts +4 -0
  11. package/dist/esm/core/index.js +5 -0
  12. package/dist/esm/core/index.js.map +1 -0
  13. package/dist/esm/core/platform.d.ts +17 -0
  14. package/dist/esm/core/platform.js +80 -0
  15. package/dist/esm/core/platform.js.map +1 -0
  16. package/dist/esm/core/provider-registry.d.ts +21 -0
  17. package/dist/esm/core/provider-registry.js +605 -0
  18. package/dist/esm/core/provider-registry.js.map +1 -0
  19. package/dist/esm/core/types.d.ts +35 -0
  20. package/dist/esm/core/types.js +2 -0
  21. package/dist/esm/core/types.js.map +1 -0
  22. package/dist/esm/definitions.d.ts +45 -10
  23. package/dist/esm/definitions.js +14 -4
  24. package/dist/esm/definitions.js.map +1 -1
  25. package/dist/esm/index.d.ts +8 -4
  26. package/dist/esm/index.js +9 -6
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/providers/base-provider.d.ts +3 -1
  29. package/dist/esm/providers/base-provider.js +8 -5
  30. package/dist/esm/providers/base-provider.js.map +1 -1
  31. package/dist/esm/providers/oauth-provider.d.ts +38 -7
  32. package/dist/esm/providers/oauth-provider.js +35 -28
  33. package/dist/esm/providers/oauth-provider.js.map +1 -1
  34. package/dist/esm/providers/provider-factory.js +1 -1
  35. package/dist/esm/providers/provider-factory.js.map +1 -1
  36. package/dist/esm/providers/web/apple-provider.d.ts +32 -5
  37. package/dist/esm/providers/web/apple-provider.js +42 -35
  38. package/dist/esm/providers/web/apple-provider.js.map +1 -1
  39. package/dist/esm/providers/web/biometric-provider.d.ts +47 -0
  40. package/dist/esm/providers/web/biometric-provider.js +267 -0
  41. package/dist/esm/providers/web/biometric-provider.js.map +1 -0
  42. package/dist/esm/providers/web/email-password-provider.d.ts +55 -0
  43. package/dist/esm/providers/web/email-password-provider.js +429 -0
  44. package/dist/esm/providers/web/email-password-provider.js.map +1 -0
  45. package/dist/esm/providers/web/facebook-provider.d.ts +29 -0
  46. package/dist/esm/providers/web/facebook-provider.js +249 -0
  47. package/dist/esm/providers/web/facebook-provider.js.map +1 -0
  48. package/dist/esm/providers/web/firebase-provider.d.ts +20 -0
  49. package/dist/esm/providers/web/firebase-provider.js +306 -0
  50. package/dist/esm/providers/web/firebase-provider.js.map +1 -0
  51. package/dist/esm/providers/web/github-provider.d.ts +25 -0
  52. package/dist/esm/providers/web/github-provider.js +248 -0
  53. package/dist/esm/providers/web/github-provider.js.map +1 -0
  54. package/dist/esm/providers/web/google-provider.d.ts +98 -7
  55. package/dist/esm/providers/web/google-provider.js +37 -23
  56. package/dist/esm/providers/web/google-provider.js.map +1 -1
  57. package/dist/esm/providers/web/index.d.ts +13 -0
  58. package/dist/esm/providers/web/index.js +15 -0
  59. package/dist/esm/providers/web/index.js.map +1 -0
  60. package/dist/esm/providers/web/linkedin-provider.d.ts +38 -0
  61. package/dist/esm/providers/web/linkedin-provider.js +152 -0
  62. package/dist/esm/providers/web/linkedin-provider.js.map +1 -0
  63. package/dist/esm/providers/web/magic-link-provider.d.ts +46 -0
  64. package/dist/esm/providers/web/magic-link-provider.js +298 -0
  65. package/dist/esm/providers/web/magic-link-provider.js.map +1 -0
  66. package/dist/esm/providers/web/microsoft-provider.d.ts +21 -0
  67. package/dist/esm/providers/web/microsoft-provider.js +211 -0
  68. package/dist/esm/providers/web/microsoft-provider.js.map +1 -0
  69. package/dist/esm/providers/web/slack-provider.d.ts +40 -0
  70. package/dist/esm/providers/web/slack-provider.js +151 -0
  71. package/dist/esm/providers/web/slack-provider.js.map +1 -0
  72. package/dist/esm/providers/web/sms-provider.d.ts +48 -0
  73. package/dist/esm/providers/web/sms-provider.js +301 -0
  74. package/dist/esm/providers/web/sms-provider.js.map +1 -0
  75. package/dist/esm/providers/web/username-password-provider.d.ts +62 -0
  76. package/dist/esm/providers/web/username-password-provider.js +432 -0
  77. package/dist/esm/providers/web/username-password-provider.js.map +1 -0
  78. package/dist/esm/utils/auth-error.d.ts +5 -5
  79. package/dist/esm/utils/auth-error.js +14 -5
  80. package/dist/esm/utils/auth-error.js.map +1 -1
  81. package/dist/esm/utils/event-emitter.d.ts +2 -2
  82. package/dist/esm/utils/event-emitter.js +1 -1
  83. package/dist/esm/utils/event-emitter.js.map +1 -1
  84. package/dist/esm/utils/logger.d.ts +4 -4
  85. package/dist/esm/utils/logger.js.map +1 -1
  86. package/dist/esm/utils/storage.d.ts +4 -4
  87. package/dist/esm/utils/storage.js +13 -3
  88. package/dist/esm/utils/storage.js.map +1 -1
  89. package/dist/esm/web.js +7 -3
  90. package/dist/esm/web.js.map +1 -1
  91. package/dist/plugin.cjs.js +4172 -407
  92. package/dist/plugin.cjs.js.map +1 -1
  93. package/dist/plugin.js +4172 -407
  94. package/dist/plugin.js.map +1 -1
  95. package/package.json +79 -18
  96. package/scripts/configure.js +105 -61
@@ -2,6 +2,82 @@
2
2
 
3
3
  var core = require('@capacitor/core');
4
4
 
5
+ class EventEmitter {
6
+ constructor() {
7
+ this.listeners = new Set();
8
+ }
9
+ emit(data) {
10
+ this.listeners.forEach((listener) => {
11
+ try {
12
+ listener(data);
13
+ }
14
+ catch (error) {
15
+ console.error('Error in event listener:', error);
16
+ }
17
+ });
18
+ }
19
+ subscribe(listener) {
20
+ this.listeners.add(listener);
21
+ return () => {
22
+ this.listeners.delete(listener);
23
+ };
24
+ }
25
+ clear() {
26
+ this.listeners.clear();
27
+ }
28
+ get listenerCount() {
29
+ return this.listeners.size;
30
+ }
31
+ }
32
+
33
+ class Logger {
34
+ constructor(config) {
35
+ this.logLevels = {
36
+ debug: 0,
37
+ info: 1,
38
+ warn: 2,
39
+ error: 3,
40
+ };
41
+ this.config = config;
42
+ }
43
+ shouldLog(level) {
44
+ if (!this.config.enableLogging)
45
+ return false;
46
+ return this.logLevels[level] >= this.logLevels[this.config.logLevel];
47
+ }
48
+ formatMessage(level, message) {
49
+ const timestamp = new Date().toISOString();
50
+ const prefix = this.config.prefix || 'CapacitorAuthManager';
51
+ return `[${timestamp}] [${prefix}] [${level.toUpperCase()}] ${message}`;
52
+ }
53
+ debug(message, ...args) {
54
+ if (this.shouldLog('debug')) {
55
+ console.debug(this.formatMessage('debug', message), ...args);
56
+ }
57
+ }
58
+ info(message, ...args) {
59
+ if (this.shouldLog('info')) {
60
+ console.info(this.formatMessage('info', message), ...args);
61
+ }
62
+ }
63
+ warn(message, ...args) {
64
+ if (this.shouldLog('warn')) {
65
+ console.warn(this.formatMessage('warn', message), ...args);
66
+ }
67
+ }
68
+ error(message, error) {
69
+ if (this.shouldLog('error')) {
70
+ console.error(this.formatMessage('error', message), error);
71
+ }
72
+ }
73
+ setLogLevel(level) {
74
+ this.config.logLevel = level;
75
+ }
76
+ setEnabled(enabled) {
77
+ this.config.enableLogging = enabled;
78
+ }
79
+ }
80
+
5
81
  exports.AuthProvider = void 0;
6
82
  (function (AuthProvider) {
7
83
  AuthProvider["GOOGLE"] = "google";
@@ -13,13 +89,16 @@ exports.AuthProvider = void 0;
13
89
  AuthProvider["LINKEDIN"] = "linkedin";
14
90
  AuthProvider["FIREBASE"] = "firebase";
15
91
  AuthProvider["EMAIL_MAGIC_LINK"] = "email_magic_link";
92
+ AuthProvider["MAGIC_LINK"] = "magic-link";
16
93
  AuthProvider["SMS"] = "sms";
17
- AuthProvider["EMAIL_PASSWORD"] = "email_password";
94
+ AuthProvider["EMAIL_PASSWORD"] = "email-password";
18
95
  AuthProvider["PHONE_PASSWORD"] = "phone_password";
19
96
  AuthProvider["USERNAME_PASSWORD"] = "username_password";
20
97
  AuthProvider["EMAIL_CODE"] = "email_code";
21
98
  AuthProvider["BIOMETRIC"] = "biometric";
22
99
  })(exports.AuthProvider || (exports.AuthProvider = {}));
100
+ // Additional provider values for backward compatibility
101
+ Object.assign(Object.assign({}, exports.AuthProvider), { 'magic-link': exports.AuthProvider.MAGIC_LINK, 'email-password': exports.AuthProvider.EMAIL_PASSWORD, sms: exports.AuthProvider.SMS, biometric: exports.AuthProvider.BIOMETRIC });
23
102
  exports.AppleAuthScope = void 0;
24
103
  (function (AppleAuthScope) {
25
104
  AppleAuthScope["EMAIL"] = "email";
@@ -98,95 +177,21 @@ exports.AuthErrorCode = void 0;
98
177
  AuthErrorCode["CONSENT_REQUIRED"] = "auth/consent-required";
99
178
  AuthErrorCode["INVALID_GRANT"] = "auth/invalid-grant";
100
179
  AuthErrorCode["UNSUPPORTED_GRANT_TYPE"] = "auth/unsupported-grant-type";
101
- AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
102
- AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
103
- AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
180
+ AuthErrorCode["PROVIDER_INIT_FAILED"] = "auth/provider-init-failed";
181
+ AuthErrorCode["SIGN_IN_FAILED"] = "auth/sign-in-failed";
182
+ AuthErrorCode["SIGN_OUT_FAILED"] = "auth/sign-out-failed";
183
+ AuthErrorCode["NO_AUTH_SESSION"] = "auth/no-auth-session";
184
+ AuthErrorCode["TOKEN_REFRESH_FAILED"] = "auth/token-refresh-failed";
104
185
  AuthErrorCode["ACCESS_DENIED"] = "auth/access-denied";
105
186
  AuthErrorCode["SERVER_ERROR"] = "auth/server-error";
106
187
  AuthErrorCode["TEMPORARILY_UNAVAILABLE"] = "auth/temporarily-unavailable";
188
+ AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
189
+ AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
190
+ AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
191
+ AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
192
+ AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
107
193
  })(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
108
194
 
109
- const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
110
- web: () => Promise.resolve().then(function () { return web; }).then(m => new m.CapacitorAuthManagerWeb()),
111
- });
112
-
113
- class AuthError extends Error {
114
- constructor(code, message, provider, details) {
115
- super(message);
116
- this.name = 'AuthError';
117
- this.code = code;
118
- this.provider = provider;
119
- this.details = details;
120
- // Maintains proper stack trace for where our error was thrown (only available on V8)
121
- if (Error.captureStackTrace) {
122
- Error.captureStackTrace(this, AuthError);
123
- }
124
- }
125
- static fromError(error, provider) {
126
- if (error instanceof AuthError) {
127
- return error;
128
- }
129
- let code = exports.AuthErrorCode.INTERNAL_ERROR;
130
- let message = 'An unknown error occurred';
131
- let details = error;
132
- if (error instanceof Error) {
133
- message = error.message;
134
- // Try to map common error patterns to specific error codes
135
- if (error.message.includes('network')) {
136
- code = exports.AuthErrorCode.NETWORK_ERROR;
137
- }
138
- else if (error.message.includes('cancelled') || error.message.includes('canceled')) {
139
- code = exports.AuthErrorCode.USER_CANCELLED;
140
- }
141
- else if (error.message.includes('timeout')) {
142
- code = exports.AuthErrorCode.NETWORK_ERROR;
143
- }
144
- }
145
- // Handle provider-specific error codes
146
- if (error === null || error === void 0 ? void 0 : error.code) {
147
- code = error.code;
148
- }
149
- return new AuthError(code, message, provider, details);
150
- }
151
- toJSON() {
152
- return {
153
- name: this.name,
154
- code: this.code,
155
- message: this.message,
156
- provider: this.provider,
157
- details: this.details,
158
- };
159
- }
160
- }
161
-
162
- class EventEmitter {
163
- constructor() {
164
- this.listeners = new Set();
165
- }
166
- emit(data) {
167
- this.listeners.forEach(listener => {
168
- try {
169
- listener(data);
170
- }
171
- catch (error) {
172
- console.error('Error in event listener:', error);
173
- }
174
- });
175
- }
176
- subscribe(listener) {
177
- this.listeners.add(listener);
178
- return () => {
179
- this.listeners.delete(listener);
180
- };
181
- }
182
- clear() {
183
- this.listeners.clear();
184
- }
185
- get listenerCount() {
186
- return this.listeners.size;
187
- }
188
- }
189
-
190
195
  class WebStorage {
191
196
  constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_') {
192
197
  this.prefix = prefix;
@@ -207,7 +212,16 @@ class WebStorage {
207
212
  }
208
213
  async get(key) {
209
214
  try {
210
- return this.storage.getItem(this.prefix + key);
215
+ const value = this.storage.getItem(this.prefix + key);
216
+ if (value) {
217
+ try {
218
+ return JSON.parse(value);
219
+ }
220
+ catch (_a) {
221
+ return value;
222
+ }
223
+ }
224
+ return null;
211
225
  }
212
226
  catch (error) {
213
227
  console.error('Storage get error:', error);
@@ -216,7 +230,8 @@ class WebStorage {
216
230
  }
217
231
  async set(key, value) {
218
232
  try {
219
- this.storage.setItem(this.prefix + key, value);
233
+ const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
234
+ this.storage.setItem(this.prefix + key, stringValue);
220
235
  }
221
236
  catch (error) {
222
237
  console.error('Storage set error:', error);
@@ -240,7 +255,7 @@ class WebStorage {
240
255
  keys.push(key);
241
256
  }
242
257
  }
243
- keys.forEach(key => this.storage.removeItem(key));
258
+ keys.forEach((key) => this.storage.removeItem(key));
244
259
  }
245
260
  catch (error) {
246
261
  console.error('Storage clear error:', error);
@@ -272,70 +287,1065 @@ class InMemoryStorage {
272
287
  }
273
288
  }
274
289
 
275
- class Logger {
276
- constructor(config) {
277
- this.logLevels = {
278
- debug: 0,
279
- info: 1,
280
- warn: 2,
281
- error: 3,
282
- };
283
- this.config = config;
284
- }
285
- shouldLog(level) {
286
- if (!this.config.enableLogging)
287
- return false;
288
- return this.logLevels[level] >= this.logLevels[this.config.logLevel];
289
- }
290
- formatMessage(level, message) {
291
- const timestamp = new Date().toISOString();
292
- const prefix = this.config.prefix || 'CapacitorAuthManager';
293
- return `[${timestamp}] [${prefix}] [${level.toUpperCase()}] ${message}`;
294
- }
295
- debug(message, ...args) {
296
- if (this.shouldLog('debug')) {
297
- console.debug(this.formatMessage('debug', message), ...args);
290
+ class AuthError extends Error {
291
+ constructor(code, message, provider, details) {
292
+ super(message);
293
+ this.name = 'AuthError';
294
+ this.code = code;
295
+ this.provider = provider;
296
+ this.details = details;
297
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
298
+ if (Error.captureStackTrace) {
299
+ Error.captureStackTrace(this, AuthError);
298
300
  }
299
301
  }
300
- info(message, ...args) {
301
- if (this.shouldLog('info')) {
302
- console.info(this.formatMessage('info', message), ...args);
302
+ static fromError(error, provider) {
303
+ if (error instanceof AuthError) {
304
+ return error;
303
305
  }
304
- }
305
- warn(message, ...args) {
306
- if (this.shouldLog('warn')) {
307
- console.warn(this.formatMessage('warn', message), ...args);
306
+ let code = exports.AuthErrorCode.INTERNAL_ERROR;
307
+ let message = 'An unknown error occurred';
308
+ let details = error;
309
+ if (error instanceof Error) {
310
+ message = error.message;
311
+ // Try to map common error patterns to specific error codes
312
+ if (error.message.includes('network')) {
313
+ code = exports.AuthErrorCode.NETWORK_ERROR;
314
+ }
315
+ else if (error.message.includes('cancelled') ||
316
+ error.message.includes('canceled')) {
317
+ code = exports.AuthErrorCode.USER_CANCELLED;
318
+ }
319
+ else if (error.message.includes('timeout')) {
320
+ code = exports.AuthErrorCode.NETWORK_ERROR;
321
+ }
308
322
  }
309
- }
310
- error(message, error) {
311
- if (this.shouldLog('error')) {
312
- console.error(this.formatMessage('error', message), error);
323
+ // Handle provider-specific error codes
324
+ const errorObj = error;
325
+ if (errorObj === null || errorObj === void 0 ? void 0 : errorObj.code) {
326
+ // Check if the code is a valid AuthErrorCode
327
+ if (Object.values(exports.AuthErrorCode).includes(errorObj.code)) {
328
+ code = errorObj.code;
329
+ }
313
330
  }
331
+ return new AuthError(code, message, provider, details);
314
332
  }
315
- setLogLevel(level) {
316
- this.config.logLevel = level;
317
- }
318
- setEnabled(enabled) {
319
- this.config.enableLogging = enabled;
333
+ toJSON() {
334
+ return {
335
+ name: this.name,
336
+ code: this.code,
337
+ message: this.message,
338
+ provider: this.provider,
339
+ details: this.details,
340
+ };
320
341
  }
321
342
  }
343
+ function isAuthError(error) {
344
+ return (error instanceof AuthError ||
345
+ (typeof error === 'object' &&
346
+ error !== null &&
347
+ error.name === 'AuthError' &&
348
+ error.code !== undefined));
349
+ }
322
350
 
323
- class BaseAuthProvider {
324
- constructor(config) {
325
- this.currentUser = null;
326
- this.isInitialized = false;
327
- this.provider = config.provider;
328
- this.options = config.options;
329
- this.storage = config.storage;
330
- this.logger = config.logger;
331
- this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
332
- this.authStateEmitter = new EventEmitter();
333
- }
334
- async getCurrentUser() {
335
- if (!this.isInitialized) {
336
- await this.initialize();
351
+ class PlatformDetector {
352
+ static getPlatform() {
353
+ if (this.platformInfo) {
354
+ return this.platformInfo;
337
355
  }
338
- return this.currentUser;
356
+ const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
357
+ const platform = this.detectPlatform(userAgent);
358
+ this.platformInfo = {
359
+ platform,
360
+ isNative: platform === 'ios' || platform === 'android',
361
+ isWeb: platform === 'web',
362
+ isMobile: platform === 'ios' ||
363
+ platform === 'android' ||
364
+ this.isMobileWeb(userAgent),
365
+ isDesktop: platform === 'electron' ||
366
+ (platform === 'web' && !this.isMobileWeb(userAgent)),
367
+ userAgent,
368
+ };
369
+ return this.platformInfo;
370
+ }
371
+ static detectPlatform(userAgent) {
372
+ var _a, _b;
373
+ // Check if running in Capacitor
374
+ if (typeof window !== 'undefined' && window.Capacitor) {
375
+ const capacitor = window.Capacitor;
376
+ if (capacitor.getPlatform) {
377
+ const platform = capacitor.getPlatform();
378
+ if (platform === 'ios' || platform === 'android') {
379
+ return platform;
380
+ }
381
+ }
382
+ }
383
+ // Check if running in Electron
384
+ if (typeof window !== 'undefined' &&
385
+ ((_b = (_a = window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron)) {
386
+ return 'electron';
387
+ }
388
+ // Check for React Native
389
+ if (typeof navigator !== 'undefined' &&
390
+ navigator.product === 'ReactNative') {
391
+ if (/iPhone|iPad|iPod/i.test(userAgent)) {
392
+ return 'ios';
393
+ }
394
+ if (/Android/i.test(userAgent)) {
395
+ return 'android';
396
+ }
397
+ }
398
+ // Check for native iOS/Android webviews
399
+ if (/iPhone|iPad|iPod/i.test(userAgent) &&
400
+ /WebKit/i.test(userAgent) &&
401
+ !/Safari/i.test(userAgent)) {
402
+ return 'ios';
403
+ }
404
+ if (/Android/i.test(userAgent) && /wv/i.test(userAgent)) {
405
+ return 'android';
406
+ }
407
+ // Default to web
408
+ return 'web';
409
+ }
410
+ static isMobileWeb(userAgent) {
411
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
412
+ }
413
+ static isCapacitorAvailable() {
414
+ return typeof window !== 'undefined' && !!window.Capacitor;
415
+ }
416
+ static async checkCapacitorPlugin(pluginName) {
417
+ if (!this.isCapacitorAvailable()) {
418
+ return false;
419
+ }
420
+ try {
421
+ const { Capacitor } = window;
422
+ return !!(Capacitor.Plugins && Capacitor.Plugins[pluginName]);
423
+ }
424
+ catch (_a) {
425
+ return false;
426
+ }
427
+ }
428
+ }
429
+ PlatformDetector.platformInfo = null;
430
+
431
+ var _a;
432
+ class ProviderRegistry {
433
+ static registerManifest(manifest) {
434
+ this.manifests.set(manifest.name, manifest);
435
+ }
436
+ static registerLoader(name, loader) {
437
+ this.loaders.set(name, loader);
438
+ }
439
+ static getManifest(name) {
440
+ return this.manifests.get(name);
441
+ }
442
+ static async getProvider(name, config) {
443
+ var _b, _c;
444
+ // Check if already loaded
445
+ const existing = this.providers.get(name);
446
+ if (existing) {
447
+ return existing;
448
+ }
449
+ // Check if loader exists
450
+ const loader = this.loaders.get(name);
451
+ if (!loader) {
452
+ const manifest = this.manifests.get(name);
453
+ if (manifest) {
454
+ throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
455
+ }
456
+ throw new Error(`Unknown provider: ${name}`);
457
+ }
458
+ // Check platform support
459
+ const manifest = this.manifests.get(name);
460
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
461
+ const platform = PlatformDetector.getPlatform();
462
+ if (!manifest.platforms.includes(platform.platform)) {
463
+ throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
464
+ }
465
+ }
466
+ try {
467
+ // Load the provider
468
+ const module = await loader();
469
+ const ProviderClass = module.default;
470
+ // Create instance
471
+ const provider = new ProviderClass(config);
472
+ // Initialize if needed
473
+ if (provider.initialize) {
474
+ await provider.initialize(config);
475
+ }
476
+ // Cache the provider
477
+ this.providers.set(name, provider);
478
+ return provider;
479
+ }
480
+ catch (error) {
481
+ // Check if it's a missing dependency error
482
+ if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot find module')) ||
483
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Failed to resolve module'))) {
484
+ const manifest = this.manifests.get(name);
485
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
486
+ throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
487
+ `Install the required package:\n` +
488
+ `npm install ${manifest.packageName}\n\n` +
489
+ `Then try again.`);
490
+ }
491
+ }
492
+ throw error;
493
+ }
494
+ }
495
+ static clearProvider(name) {
496
+ const provider = this.providers.get(name);
497
+ if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
498
+ provider.dispose();
499
+ }
500
+ this.providers.delete(name);
501
+ }
502
+ static clearAll() {
503
+ for (const [, provider] of this.providers) {
504
+ if (provider.dispose) {
505
+ provider.dispose();
506
+ }
507
+ }
508
+ this.providers.clear();
509
+ }
510
+ static getAvailableProviders() {
511
+ return Array.from(this.manifests.keys());
512
+ }
513
+ static getSupportedProviders() {
514
+ const platform = PlatformDetector.getPlatform();
515
+ const supported = [];
516
+ for (const [name, manifest] of this.manifests) {
517
+ if (!manifest.platforms ||
518
+ manifest.platforms.includes(platform.platform)) {
519
+ supported.push(name);
520
+ }
521
+ }
522
+ return Promise.resolve(supported);
523
+ }
524
+ }
525
+ _a = ProviderRegistry;
526
+ ProviderRegistry.providers = new Map();
527
+ ProviderRegistry.loaders = new Map();
528
+ ProviderRegistry.manifests = new Map();
529
+ (() => {
530
+ // Register built-in provider manifests
531
+ _a.registerManifest({
532
+ name: 'google',
533
+ displayName: 'Google',
534
+ packageName: '@google/gsi',
535
+ setupInstructions: `
536
+ To use Google authentication, you need to:
537
+
538
+ 1. Install the Google Sign-In SDK:
539
+ npm install @google/gsi
540
+
541
+ 2. Configure your Google OAuth client:
542
+ - Go to https://console.cloud.google.com/
543
+ - Create or select a project
544
+ - Enable Google Sign-In API
545
+ - Create OAuth 2.0 credentials
546
+ - Add authorized JavaScript origins
547
+
548
+ 3. Configure the provider:
549
+ auth.configure({
550
+ providers: {
551
+ google: {
552
+ clientId: 'YOUR_CLIENT_ID'
553
+ }
554
+ }
555
+ })
556
+ `,
557
+ platforms: ['web', 'ios', 'android'],
558
+ configSchema: {
559
+ clientId: { type: 'string', required: true },
560
+ scopes: { type: 'array', items: 'string' },
561
+ hostedDomain: { type: 'string' },
562
+ },
563
+ });
564
+ _a.registerManifest({
565
+ name: 'apple',
566
+ displayName: 'Apple',
567
+ setupInstructions: `
568
+ To use Apple authentication:
569
+
570
+ 1. Configure Sign in with Apple:
571
+ - Go to https://developer.apple.com/
572
+ - Configure your app for Sign in with Apple
573
+ - Create a Services ID for web
574
+ - Configure return URLs
575
+
576
+ 2. Configure the provider:
577
+ auth.configure({
578
+ providers: {
579
+ apple: {
580
+ clientId: 'YOUR_SERVICE_ID',
581
+ redirectUri: 'YOUR_REDIRECT_URI'
582
+ }
583
+ }
584
+ })
585
+ `,
586
+ platforms: ['web', 'ios'],
587
+ configSchema: {
588
+ clientId: { type: 'string', required: true },
589
+ redirectUri: { type: 'string', required: true },
590
+ scopes: { type: 'array', items: 'string' },
591
+ },
592
+ });
593
+ _a.registerManifest({
594
+ name: 'firebase',
595
+ displayName: 'Firebase Auth',
596
+ packageName: 'firebase',
597
+ setupInstructions: `
598
+ To use Firebase authentication:
599
+
600
+ 1. Install Firebase SDK:
601
+ npm install firebase
602
+
603
+ 2. Configure Firebase:
604
+ - Go to https://console.firebase.google.com/
605
+ - Create or select a project
606
+ - Add your app (Web/iOS/Android)
607
+ - Copy the configuration
608
+
609
+ 3. Configure the provider:
610
+ auth.configure({
611
+ providers: {
612
+ firebase: {
613
+ apiKey: 'YOUR_API_KEY',
614
+ authDomain: 'YOUR_AUTH_DOMAIN',
615
+ projectId: 'YOUR_PROJECT_ID',
616
+ // ... other Firebase config
617
+ }
618
+ }
619
+ })
620
+ `,
621
+ platforms: ['web', 'ios', 'android'],
622
+ configSchema: {
623
+ apiKey: { type: 'string', required: true },
624
+ authDomain: { type: 'string', required: true },
625
+ projectId: { type: 'string', required: true },
626
+ },
627
+ });
628
+ _a.registerManifest({
629
+ name: 'microsoft',
630
+ displayName: 'Microsoft',
631
+ packageName: '@azure/msal-browser',
632
+ setupInstructions: `
633
+ To use Microsoft authentication:
634
+
635
+ 1. Install the Microsoft Authentication Library:
636
+ npm install @azure/msal-browser
637
+
638
+ 2. Configure your Azure AD app:
639
+ - Go to https://portal.azure.com/
640
+ - Create or select an app registration
641
+ - Add platform configuration for SPA
642
+ - Add redirect URIs
643
+
644
+ 3. Configure the provider:
645
+ auth.configure({
646
+ providers: {
647
+ microsoft: {
648
+ clientId: 'YOUR_CLIENT_ID',
649
+ authority: 'YOUR_AUTHORITY', // optional
650
+ redirectUri: 'YOUR_REDIRECT_URI' // optional
651
+ }
652
+ }
653
+ })
654
+ `,
655
+ platforms: ['web'],
656
+ configSchema: {
657
+ clientId: { type: 'string', required: true },
658
+ authority: { type: 'string' },
659
+ redirectUri: { type: 'string' },
660
+ scopes: { type: 'array', items: 'string' },
661
+ },
662
+ });
663
+ _a.registerManifest({
664
+ name: 'facebook',
665
+ displayName: 'Facebook',
666
+ setupInstructions: `
667
+ To use Facebook authentication:
668
+
669
+ 1. Configure your Facebook app:
670
+ - Go to https://developers.facebook.com/
671
+ - Create or select an app
672
+ - Add Facebook Login product
673
+ - Configure OAuth redirect URIs
674
+
675
+ 2. Add Facebook SDK to your HTML:
676
+ <script async defer crossorigin="anonymous"
677
+ src="https://connect.facebook.net/en_US/sdk.js"></script>
678
+
679
+ 3. Configure the provider:
680
+ auth.configure({
681
+ providers: {
682
+ facebook: {
683
+ appId: 'YOUR_APP_ID',
684
+ version: 'v18.0' // optional
685
+ }
686
+ }
687
+ })
688
+ `,
689
+ platforms: ['web'],
690
+ configSchema: {
691
+ appId: { type: 'string', required: true },
692
+ version: { type: 'string' },
693
+ scopes: { type: 'array', items: 'string' },
694
+ },
695
+ });
696
+ _a.registerManifest({
697
+ name: 'github',
698
+ displayName: 'GitHub',
699
+ setupInstructions: `
700
+ To use GitHub authentication:
701
+
702
+ 1. Configure your GitHub OAuth app:
703
+ - Go to https://github.com/settings/developers
704
+ - Create a new OAuth App
705
+ - Set authorization callback URL
706
+
707
+ 2. Configure the provider:
708
+ auth.configure({
709
+ providers: {
710
+ github: {
711
+ clientId: 'YOUR_CLIENT_ID',
712
+ redirectUri: 'YOUR_REDIRECT_URI'
713
+ }
714
+ }
715
+ })
716
+
717
+ Note: You'll need a backend service to exchange the authorization code for an access token.
718
+ `,
719
+ platforms: ['web'],
720
+ configSchema: {
721
+ clientId: { type: 'string', required: true },
722
+ redirectUri: { type: 'string' },
723
+ scopes: { type: 'array', items: 'string' },
724
+ },
725
+ });
726
+ // Register all new provider manifests
727
+ _a.registerManifest({
728
+ name: 'magic-link',
729
+ displayName: 'Email Magic Link',
730
+ setupInstructions: `
731
+ To use Email Magic Link authentication:
732
+
733
+ 1. Set up a backend endpoint to send emails:
734
+ - Endpoint should accept POST requests with email and magic link
735
+ - Send email with the magic link to the user
736
+
737
+ 2. Configure the provider:
738
+ auth.configure({
739
+ providers: {
740
+ 'magic-link': {
741
+ sendLinkUrl: 'https://your-api.com/send-magic-link',
742
+ verifyUrl: 'https://your-api.com/verify-magic-link', // Optional
743
+ redirectUrl: window.location.origin + '/auth-callback'
744
+ }
745
+ }
746
+ })
747
+ `,
748
+ platforms: ['web'],
749
+ configSchema: {
750
+ sendLinkUrl: { type: 'string', required: true },
751
+ verifyUrl: { type: 'string' },
752
+ redirectUrl: { type: 'string' },
753
+ },
754
+ });
755
+ _a.registerManifest({
756
+ name: 'sms',
757
+ displayName: 'SMS Authentication',
758
+ setupInstructions: `
759
+ To use SMS authentication:
760
+
761
+ 1. Set up backend endpoints:
762
+ - Send code endpoint: POST request to send SMS
763
+ - Verify code endpoint: POST request to verify SMS code
764
+
765
+ 2. Configure the provider:
766
+ auth.configure({
767
+ providers: {
768
+ sms: {
769
+ sendCodeUrl: 'https://your-api.com/sms/send',
770
+ verifyCodeUrl: 'https://your-api.com/sms/verify',
771
+ countryCode: '+1', // Default country code
772
+ codeLength: 6 // SMS code length
773
+ }
774
+ }
775
+ })
776
+ `,
777
+ platforms: ['web', 'ios', 'android'],
778
+ configSchema: {
779
+ sendCodeUrl: { type: 'string', required: true },
780
+ verifyCodeUrl: { type: 'string', required: true },
781
+ countryCode: { type: 'string' },
782
+ codeLength: { type: 'number' },
783
+ },
784
+ });
785
+ _a.registerManifest({
786
+ name: 'email-password',
787
+ displayName: 'Email & Password',
788
+ setupInstructions: `
789
+ To use Email/Password authentication:
790
+
791
+ 1. Set up backend API endpoints for authentication
792
+
793
+ 2. Configure the provider:
794
+ auth.configure({
795
+ providers: {
796
+ 'email-password': {
797
+ apiUrl: 'https://your-api.com',
798
+ passwordRequirements: {
799
+ minLength: 8,
800
+ requireUppercase: true,
801
+ requireNumbers: true
802
+ }
803
+ }
804
+ }
805
+ })
806
+ `,
807
+ platforms: ['web', 'ios', 'android'],
808
+ configSchema: {
809
+ apiUrl: { type: 'string', required: true },
810
+ passwordRequirements: { type: 'object' },
811
+ },
812
+ });
813
+ _a.registerManifest({
814
+ name: 'biometric',
815
+ displayName: 'Biometric Authentication',
816
+ packageName: 'capacitor-biometric-authentication',
817
+ setupInstructions: `
818
+ To use Biometric authentication:
819
+
820
+ 1. Install the capacitor-biometric-authentication plugin:
821
+ npm install capacitor-biometric-authentication
822
+ npx cap sync
823
+
824
+ 2. Configure the provider:
825
+ auth.configure({
826
+ providers: {
827
+ biometric: {
828
+ reason: 'Authenticate to access your account',
829
+ title: 'Authentication Required'
830
+ }
831
+ }
832
+ })
833
+
834
+ Note: Users must first authenticate with another method before enabling biometric authentication.
835
+ `,
836
+ platforms: ['ios', 'android'],
837
+ configSchema: {
838
+ reason: { type: 'string' },
839
+ title: { type: 'string' },
840
+ subtitle: { type: 'string' },
841
+ },
842
+ });
843
+ _a.registerManifest({
844
+ name: 'slack',
845
+ displayName: 'Slack',
846
+ setupInstructions: `
847
+ To use Slack authentication:
848
+
849
+ 1. Create a Slack App:
850
+ - Go to https://api.slack.com/apps
851
+ - Click "Create New App" > "From scratch"
852
+ - Name your app and select workspace
853
+
854
+ 2. Configure OAuth & Permissions:
855
+ - Add redirect URL: https://your-app.com/auth/slack/callback
856
+ - Add required scopes:
857
+ - openid
858
+ - profile
859
+ - email
860
+
861
+ 3. Get your credentials:
862
+ - Go to "Basic Information"
863
+ - Copy Client ID and Client Secret
864
+
865
+ 4. Configure the provider:
866
+ auth.configure({
867
+ providers: {
868
+ slack: {
869
+ clientId: 'YOUR_CLIENT_ID',
870
+ redirectUri: 'https://your-app.com/auth/slack/callback',
871
+ scopes: ['openid', 'profile', 'email'],
872
+ teamId: 'OPTIONAL_TEAM_ID' // Restrict to specific workspace
873
+ }
874
+ }
875
+ })
876
+
877
+ Note: Slack OAuth requires a backend service to exchange the authorization code for access tokens.
878
+ `,
879
+ platforms: ['web'],
880
+ configSchema: {
881
+ clientId: { type: 'string', required: true },
882
+ redirectUri: { type: 'string', required: true },
883
+ scopes: { type: 'array', items: 'string' },
884
+ teamId: { type: 'string' },
885
+ },
886
+ });
887
+ _a.registerManifest({
888
+ name: 'linkedin',
889
+ displayName: 'LinkedIn',
890
+ setupInstructions: `
891
+ To use LinkedIn authentication:
892
+
893
+ 1. Create a LinkedIn App:
894
+ - Go to https://www.linkedin.com/developers/apps
895
+ - Click "Create app"
896
+ - Fill in required information
897
+ - Verify your app
898
+
899
+ 2. Configure OAuth 2.0:
900
+ - Go to the "Auth" tab
901
+ - Add authorized redirect URLs:
902
+ - https://your-app.com/auth/linkedin/callback
903
+ - Note your Client ID and Client Secret
904
+
905
+ 3. Configure scopes:
906
+ - Under "OAuth 2.0 scopes", select:
907
+ - openid
908
+ - profile
909
+ - email
910
+
911
+ 4. Configure the provider:
912
+ auth.configure({
913
+ providers: {
914
+ linkedin: {
915
+ clientId: 'YOUR_CLIENT_ID',
916
+ redirectUri: 'https://your-app.com/auth/linkedin/callback',
917
+ scopes: ['openid', 'profile', 'email']
918
+ }
919
+ }
920
+ })
921
+
922
+ Note: LinkedIn OAuth requires a backend service to exchange the authorization code for access tokens.
923
+ The redirect URI must be HTTPS in production (LinkedIn requirement).
924
+ `,
925
+ platforms: ['web'],
926
+ configSchema: {
927
+ clientId: { type: 'string', required: true },
928
+ redirectUri: { type: 'string', required: true },
929
+ scopes: { type: 'array', items: 'string' },
930
+ },
931
+ });
932
+ _a.registerManifest({
933
+ name: 'username-password',
934
+ displayName: 'Username & Password',
935
+ setupInstructions: `
936
+ To use Username/Password authentication:
937
+
938
+ 1. Set up backend API endpoints:
939
+ - /auth/signin - Sign in with username/password
940
+ - /auth/signup - Create new account
941
+ - /auth/signout - Sign out user
942
+ - /auth/refresh - Refresh access token
943
+ - /auth/update-password - Update password
944
+ - /auth/check-username - Check username availability
945
+
946
+ 2. Configure the provider:
947
+ auth.configure({
948
+ providers: {
949
+ 'username-password': {
950
+ apiUrl: 'https://your-api.com',
951
+ usernameRequirements: {
952
+ minLength: 3,
953
+ maxLength: 20,
954
+ allowedCharacters: /^[a-zA-Z0-9_-]+$/,
955
+ reservedUsernames: ['admin', 'root', 'system']
956
+ },
957
+ passwordRequirements: {
958
+ minLength: 8,
959
+ requireUppercase: true,
960
+ requireLowercase: true,
961
+ requireNumbers: true,
962
+ requireSpecialChars: false
963
+ },
964
+ allowSignUp: true
965
+ }
966
+ }
967
+ })
968
+
969
+ 3. Sign in:
970
+ await auth.signIn('username-password', {
971
+ username: 'johndoe',
972
+ password: 'password123'
973
+ });
974
+
975
+ 4. Sign up:
976
+ await auth.signUp({
977
+ username: 'johndoe',
978
+ password: 'password123',
979
+ email: 'john@example.com', // optional
980
+ displayName: 'John Doe' // optional
981
+ });
982
+
983
+ Note: This provider requires a backend service to handle authentication.
984
+ `,
985
+ platforms: ['web', 'ios', 'android'],
986
+ configSchema: {
987
+ apiUrl: { type: 'string', required: true },
988
+ usernameRequirements: { type: 'object' },
989
+ passwordRequirements: { type: 'object' },
990
+ allowSignUp: { type: 'boolean' },
991
+ },
992
+ });
993
+ // Register provider loaders
994
+ _a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
995
+ default: m.GoogleAuthProviderWeb,
996
+ })));
997
+ _a.registerLoader('apple', () => Promise.resolve().then(function () { return appleProvider; }).then((m) => ({
998
+ default: m.AppleAuthProviderWeb,
999
+ })));
1000
+ _a.registerLoader('microsoft', () => Promise.resolve().then(function () { return microsoftProvider; }).then((m) => ({
1001
+ default: m.MicrosoftAuthProviderWeb,
1002
+ })));
1003
+ _a.registerLoader('facebook', () => Promise.resolve().then(function () { return facebookProvider; }).then((m) => ({
1004
+ default: m.FacebookAuthProviderWeb,
1005
+ })));
1006
+ _a.registerLoader('github', () => Promise.resolve().then(function () { return githubProvider; }).then((m) => ({
1007
+ default: m.GitHubAuthProviderWeb,
1008
+ })));
1009
+ _a.registerLoader('firebase', () => Promise.resolve().then(function () { return firebaseProvider; }).then((m) => ({
1010
+ default: m.FirebaseAuthProviderWeb,
1011
+ })));
1012
+ _a.registerLoader('magic-link', () => Promise.resolve().then(function () { return magicLinkProvider; }).then((m) => ({
1013
+ default: m.MagicLinkProvider,
1014
+ })));
1015
+ _a.registerLoader('sms', () => Promise.resolve().then(function () { return smsProvider; }).then((m) => ({
1016
+ default: m.SMSProvider,
1017
+ })));
1018
+ _a.registerLoader('email-password', () => Promise.resolve().then(function () { return emailPasswordProvider; }).then((m) => ({
1019
+ default: m.EmailPasswordProvider,
1020
+ })));
1021
+ _a.registerLoader('biometric', () => Promise.resolve().then(function () { return biometricProvider; }).then((m) => ({
1022
+ default: m.BiometricProvider,
1023
+ })));
1024
+ _a.registerLoader('slack', () => Promise.resolve().then(function () { return slackProvider; }).then((m) => ({
1025
+ default: m.SlackProvider,
1026
+ })));
1027
+ _a.registerLoader('linkedin', () => Promise.resolve().then(function () { return linkedinProvider; }).then((m) => ({
1028
+ default: m.LinkedInProvider,
1029
+ })));
1030
+ _a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
1031
+ default: m.UsernamePasswordProvider,
1032
+ })));
1033
+ })();
1034
+
1035
+ class AuthManagerCore {
1036
+ constructor() {
1037
+ this.state = {
1038
+ user: null,
1039
+ isLoading: false,
1040
+ isAuthenticated: false,
1041
+ provider: null,
1042
+ };
1043
+ this.stateEmitter = new EventEmitter();
1044
+ this.config = {};
1045
+ this.isInitialized = false;
1046
+ this.tokenRefreshTimers = new Map();
1047
+ this.storage = new WebStorage('local');
1048
+ this.logger = new Logger({
1049
+ enableLogging: false,
1050
+ logLevel: 'info',
1051
+ prefix: 'AuthManager',
1052
+ });
1053
+ // Auto-initialize on first use
1054
+ if (typeof window !== 'undefined') {
1055
+ this.initialize().catch((err) => {
1056
+ this.logger.error('Auto-initialization failed:', err);
1057
+ });
1058
+ }
1059
+ }
1060
+ async initialize(config) {
1061
+ if (this.isInitialized && !config) {
1062
+ return;
1063
+ }
1064
+ if (config) {
1065
+ this.config = Object.assign(Object.assign({}, this.config), config);
1066
+ }
1067
+ // Configure logger
1068
+ if (this.config.enableLogging !== undefined) {
1069
+ this.logger.setEnabled(this.config.enableLogging);
1070
+ }
1071
+ if (this.config.logLevel) {
1072
+ this.logger.setLogLevel(this.config.logLevel);
1073
+ }
1074
+ // Configure persistence
1075
+ if (this.config.persistence) {
1076
+ this.storage = new WebStorage(this.config.persistence);
1077
+ }
1078
+ // Restore auth state
1079
+ await this.restoreAuthState();
1080
+ this.isInitialized = true;
1081
+ this.logger.info('Auth manager initialized');
1082
+ }
1083
+ configure(config) {
1084
+ this.config = Object.assign(Object.assign({}, this.config), config);
1085
+ if (config.enableLogging !== undefined) {
1086
+ this.logger.setEnabled(config.enableLogging);
1087
+ }
1088
+ if (config.logLevel) {
1089
+ this.logger.setLogLevel(config.logLevel);
1090
+ }
1091
+ if (config.persistence) {
1092
+ this.storage = new WebStorage(config.persistence);
1093
+ }
1094
+ }
1095
+ async signIn(providerOrOptions) {
1096
+ var _a;
1097
+ await this.ensureInitialized();
1098
+ let providerName;
1099
+ let signInOptions = {};
1100
+ if (typeof providerOrOptions === 'string') {
1101
+ providerName = providerOrOptions;
1102
+ }
1103
+ else {
1104
+ // Convert AuthProvider enum to string if needed
1105
+ providerName =
1106
+ typeof providerOrOptions.provider === 'string'
1107
+ ? providerOrOptions.provider
1108
+ : exports.AuthProvider[providerOrOptions.provider];
1109
+ signInOptions = {
1110
+ credentials: providerOrOptions.credentials,
1111
+ options: providerOrOptions.options,
1112
+ };
1113
+ }
1114
+ this.updateState({ isLoading: true });
1115
+ try {
1116
+ // Get provider configuration
1117
+ const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[providerName];
1118
+ if (!providerConfig) {
1119
+ throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
1120
+ }
1121
+ // Get provider instance
1122
+ const provider = await ProviderRegistry.getProvider(providerName, providerConfig);
1123
+ // Sign in
1124
+ this.logger.info(`Signing in with ${providerName}`);
1125
+ const result = await provider.signIn(Object.assign(Object.assign({}, signInOptions.options), { credentials: signInOptions.credentials }));
1126
+ // Update state
1127
+ this.updateState({
1128
+ user: result.user,
1129
+ isAuthenticated: true,
1130
+ provider: providerName,
1131
+ isLoading: false,
1132
+ });
1133
+ // Store auth state
1134
+ await this.storage.set('auth_state', {
1135
+ user: result.user,
1136
+ provider: providerName,
1137
+ credential: result.credential,
1138
+ });
1139
+ // Setup token refresh
1140
+ if (this.config.autoRefreshToken && result.credential.refreshToken) {
1141
+ this.setupTokenRefresh(providerName, result.credential);
1142
+ }
1143
+ return result;
1144
+ }
1145
+ catch (error) {
1146
+ this.updateState({ isLoading: false });
1147
+ this.logger.error(`Sign in failed for ${providerName}`, error);
1148
+ throw AuthError.fromError(error);
1149
+ }
1150
+ }
1151
+ async signOut(options) {
1152
+ var _a;
1153
+ await this.ensureInitialized();
1154
+ const provider = (options === null || options === void 0 ? void 0 : options.provider) || this.state.provider;
1155
+ if (!provider) {
1156
+ this.logger.warn('No active auth session to sign out from');
1157
+ return;
1158
+ }
1159
+ this.updateState({ isLoading: true });
1160
+ try {
1161
+ // Get provider instance
1162
+ const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
1163
+ const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig);
1164
+ // Sign out
1165
+ await providerInstance.signOut(options);
1166
+ // Clear token refresh
1167
+ this.clearTokenRefresh(provider);
1168
+ // Clear state
1169
+ this.updateState({
1170
+ user: null,
1171
+ isAuthenticated: false,
1172
+ provider: null,
1173
+ isLoading: false,
1174
+ });
1175
+ // Clear storage
1176
+ await this.storage.remove('auth_state');
1177
+ this.logger.info(`Signed out from ${provider}`);
1178
+ }
1179
+ catch (error) {
1180
+ this.updateState({ isLoading: false });
1181
+ this.logger.error(`Sign out failed for ${provider}`, error);
1182
+ throw AuthError.fromError(error);
1183
+ }
1184
+ }
1185
+ getCurrentUser() {
1186
+ return this.state.user;
1187
+ }
1188
+ getAuthState() {
1189
+ return Object.assign({}, this.state);
1190
+ }
1191
+ isAuthenticated() {
1192
+ return this.state.isAuthenticated;
1193
+ }
1194
+ getCurrentProvider() {
1195
+ return this.state.provider;
1196
+ }
1197
+ async refreshToken(provider) {
1198
+ var _a;
1199
+ await this.ensureInitialized();
1200
+ const targetProvider = provider || this.state.provider;
1201
+ if (!targetProvider) {
1202
+ throw new AuthError('auth/no-auth-session', 'No active auth session to refresh');
1203
+ }
1204
+ try {
1205
+ const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
1206
+ const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig);
1207
+ if (!providerInstance.refreshToken) {
1208
+ throw new AuthError('auth/operation-not-supported', `Provider '${targetProvider}' does not support token refresh`);
1209
+ }
1210
+ const result = await providerInstance.refreshToken();
1211
+ // Update user
1212
+ this.updateState({ user: result.user });
1213
+ // Setup new token refresh
1214
+ if (this.config.autoRefreshToken && result.credential.refreshToken) {
1215
+ this.setupTokenRefresh(targetProvider, result.credential);
1216
+ }
1217
+ return result;
1218
+ }
1219
+ catch (error) {
1220
+ this.logger.error(`Token refresh failed for ${targetProvider}`, error);
1221
+ throw AuthError.fromError(error);
1222
+ }
1223
+ }
1224
+ onAuthStateChange(listener) {
1225
+ // Immediately call with current state
1226
+ listener(this.getAuthState());
1227
+ // Subscribe to future changes
1228
+ return this.stateEmitter.subscribe(listener);
1229
+ }
1230
+ async getAvailableProviders() {
1231
+ return ProviderRegistry.getAvailableProviders();
1232
+ }
1233
+ async getSupportedProviders() {
1234
+ return ProviderRegistry.getSupportedProviders();
1235
+ }
1236
+ async isProviderSupported(provider) {
1237
+ const supported = await this.getSupportedProviders();
1238
+ return supported.includes(provider);
1239
+ }
1240
+ async ensureInitialized() {
1241
+ if (!this.isInitialized) {
1242
+ await this.initialize();
1243
+ }
1244
+ }
1245
+ updateState(partial) {
1246
+ this.state = Object.assign(Object.assign({}, this.state), partial);
1247
+ this.stateEmitter.emit(this.state);
1248
+ }
1249
+ async restoreAuthState() {
1250
+ var _a, _b;
1251
+ try {
1252
+ const stored = await this.storage.get('auth_state');
1253
+ if ((stored === null || stored === void 0 ? void 0 : stored.user) && (stored === null || stored === void 0 ? void 0 : stored.provider)) {
1254
+ // Verify the session is still valid
1255
+ const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
1256
+ if (providerConfig) {
1257
+ try {
1258
+ const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig);
1259
+ const currentUser = await provider.getCurrentUser();
1260
+ if (currentUser) {
1261
+ this.updateState({
1262
+ user: currentUser,
1263
+ isAuthenticated: true,
1264
+ provider: stored.provider,
1265
+ });
1266
+ // Setup token refresh if needed
1267
+ if (((_b = stored.credential) === null || _b === void 0 ? void 0 : _b.refreshToken) &&
1268
+ this.config.autoRefreshToken) {
1269
+ this.setupTokenRefresh(stored.provider, stored.credential);
1270
+ }
1271
+ }
1272
+ }
1273
+ catch (error) {
1274
+ this.logger.warn('Failed to restore auth session:', error);
1275
+ await this.storage.remove('auth_state');
1276
+ }
1277
+ }
1278
+ }
1279
+ }
1280
+ catch (error) {
1281
+ this.logger.error('Failed to restore auth state:', error);
1282
+ }
1283
+ }
1284
+ setupTokenRefresh(provider, credential) {
1285
+ this.clearTokenRefresh(provider);
1286
+ if (!credential.expiresAt || !credential.refreshToken) {
1287
+ return;
1288
+ }
1289
+ const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
1290
+ const refreshTime = credential.expiresAt - buffer - Date.now();
1291
+ if (refreshTime > 0) {
1292
+ const timer = setTimeout(async () => {
1293
+ try {
1294
+ await this.refreshToken(provider);
1295
+ }
1296
+ catch (error) {
1297
+ this.logger.error(`Auto token refresh failed for ${provider}`, error);
1298
+ }
1299
+ }, refreshTime);
1300
+ this.tokenRefreshTimers.set(provider, timer);
1301
+ }
1302
+ }
1303
+ clearTokenRefresh(provider) {
1304
+ const timer = this.tokenRefreshTimers.get(provider);
1305
+ if (timer) {
1306
+ clearTimeout(timer);
1307
+ this.tokenRefreshTimers.delete(provider);
1308
+ }
1309
+ }
1310
+ dispose() {
1311
+ // Clear all timers
1312
+ for (const timer of this.tokenRefreshTimers.values()) {
1313
+ clearTimeout(timer);
1314
+ }
1315
+ this.tokenRefreshTimers.clear();
1316
+ // Clear providers
1317
+ ProviderRegistry.clearAll();
1318
+ // Clear listeners
1319
+ this.stateEmitter.clear();
1320
+ }
1321
+ }
1322
+ // Create singleton instance
1323
+ const auth = new AuthManagerCore();
1324
+
1325
+ // This provides backward compatibility for users who still want to use the Capacitor plugin interface
1326
+ const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
1327
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
1328
+ });
1329
+
1330
+ class BaseAuthProvider {
1331
+ get name() {
1332
+ return this.provider;
1333
+ }
1334
+ constructor(config) {
1335
+ this.currentUser = null;
1336
+ this.isInitialized = false;
1337
+ this.provider = config.provider;
1338
+ this.options = config.options;
1339
+ this.storage = config.storage;
1340
+ this.logger = config.logger;
1341
+ this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
1342
+ this.authStateEmitter = new EventEmitter();
1343
+ }
1344
+ async getCurrentUser() {
1345
+ if (!this.isInitialized) {
1346
+ await this.initialize();
1347
+ }
1348
+ return this.currentUser;
339
1349
  }
340
1350
  addAuthStateListener(callback) {
341
1351
  return this.authStateEmitter.subscribe(callback);
@@ -345,7 +1355,7 @@ class BaseAuthProvider {
345
1355
  // Persist user to storage
346
1356
  const storageKey = `${this.provider}_current_user`;
347
1357
  if (user) {
348
- await this.storage.set(storageKey, JSON.stringify(user));
1358
+ await this.storage.set(storageKey, user);
349
1359
  }
350
1360
  else {
351
1361
  await this.storage.remove(storageKey);
@@ -358,7 +1368,7 @@ class BaseAuthProvider {
358
1368
  const storageKey = `${this.provider}_current_user`;
359
1369
  const userData = await this.storage.get(storageKey);
360
1370
  if (userData) {
361
- this.currentUser = JSON.parse(userData);
1371
+ this.currentUser = userData;
362
1372
  this.logger.debug(`Loaded user from storage for provider ${this.provider}`);
363
1373
  }
364
1374
  }
@@ -368,14 +1378,14 @@ class BaseAuthProvider {
368
1378
  }
369
1379
  async saveCredential(credential) {
370
1380
  const storageKey = `${this.provider}_credential`;
371
- await this.storage.set(storageKey, JSON.stringify(credential));
1381
+ await this.storage.set(storageKey, credential);
372
1382
  }
373
1383
  async loadCredential() {
374
1384
  try {
375
1385
  const storageKey = `${this.provider}_credential`;
376
1386
  const credentialData = await this.storage.get(storageKey);
377
1387
  if (credentialData) {
378
- return JSON.parse(credentialData);
1388
+ return credentialData;
379
1389
  }
380
1390
  }
381
1391
  catch (error) {
@@ -420,7 +1430,7 @@ class BaseAuthProvider {
420
1430
  // Default to 1 hour
421
1431
  expiresIn = 3600;
422
1432
  }
423
- return Date.now() + (expiresIn * 1000);
1433
+ return Date.now() + expiresIn * 1000;
424
1434
  }
425
1435
  dispose() {
426
1436
  this.authStateEmitter.clear();
@@ -446,6 +1456,9 @@ class OAuthProvider extends BaseAuthProvider {
446
1456
  // Validate response
447
1457
  await this.validateOAuthResponse(authResponse, state, nonce);
448
1458
  // Exchange authorization code for tokens
1459
+ if (!authResponse.code) {
1460
+ throw new AuthError(exports.AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
1461
+ }
449
1462
  const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
450
1463
  // Parse user information
451
1464
  const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
@@ -455,7 +1468,7 @@ class OAuthProvider extends BaseAuthProvider {
455
1468
  // Save user and credential
456
1469
  await this.setCurrentUser(user);
457
1470
  await this.saveCredential(credential);
458
- return this.createAuthResult(user, credential, userInfo.isNewUser);
1471
+ return this.createAuthResult(user, credential, userInfo.isNewUser || false);
459
1472
  }
460
1473
  catch (error) {
461
1474
  this.logger.error(`OAuth flow failed for ${this.provider}`, error);
@@ -519,9 +1532,10 @@ class OAuthProvider extends BaseAuthProvider {
519
1532
  },
520
1533
  body: params.toString(),
521
1534
  });
522
- const data = await response.json();
1535
+ const data = (await response.json());
523
1536
  if (!response.ok) {
524
- throw new AuthError(this.mapOAuthError(data.error), data.error_description || 'Token exchange failed', this.provider, data);
1537
+ const errorData = data;
1538
+ throw new AuthError(this.mapOAuthError(errorData.error), errorData.error_description || 'Token exchange failed', this.provider, errorData);
525
1539
  }
526
1540
  return data;
527
1541
  }
@@ -555,9 +1569,10 @@ class OAuthProvider extends BaseAuthProvider {
555
1569
  },
556
1570
  body: params.toString(),
557
1571
  });
558
- const data = await response.json();
1572
+ const data = (await response.json());
559
1573
  if (!response.ok) {
560
- throw new AuthError(this.mapOAuthError(data.error), data.error_description || 'Token refresh failed', this.provider, data);
1574
+ const errorData = data;
1575
+ throw new AuthError(this.mapOAuthError(errorData.error), errorData.error_description || 'Token refresh failed', this.provider, errorData);
561
1576
  }
562
1577
  // Update credential with new tokens
563
1578
  const newCredential = this.createOAuthCredential(data);
@@ -630,21 +1645,23 @@ class OAuthProvider extends BaseAuthProvider {
630
1645
  createAuthUser(userInfo, tokenResponse) {
631
1646
  return {
632
1647
  uid: userInfo.id || userInfo.sub || this.generateUniqueId(),
633
- email: userInfo.email,
1648
+ email: userInfo.email || null,
634
1649
  emailVerified: userInfo.email_verified || false,
635
- displayName: userInfo.name || userInfo.displayName,
636
- photoURL: userInfo.picture || userInfo.photoURL,
637
- phoneNumber: userInfo.phone_number,
1650
+ displayName: userInfo.name || userInfo.displayName || null,
1651
+ photoURL: userInfo.picture || userInfo.photoURL || null,
1652
+ phoneNumber: userInfo.phone_number || null,
638
1653
  isAnonymous: false,
639
1654
  tenantId: null,
640
- providerData: [{
1655
+ providerData: [
1656
+ {
641
1657
  providerId: this.provider,
642
- uid: userInfo.id || userInfo.sub,
643
- displayName: userInfo.name,
644
- email: userInfo.email,
645
- phoneNumber: userInfo.phone_number,
646
- photoURL: userInfo.picture,
647
- }],
1658
+ uid: userInfo.id || userInfo.sub || '',
1659
+ displayName: userInfo.name || null,
1660
+ email: userInfo.email || null,
1661
+ phoneNumber: userInfo.phone_number || null,
1662
+ photoURL: userInfo.picture || null,
1663
+ },
1664
+ ],
648
1665
  metadata: {
649
1666
  creationTime: new Date().toISOString(),
650
1667
  lastSignInTime: new Date().toISOString(),
@@ -654,18 +1671,18 @@ class OAuthProvider extends BaseAuthProvider {
654
1671
  }
655
1672
  mapOAuthError(error) {
656
1673
  const errorMap = {
657
- 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
658
- 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
659
- 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
660
- 'unsupported_response_type': exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
661
- 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
662
- 'server_error': exports.AuthErrorCode.SERVER_ERROR,
663
- 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
664
- 'invalid_grant': exports.AuthErrorCode.INVALID_GRANT,
665
- 'invalid_client': exports.AuthErrorCode.CLIENT_NOT_FOUND,
666
- 'interaction_required': exports.AuthErrorCode.INTERACTION_REQUIRED,
667
- 'login_required': exports.AuthErrorCode.LOGIN_REQUIRED,
668
- 'consent_required': exports.AuthErrorCode.CONSENT_REQUIRED,
1674
+ invalid_request: exports.AuthErrorCode.INVALID_REQUEST,
1675
+ unauthorized_client: exports.AuthErrorCode.APP_NOT_AUTHORIZED,
1676
+ access_denied: exports.AuthErrorCode.ACCESS_DENIED,
1677
+ unsupported_response_type: exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
1678
+ invalid_scope: exports.AuthErrorCode.INVALID_SCOPE,
1679
+ server_error: exports.AuthErrorCode.SERVER_ERROR,
1680
+ temporarily_unavailable: exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
1681
+ invalid_grant: exports.AuthErrorCode.INVALID_GRANT,
1682
+ invalid_client: exports.AuthErrorCode.CLIENT_NOT_FOUND,
1683
+ interaction_required: exports.AuthErrorCode.INTERACTION_REQUIRED,
1684
+ login_required: exports.AuthErrorCode.LOGIN_REQUIRED,
1685
+ consent_required: exports.AuthErrorCode.CONSENT_REQUIRED,
669
1686
  };
670
1687
  return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
671
1688
  }
@@ -720,11 +1737,15 @@ class GoogleAuthProviderWeb extends OAuthProvider {
720
1737
  }
721
1738
  }
722
1739
  async _initialize() {
1740
+ var _a, _b;
723
1741
  const options = this.options;
724
1742
  try {
725
1743
  // Load Google Identity Services library
726
1744
  await this.loadGoogleIdentityServices();
727
1745
  // Initialize Google client
1746
+ if (!((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2)) {
1747
+ throw new Error('Google Identity Services not loaded');
1748
+ }
728
1749
  window.google.accounts.oauth2.initCodeClient({
729
1750
  client_id: options.clientId,
730
1751
  scope: (options.scopes || ['openid', 'email', 'profile']).join(' '),
@@ -746,13 +1767,14 @@ class GoogleAuthProviderWeb extends OAuthProvider {
746
1767
  async signIn(options) {
747
1768
  this.validateInitialized();
748
1769
  return new Promise((resolve, reject) => {
749
- var _a, _b, _c;
1770
+ var _a, _b, _c, _d, _e;
750
1771
  try {
751
1772
  const googleOptions = this.options;
752
1773
  // Configure sign-in options
753
1774
  const signInConfig = {
754
1775
  client_id: googleOptions.clientId,
755
- scope: (((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) || googleOptions.scopes || ['openid', 'email', 'profile']).join(' '),
1776
+ scope: (((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) ||
1777
+ googleOptions.scopes || ['openid', 'email', 'profile']).join(' '),
756
1778
  callback: async (response) => {
757
1779
  if (response.error) {
758
1780
  reject(new AuthError(this.mapGoogleError(response.error), response.error_description || response.error, this.provider));
@@ -760,6 +1782,9 @@ class GoogleAuthProviderWeb extends OAuthProvider {
760
1782
  }
761
1783
  try {
762
1784
  // Exchange authorization code for tokens
1785
+ if (!response.code) {
1786
+ throw new AuthError(exports.AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
1787
+ }
763
1788
  const tokenResponse = await this.exchangeCodeForTokens(response.code, this.getOAuthConfig());
764
1789
  // Get user info
765
1790
  const userInfo = await this.getUserInfo(tokenResponse.access_token);
@@ -778,13 +1803,17 @@ class GoogleAuthProviderWeb extends OAuthProvider {
778
1803
  };
779
1804
  // Add login hint if provided
780
1805
  if (((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.loginHint) || googleOptions.loginHint) {
781
- signInConfig.login_hint = ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) || googleOptions.loginHint;
1806
+ signInConfig.login_hint =
1807
+ ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) || googleOptions.loginHint;
782
1808
  }
783
1809
  // Add hosted domain if provided
784
1810
  if (googleOptions.hostedDomain) {
785
1811
  signInConfig.hd = googleOptions.hostedDomain;
786
1812
  }
787
1813
  // Create new client with callback
1814
+ if (!((_e = (_d = window.google) === null || _d === void 0 ? void 0 : _d.accounts) === null || _e === void 0 ? void 0 : _e.oauth2)) {
1815
+ throw new Error('Google Identity Services not loaded');
1816
+ }
788
1817
  const client = window.google.accounts.oauth2.initCodeClient(signInConfig);
789
1818
  // Request authorization code
790
1819
  client.requestCode();
@@ -862,7 +1891,7 @@ class GoogleAuthProviderWeb extends OAuthProvider {
862
1891
  if (!response.ok) {
863
1892
  throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to fetch user info', this.provider);
864
1893
  }
865
- return await response.json();
1894
+ return (await response.json());
866
1895
  }
867
1896
  catch (error) {
868
1897
  if (error instanceof AuthError) {
@@ -898,35 +1927,37 @@ class GoogleAuthProviderWeb extends OAuthProvider {
898
1927
  }
899
1928
  mapGoogleError(error) {
900
1929
  const errorMap = {
901
- 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
902
- 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
903
- 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
904
- 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
905
- 'server_error': exports.AuthErrorCode.SERVER_ERROR,
906
- 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
907
- 'popup_closed_by_user': exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
908
- 'popup_blocked': exports.AuthErrorCode.POPUP_BLOCKED,
1930
+ access_denied: exports.AuthErrorCode.ACCESS_DENIED,
1931
+ unauthorized_client: exports.AuthErrorCode.APP_NOT_AUTHORIZED,
1932
+ invalid_request: exports.AuthErrorCode.INVALID_REQUEST,
1933
+ invalid_scope: exports.AuthErrorCode.INVALID_SCOPE,
1934
+ server_error: exports.AuthErrorCode.SERVER_ERROR,
1935
+ temporarily_unavailable: exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
1936
+ popup_closed_by_user: exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
1937
+ popup_blocked: exports.AuthErrorCode.POPUP_BLOCKED,
909
1938
  };
910
1939
  return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
911
1940
  }
912
1941
  createAuthUser(userInfo, tokenResponse) {
913
1942
  return {
914
- uid: userInfo.sub,
915
- email: userInfo.email,
1943
+ uid: userInfo.sub || '',
1944
+ email: userInfo.email || null,
916
1945
  emailVerified: userInfo.email_verified || false,
917
- displayName: userInfo.name,
918
- photoURL: userInfo.picture,
1946
+ displayName: userInfo.name || null,
1947
+ photoURL: userInfo.picture || null,
919
1948
  phoneNumber: null,
920
1949
  isAnonymous: false,
921
1950
  tenantId: null,
922
- providerData: [{
1951
+ providerData: [
1952
+ {
923
1953
  providerId: exports.AuthProvider.GOOGLE,
924
- uid: userInfo.sub,
925
- displayName: userInfo.name,
926
- email: userInfo.email,
1954
+ uid: userInfo.sub || '',
1955
+ displayName: userInfo.name || null,
1956
+ email: userInfo.email || null,
927
1957
  phoneNumber: null,
928
- photoURL: userInfo.picture,
929
- }],
1958
+ photoURL: userInfo.picture || null,
1959
+ },
1960
+ ],
930
1961
  metadata: {
931
1962
  creationTime: new Date().toISOString(),
932
1963
  lastSignInTime: new Date().toISOString(),
@@ -936,6 +1967,11 @@ class GoogleAuthProviderWeb extends OAuthProvider {
936
1967
  }
937
1968
  }
938
1969
 
1970
+ var googleProvider = /*#__PURE__*/Object.freeze({
1971
+ __proto__: null,
1972
+ GoogleAuthProviderWeb: GoogleAuthProviderWeb
1973
+ });
1974
+
939
1975
  class AppleAuthProviderWeb extends OAuthProvider {
940
1976
  constructor(config) {
941
1977
  super(config);
@@ -959,250 +1995,2971 @@ class AppleAuthProviderWeb extends OAuthProvider {
959
1995
  if (this.isInitialized) {
960
1996
  return;
961
1997
  }
962
- if (this.initPromise) {
963
- return this.initPromise;
1998
+ if (this.initPromise) {
1999
+ return this.initPromise;
2000
+ }
2001
+ this.initPromise = this._initialize();
2002
+ try {
2003
+ await this.initPromise;
2004
+ }
2005
+ finally {
2006
+ this.initPromise = null;
2007
+ }
2008
+ }
2009
+ async _initialize() {
2010
+ const options = this.options;
2011
+ try {
2012
+ // Load Apple JS SDK
2013
+ await this.loadAppleSDK();
2014
+ // Initialize Apple ID auth
2015
+ window.AppleID.auth.init({
2016
+ clientId: options.clientId,
2017
+ scope: this.mapAppleScopes(options.scopes).join(' '),
2018
+ redirectURI: options.redirectUri,
2019
+ state: options.state || this.generateSecureRandomString(),
2020
+ nonce: options.nonce,
2021
+ usePopup: options.usePopup !== false, // Default to true
2022
+ });
2023
+ // Load previously authenticated user
2024
+ await this.loadCurrentUser();
2025
+ this.isInitialized = true;
2026
+ this.logger.info('Apple Auth provider initialized');
2027
+ }
2028
+ catch (error) {
2029
+ this.logger.error('Failed to initialize Apple Auth', error);
2030
+ throw AuthError.fromError(error, this.provider);
2031
+ }
2032
+ }
2033
+ async signIn(options) {
2034
+ var _a, _b, _c;
2035
+ this.validateInitialized();
2036
+ try {
2037
+ const appleOptions = this.options;
2038
+ // Generate state and nonce for security
2039
+ const state = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.state) || this.generateSecureRandomString();
2040
+ const nonce = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.nonce) || this.generateSecureRandomString();
2041
+ // Store state and nonce for validation
2042
+ await this.storage.set(`${this.provider}_oauth_state`, state);
2043
+ await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
2044
+ // Configure sign-in options
2045
+ const signInConfig = {
2046
+ clientId: appleOptions.clientId,
2047
+ scope: this.mapAppleScopes(((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.scopes) || appleOptions.scopes).join(' '),
2048
+ redirectURI: appleOptions.redirectUri,
2049
+ state,
2050
+ nonce,
2051
+ usePopup: appleOptions.usePopup !== false,
2052
+ };
2053
+ // Perform sign in
2054
+ const response = await window.AppleID.auth.signIn(signInConfig);
2055
+ // Validate response
2056
+ await this.validateAppleResponse(response, state, nonce);
2057
+ // Parse user information from response
2058
+ const user = this.createAppleAuthUser(response);
2059
+ const credential = this.createAppleCredential(response);
2060
+ // Save user and credential
2061
+ await this.setCurrentUser(user);
2062
+ await this.saveCredential(credential);
2063
+ return this.createAuthResult(user, credential, response.user ? true : false);
2064
+ }
2065
+ catch (error) {
2066
+ this.logger.error('Apple sign in failed', error);
2067
+ if (error && typeof error === 'object' && 'error' in error) {
2068
+ throw new AuthError(this.mapAppleError(error.error), error.error, this.provider);
2069
+ }
2070
+ throw AuthError.fromError(error, this.provider);
2071
+ }
2072
+ finally {
2073
+ // Clean up temporary storage
2074
+ await this.storage.remove(`${this.provider}_oauth_state`);
2075
+ await this.storage.remove(`${this.provider}_oauth_nonce`);
2076
+ }
2077
+ }
2078
+ async signOut(_options) {
2079
+ this.validateInitialized();
2080
+ try {
2081
+ // Apple doesn't provide a sign-out method in their JS SDK
2082
+ // Just clear local data
2083
+ await this.clearStoredData();
2084
+ await this.setCurrentUser(null);
2085
+ this.logger.info('Signed out from Apple');
2086
+ }
2087
+ catch (error) {
2088
+ this.logger.error('Failed to sign out from Apple', error);
2089
+ throw AuthError.fromError(error, this.provider);
2090
+ }
2091
+ }
2092
+ async isSupported() {
2093
+ // Check if we're in a browser environment
2094
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
2095
+ return false;
2096
+ }
2097
+ // Check if we're on HTTPS (required for Apple Sign In)
2098
+ if (window.location.protocol !== 'https:' &&
2099
+ window.location.hostname !== 'localhost') {
2100
+ return false;
2101
+ }
2102
+ return true;
2103
+ }
2104
+ async linkAccount(options) {
2105
+ // For web, linking is the same as signing in
2106
+ return this.signIn(options);
2107
+ }
2108
+ async unlinkAccount(_options) {
2109
+ // For web, unlinking is the same as signing out
2110
+ await this.signOut();
2111
+ }
2112
+ async openAuthorizationUrl(_url) {
2113
+ // This method is not used in Apple JS SDK flow
2114
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Direct OAuth flow not supported for Apple. Use signIn method instead.', this.provider);
2115
+ }
2116
+ async parseUserFromTokenResponse(_response) {
2117
+ // Apple provides user info directly in the authorization response
2118
+ // Note: This is a simplified implementation since Apple doesn't provide user info in the token response
2119
+ return {};
2120
+ }
2121
+ async loadAppleSDK() {
2122
+ var _a;
2123
+ if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
2124
+ return;
2125
+ }
2126
+ return new Promise((resolve, reject) => {
2127
+ const script = document.createElement('script');
2128
+ script.src =
2129
+ 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
2130
+ script.async = true;
2131
+ script.defer = true;
2132
+ script.onload = () => {
2133
+ var _a;
2134
+ if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
2135
+ resolve();
2136
+ }
2137
+ else {
2138
+ reject(new Error('Apple ID SDK failed to load'));
2139
+ }
2140
+ };
2141
+ script.onerror = () => {
2142
+ reject(new Error('Failed to load Apple ID SDK'));
2143
+ };
2144
+ document.head.appendChild(script);
2145
+ });
2146
+ }
2147
+ mapAppleScopes(scopes) {
2148
+ if (!scopes || scopes.length === 0) {
2149
+ return [];
2150
+ }
2151
+ return scopes.map((scope) => {
2152
+ switch (scope) {
2153
+ case exports.AppleAuthScope.EMAIL:
2154
+ return 'email';
2155
+ case exports.AppleAuthScope.NAME:
2156
+ return 'name';
2157
+ default:
2158
+ return scope;
2159
+ }
2160
+ });
2161
+ }
2162
+ async validateAppleResponse(response, expectedState, _expectedNonce) {
2163
+ if (response.error) {
2164
+ throw new AuthError(this.mapAppleError(response.error), response.error, this.provider);
2165
+ }
2166
+ if (response.authorization.state !== expectedState) {
2167
+ throw new AuthError(exports.AuthErrorCode.INVALID_STATE, 'OAuth state mismatch', this.provider);
2168
+ }
2169
+ // ID token validation with nonce would be done here
2170
+ // For production, you should validate the ID token on your backend
2171
+ }
2172
+ createAppleAuthUser(response) {
2173
+ var _a, _b, _c;
2174
+ const user = response.user || {};
2175
+ const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
2176
+ // Parse ID token claims (in production, do this on backend)
2177
+ let claims = {};
2178
+ if (idToken) {
2179
+ try {
2180
+ const payload = idToken.split('.')[1];
2181
+ claims = JSON.parse(atob(payload));
2182
+ }
2183
+ catch (error) {
2184
+ this.logger.error('Failed to parse ID token', error);
2185
+ }
2186
+ }
2187
+ return {
2188
+ uid: claims.sub || ((_b = response.authorization) === null || _b === void 0 ? void 0 : _b.code) || this.generateUniqueId(),
2189
+ email: user.email || claims.email || null,
2190
+ emailVerified: claims.email_verified || false,
2191
+ displayName: user.name
2192
+ ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim()
2193
+ : null,
2194
+ photoURL: null, // Apple doesn't provide profile photos
2195
+ phoneNumber: null,
2196
+ isAnonymous: false,
2197
+ tenantId: null,
2198
+ providerData: [
2199
+ {
2200
+ providerId: exports.AuthProvider.APPLE,
2201
+ uid: claims.sub || ((_c = response.authorization) === null || _c === void 0 ? void 0 : _c.code) || '',
2202
+ displayName: user.name
2203
+ ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim()
2204
+ : null,
2205
+ email: user.email || claims.email || null,
2206
+ phoneNumber: null,
2207
+ photoURL: null,
2208
+ },
2209
+ ],
2210
+ metadata: {
2211
+ creationTime: new Date().toISOString(),
2212
+ lastSignInTime: new Date().toISOString(),
2213
+ },
2214
+ refreshToken: undefined, // Apple doesn't provide refresh tokens through JS SDK
2215
+ };
2216
+ }
2217
+ createAppleCredential(response) {
2218
+ var _a, _b;
2219
+ return {
2220
+ providerId: exports.AuthProvider.APPLE,
2221
+ signInMethod: 'oauth',
2222
+ accessToken: undefined, // Apple doesn't provide access tokens through JS SDK
2223
+ idToken: (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token,
2224
+ refreshToken: undefined, // Apple doesn't provide refresh tokens through JS SDK
2225
+ expiresAt: undefined,
2226
+ tokenType: 'Bearer',
2227
+ scope: undefined, // Apple doesn't provide scope info in JS SDK response
2228
+ rawNonce: (_b = response.authorization) === null || _b === void 0 ? void 0 : _b.state,
2229
+ };
2230
+ }
2231
+ mapAppleError(error) {
2232
+ const errorMap = {
2233
+ user_cancelled_authorize: exports.AuthErrorCode.USER_CANCELLED,
2234
+ popup_closed_by_user: exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
2235
+ popup_blocked: exports.AuthErrorCode.POPUP_BLOCKED,
2236
+ invalid_request: exports.AuthErrorCode.INVALID_REQUEST,
2237
+ invalid_client: exports.AuthErrorCode.CLIENT_NOT_FOUND,
2238
+ invalid_scope: exports.AuthErrorCode.INVALID_SCOPE,
2239
+ unauthorized_client: exports.AuthErrorCode.APP_NOT_AUTHORIZED,
2240
+ access_denied: exports.AuthErrorCode.ACCESS_DENIED,
2241
+ unsupported_response_type: exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
2242
+ server_error: exports.AuthErrorCode.SERVER_ERROR,
2243
+ temporarily_unavailable: exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
2244
+ };
2245
+ return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
2246
+ }
2247
+ }
2248
+
2249
+ var appleProvider = /*#__PURE__*/Object.freeze({
2250
+ __proto__: null,
2251
+ AppleAuthProviderWeb: AppleAuthProviderWeb
2252
+ });
2253
+
2254
+ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
2255
+ constructor() {
2256
+ super(...arguments);
2257
+ this.clientId = '';
2258
+ this.authority = '';
2259
+ this.redirectUri = '';
2260
+ this.scopes = [];
2261
+ }
2262
+ async initialize() {
2263
+ const options = this.options;
2264
+ if (!options.clientId) {
2265
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'Microsoft client ID is required', this.provider);
2266
+ }
2267
+ this.clientId = options.clientId;
2268
+ this.authority =
2269
+ options.authority || 'https://login.microsoftonline.com/common';
2270
+ this.redirectUri = options.redirectUri || window.location.origin;
2271
+ this.scopes = options.scopes || ['openid', 'profile', 'email'];
2272
+ // Check if MSAL is available
2273
+ const msal = window.msal;
2274
+ if (!msal) {
2275
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Microsoft Authentication Library (MSAL) is not loaded. Please include the MSAL script in your HTML.', this.provider);
2276
+ }
2277
+ // Configure MSAL
2278
+ this.msalConfig = {
2279
+ auth: {
2280
+ clientId: this.clientId,
2281
+ authority: this.authority,
2282
+ redirectUri: this.redirectUri,
2283
+ navigateToLoginRequestUrl: true,
2284
+ },
2285
+ cache: {
2286
+ cacheLocation: this.persistence === 'session' ? 'sessionStorage' : 'localStorage',
2287
+ storeAuthStateInCookie: false,
2288
+ },
2289
+ system: {
2290
+ loggerOptions: {
2291
+ loggerCallback: (_level, message) => {
2292
+ this.logger.debug(`MSAL: ${message}`);
2293
+ },
2294
+ },
2295
+ },
2296
+ };
2297
+ try {
2298
+ this.msalInstance = new msal.PublicClientApplication(this.msalConfig);
2299
+ await this.msalInstance.initialize();
2300
+ // Handle redirect response
2301
+ const response = await this.msalInstance.handleRedirectPromise();
2302
+ if (response && response.account) {
2303
+ await this.handleAuthResponse(response);
2304
+ }
2305
+ // Check for existing session
2306
+ const accounts = this.msalInstance.getAllAccounts();
2307
+ if (accounts.length > 0) {
2308
+ const account = accounts[0];
2309
+ const user = this.createUserFromMSALAccount(account);
2310
+ await this.setCurrentUser(user);
2311
+ }
2312
+ this.isInitialized = true;
2313
+ this.logger.info('Microsoft auth provider initialized');
2314
+ }
2315
+ catch (error) {
2316
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_INIT_FAILED, `Failed to initialize Microsoft auth: ${error}`, this.provider);
2317
+ }
2318
+ }
2319
+ async signIn(options) {
2320
+ this.validateInitialized();
2321
+ try {
2322
+ const loginRequest = Object.assign({ scopes: this.scopes }, options);
2323
+ // Try popup first, fallback to redirect
2324
+ let response;
2325
+ try {
2326
+ response = await this.msalInstance.loginPopup(loginRequest);
2327
+ }
2328
+ catch (popupError) {
2329
+ if (popupError.errorCode === 'popup_window_error') {
2330
+ // Popup blocked, use redirect
2331
+ await this.msalInstance.loginRedirect(loginRequest);
2332
+ // This will navigate away, so we won't reach here
2333
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Redirecting to Microsoft login...', this.provider);
2334
+ }
2335
+ throw popupError;
2336
+ }
2337
+ return await this.handleAuthResponse(response);
2338
+ }
2339
+ catch (error) {
2340
+ this.logger.error('Microsoft sign in failed', error);
2341
+ if (error.errorCode === 'user_cancelled') {
2342
+ throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
2343
+ }
2344
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${error.message}`, this.provider);
2345
+ }
2346
+ }
2347
+ async signOut(options) {
2348
+ this.validateInitialized();
2349
+ try {
2350
+ const account = this.msalInstance.getAllAccounts()[0];
2351
+ if (account) {
2352
+ const logoutRequest = {
2353
+ account,
2354
+ postLogoutRedirectUri: (options === null || options === void 0 ? void 0 : options.redirectUrl) || this.redirectUri,
2355
+ };
2356
+ if (options === null || options === void 0 ? void 0 : options.revokeToken) {
2357
+ // Use redirect logout to revoke tokens
2358
+ await this.msalInstance.logoutRedirect(logoutRequest);
2359
+ }
2360
+ else {
2361
+ // Just clear local session
2362
+ await this.msalInstance.logoutPopup(logoutRequest);
2363
+ }
2364
+ }
2365
+ await this.setCurrentUser(null);
2366
+ await this.clearStoredData();
2367
+ }
2368
+ catch (error) {
2369
+ this.logger.error('Microsoft sign out failed', error);
2370
+ throw new AuthError(exports.AuthErrorCode.SIGN_OUT_FAILED, `Microsoft sign out failed: ${error}`, this.provider);
2371
+ }
2372
+ }
2373
+ async refreshToken() {
2374
+ this.validateInitialized();
2375
+ try {
2376
+ const account = this.msalInstance.getAllAccounts()[0];
2377
+ if (!account) {
2378
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active Microsoft session', this.provider);
2379
+ }
2380
+ const silentRequest = {
2381
+ account,
2382
+ scopes: this.scopes,
2383
+ forceRefresh: true,
2384
+ };
2385
+ const response = await this.msalInstance.acquireTokenSilent(silentRequest);
2386
+ return await this.handleAuthResponse(response);
2387
+ }
2388
+ catch (error) {
2389
+ this.logger.error('Token refresh failed', error);
2390
+ if (error.errorCode === 'interaction_required') {
2391
+ // Need user interaction, trigger sign in
2392
+ return await this.signIn();
2393
+ }
2394
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${error.message}`, this.provider);
2395
+ }
2396
+ }
2397
+ async isSupported() {
2398
+ return typeof window !== 'undefined' && !!window.msal;
2399
+ }
2400
+ async linkAccount() {
2401
+ // Microsoft doesn't support account linking in the same way
2402
+ // Just trigger a new sign in
2403
+ return await this.signIn();
2404
+ }
2405
+ async unlinkAccount() {
2406
+ // Sign out to unlink
2407
+ await this.signOut();
2408
+ }
2409
+ async revokeAccess() {
2410
+ // Microsoft requires redirect to revoke tokens
2411
+ await this.signOut({ revokeToken: true });
2412
+ }
2413
+ async handleAuthResponse(response) {
2414
+ var _a;
2415
+ const user = this.createUserFromMSALAccount(response.account);
2416
+ await this.setCurrentUser(user);
2417
+ const credential = {
2418
+ providerId: this.provider,
2419
+ signInMethod: 'oauth',
2420
+ accessToken: response.accessToken,
2421
+ idToken: response.idToken,
2422
+ refreshToken: response.refreshToken || undefined,
2423
+ expiresAt: response.expiresOn ? response.expiresOn.getTime() : undefined,
2424
+ tokenType: response.tokenType,
2425
+ scope: response.scopes.join(' '),
2426
+ };
2427
+ await this.saveCredential(credential);
2428
+ return this.createAuthResult(user, credential, ((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser) || false);
2429
+ }
2430
+ createUserFromMSALAccount(account) {
2431
+ const idTokenClaims = account.idTokenClaims || {};
2432
+ return {
2433
+ uid: account.localAccountId || account.homeAccountId,
2434
+ email: idTokenClaims.email || account.username,
2435
+ emailVerified: !!idTokenClaims.email_verified,
2436
+ displayName: account.name || idTokenClaims.name,
2437
+ photoURL: idTokenClaims.picture || null,
2438
+ phoneNumber: idTokenClaims.phone_number || null,
2439
+ isAnonymous: false,
2440
+ tenantId: account.tenantId,
2441
+ providerData: [
2442
+ {
2443
+ providerId: this.provider,
2444
+ uid: account.localAccountId,
2445
+ displayName: account.name,
2446
+ email: account.username,
2447
+ phoneNumber: null,
2448
+ photoURL: idTokenClaims.picture || null,
2449
+ },
2450
+ ],
2451
+ metadata: {
2452
+ creationTime: idTokenClaims.iat
2453
+ ? new Date(idTokenClaims.iat * 1000).toISOString()
2454
+ : undefined,
2455
+ lastSignInTime: new Date().toISOString(),
2456
+ },
2457
+ customClaims: idTokenClaims,
2458
+ };
2459
+ }
2460
+ }
2461
+
2462
+ var microsoftProvider = /*#__PURE__*/Object.freeze({
2463
+ __proto__: null,
2464
+ MicrosoftAuthProviderWeb: MicrosoftAuthProviderWeb
2465
+ });
2466
+
2467
+ class FacebookAuthProviderWeb extends BaseAuthProvider {
2468
+ constructor() {
2469
+ super(...arguments);
2470
+ this.appId = '';
2471
+ this.version = '';
2472
+ this.scopes = [];
2473
+ this.fields = [];
2474
+ this.fbInitialized = false;
2475
+ }
2476
+ async initialize() {
2477
+ const options = this.options;
2478
+ if (!options.appId) {
2479
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'Facebook App ID is required', this.provider);
2480
+ }
2481
+ this.appId = options.appId;
2482
+ this.version = options.version || 'v18.0';
2483
+ this.scopes = options.scopes || ['email', 'public_profile'];
2484
+ this.fields = options.fields || [
2485
+ 'id',
2486
+ 'name',
2487
+ 'email',
2488
+ 'picture.type(large)',
2489
+ ];
2490
+ try {
2491
+ await this.loadFacebookSDK();
2492
+ await this.initializeFacebookSDK();
2493
+ // Check login status
2494
+ await this.checkLoginStatus();
2495
+ this.isInitialized = true;
2496
+ this.logger.info('Facebook auth provider initialized');
2497
+ }
2498
+ catch (error) {
2499
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_INIT_FAILED, `Failed to initialize Facebook auth: ${error}`, this.provider);
2500
+ }
2501
+ }
2502
+ loadFacebookSDK() {
2503
+ return new Promise((resolve) => {
2504
+ // Check if already loaded
2505
+ if (window.FB) {
2506
+ resolve();
2507
+ return;
2508
+ }
2509
+ // Check if script is already loading
2510
+ const existingScript = document.getElementById('facebook-jssdk');
2511
+ if (existingScript) {
2512
+ existingScript.addEventListener('load', () => resolve());
2513
+ return;
2514
+ }
2515
+ // Load the SDK
2516
+ const script = document.createElement('script');
2517
+ script.id = 'facebook-jssdk';
2518
+ script.src = `https://connect.facebook.net/en_US/sdk.js`;
2519
+ script.async = true;
2520
+ script.defer = true;
2521
+ script.onload = () => resolve();
2522
+ document.head.appendChild(script);
2523
+ });
2524
+ }
2525
+ initializeFacebookSDK() {
2526
+ return new Promise((resolve, reject) => {
2527
+ window.fbAsyncInit = () => {
2528
+ try {
2529
+ window.FB.init({
2530
+ appId: this.appId,
2531
+ cookie: true,
2532
+ xfbml: false,
2533
+ version: this.version,
2534
+ });
2535
+ this.fbInitialized = true;
2536
+ resolve();
2537
+ }
2538
+ catch (error) {
2539
+ reject(error);
2540
+ }
2541
+ };
2542
+ // If FB is already loaded, trigger init
2543
+ if (window.FB && !this.fbInitialized) {
2544
+ window.fbAsyncInit();
2545
+ }
2546
+ });
2547
+ }
2548
+ checkLoginStatus() {
2549
+ return new Promise((resolve) => {
2550
+ window.FB.getLoginStatus(async (response) => {
2551
+ if (response.status === 'connected') {
2552
+ await this.handleAuthResponse(response.authResponse);
2553
+ }
2554
+ resolve();
2555
+ });
2556
+ });
2557
+ }
2558
+ async signIn(_options) {
2559
+ this.validateInitialized();
2560
+ return new Promise((resolve, reject) => {
2561
+ window.FB.login(async (response) => {
2562
+ if (response.authResponse) {
2563
+ try {
2564
+ const result = await this.handleAuthResponse(response.authResponse);
2565
+ resolve(result);
2566
+ }
2567
+ catch (error) {
2568
+ reject(error);
2569
+ }
2570
+ }
2571
+ else if (response.status === 'unknown') {
2572
+ reject(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider));
2573
+ }
2574
+ else {
2575
+ reject(new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, 'Facebook sign in failed', this.provider));
2576
+ }
2577
+ }, {
2578
+ scope: this.scopes.join(','),
2579
+ auth_type: this.options.authType,
2580
+ });
2581
+ });
2582
+ }
2583
+ async signOut(options) {
2584
+ this.validateInitialized();
2585
+ return new Promise((resolve, reject) => {
2586
+ window.FB.logout(async () => {
2587
+ try {
2588
+ await this.setCurrentUser(null);
2589
+ await this.clearStoredData();
2590
+ if (options === null || options === void 0 ? void 0 : options.redirectUrl) {
2591
+ window.location.href = options.redirectUrl;
2592
+ }
2593
+ resolve();
2594
+ }
2595
+ catch (error) {
2596
+ reject(new AuthError(exports.AuthErrorCode.SIGN_OUT_FAILED, `Facebook sign out failed: ${error}`, this.provider));
2597
+ }
2598
+ });
2599
+ });
2600
+ }
2601
+ async refreshToken() {
2602
+ this.validateInitialized();
2603
+ // Facebook access tokens are short-lived and need to be refreshed via re-authentication
2604
+ return new Promise((resolve, reject) => {
2605
+ window.FB.getLoginStatus(async (response) => {
2606
+ if (response.status === 'connected') {
2607
+ try {
2608
+ const result = await this.handleAuthResponse(response.authResponse, true);
2609
+ resolve(result);
2610
+ }
2611
+ catch (error) {
2612
+ reject(error);
2613
+ }
2614
+ }
2615
+ else {
2616
+ // Token expired, need to re-authenticate
2617
+ this.signIn().then(resolve).catch(reject);
2618
+ }
2619
+ }, true); // Force fresh status check
2620
+ });
2621
+ }
2622
+ async isSupported() {
2623
+ return typeof window !== 'undefined';
2624
+ }
2625
+ async linkAccount() {
2626
+ // Facebook doesn't support account linking in the traditional sense
2627
+ // Re-authenticate to ensure current credentials
2628
+ return await this.signIn();
2629
+ }
2630
+ async unlinkAccount() {
2631
+ // Facebook doesn't support unlinking without app management
2632
+ // Best we can do is sign out
2633
+ await this.signOut();
2634
+ }
2635
+ async revokeAccess() {
2636
+ this.validateInitialized();
2637
+ return new Promise((resolve, reject) => {
2638
+ window.FB.api('/me/permissions', 'DELETE', async (response) => {
2639
+ if (response.success) {
2640
+ try {
2641
+ await this.setCurrentUser(null);
2642
+ await this.clearStoredData();
2643
+ resolve();
2644
+ }
2645
+ catch (error) {
2646
+ reject(error);
2647
+ }
2648
+ }
2649
+ else {
2650
+ reject(new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Failed to revoke Facebook access', this.provider));
2651
+ }
2652
+ });
2653
+ });
2654
+ }
2655
+ async handleAuthResponse(authResponse, isRefresh = false) {
2656
+ var _a, _b, _c, _d;
2657
+ // Get user data
2658
+ const userData = await this.getUserData(authResponse.accessToken);
2659
+ const user = {
2660
+ uid: authResponse.userID,
2661
+ email: userData.email || null,
2662
+ emailVerified: !!userData.email,
2663
+ displayName: userData.name || null,
2664
+ photoURL: ((_b = (_a = userData.picture) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.url) || null,
2665
+ phoneNumber: null,
2666
+ isAnonymous: false,
2667
+ tenantId: null,
2668
+ providerData: [
2669
+ {
2670
+ providerId: this.provider,
2671
+ uid: authResponse.userID,
2672
+ displayName: userData.name || null,
2673
+ email: userData.email || null,
2674
+ phoneNumber: null,
2675
+ photoURL: ((_d = (_c = userData.picture) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.url) || null,
2676
+ },
2677
+ ],
2678
+ metadata: {
2679
+ creationTime: userData.created_time || undefined,
2680
+ lastSignInTime: new Date().toISOString(),
2681
+ },
2682
+ };
2683
+ await this.setCurrentUser(user);
2684
+ const credential = {
2685
+ providerId: this.provider,
2686
+ signInMethod: 'oauth',
2687
+ accessToken: authResponse.accessToken,
2688
+ idToken: authResponse.signedRequest,
2689
+ refreshToken: undefined, // Facebook doesn't provide refresh tokens
2690
+ expiresAt: authResponse.expiresIn
2691
+ ? Date.now() + authResponse.expiresIn * 1000
2692
+ : undefined,
2693
+ tokenType: 'bearer',
2694
+ scope: this.scopes.join(' '),
2695
+ };
2696
+ await this.saveCredential(credential);
2697
+ return this.createAuthResult(user, credential, !isRefresh && !userData.created_time);
2698
+ }
2699
+ getUserData(accessToken) {
2700
+ return new Promise((resolve, reject) => {
2701
+ window.FB.api('/me', { fields: this.fields.join(','), access_token: accessToken }, (response) => {
2702
+ if (response.error) {
2703
+ reject(new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to get user data: ${response.error.message}`, this.provider));
2704
+ }
2705
+ else {
2706
+ resolve(response);
2707
+ }
2708
+ });
2709
+ });
2710
+ }
2711
+ }
2712
+
2713
+ var facebookProvider = /*#__PURE__*/Object.freeze({
2714
+ __proto__: null,
2715
+ FacebookAuthProviderWeb: FacebookAuthProviderWeb
2716
+ });
2717
+
2718
+ class GitHubAuthProviderWeb extends BaseAuthProvider {
2719
+ constructor() {
2720
+ super(...arguments);
2721
+ this.clientId = '';
2722
+ this.redirectUri = '';
2723
+ this.scopes = [];
2724
+ this.authWindow = null;
2725
+ this.authPromise = null;
2726
+ }
2727
+ async initialize() {
2728
+ const options = this.options;
2729
+ if (!options.clientId) {
2730
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'GitHub client ID is required', this.provider);
2731
+ }
2732
+ this.clientId = options.clientId;
2733
+ this.redirectUri =
2734
+ options.redirectUri || window.location.origin + '/auth/github/callback';
2735
+ this.scopes = options.scopes || ['read:user', 'user:email'];
2736
+ // Set up message listener for OAuth callback
2737
+ window.addEventListener('message', this.handleAuthMessage.bind(this));
2738
+ // Check for stored session
2739
+ await this.loadCurrentUser();
2740
+ this.isInitialized = true;
2741
+ this.logger.info('GitHub auth provider initialized');
2742
+ }
2743
+ async signIn(_options) {
2744
+ this.validateInitialized();
2745
+ return new Promise((resolve, reject) => {
2746
+ this.authPromise = { resolve, reject };
2747
+ const state = this.generateState();
2748
+ const authUrl = this.buildAuthUrl(state);
2749
+ // Open GitHub OAuth in a popup window
2750
+ const width = 600;
2751
+ const height = 700;
2752
+ const left = window.screenX + (window.outerWidth - width) / 2;
2753
+ const top = window.screenY + (window.outerHeight - height) / 2;
2754
+ this.authWindow = window.open(authUrl, 'github-auth', `width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no`);
2755
+ if (!this.authWindow) {
2756
+ this.authPromise = null;
2757
+ reject(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, 'Popup window was blocked. Please allow popups for this site.', this.provider));
2758
+ return;
2759
+ }
2760
+ // Check if popup is closed
2761
+ const checkInterval = setInterval(() => {
2762
+ var _a;
2763
+ if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
2764
+ clearInterval(checkInterval);
2765
+ if (this.authPromise) {
2766
+ this.authPromise = null;
2767
+ reject(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User closed the authentication window', this.provider));
2768
+ }
2769
+ }
2770
+ }, 1000);
2771
+ });
2772
+ }
2773
+ async signOut(options) {
2774
+ this.validateInitialized();
2775
+ try {
2776
+ await this.setCurrentUser(null);
2777
+ await this.clearStoredData();
2778
+ if (options === null || options === void 0 ? void 0 : options.revokeToken) {
2779
+ // GitHub requires using their API to revoke tokens
2780
+ // This would need to be done server-side for security
2781
+ this.logger.warn('Token revocation should be handled server-side for GitHub');
2782
+ }
2783
+ if (options === null || options === void 0 ? void 0 : options.redirectUrl) {
2784
+ window.location.href = options.redirectUrl;
2785
+ }
2786
+ }
2787
+ catch (error) {
2788
+ throw new AuthError(exports.AuthErrorCode.SIGN_OUT_FAILED, `GitHub sign out failed: ${error}`, this.provider);
2789
+ }
2790
+ }
2791
+ async refreshToken() {
2792
+ this.validateInitialized();
2793
+ // GitHub access tokens don't expire, but we can validate the current session
2794
+ const credential = await this.loadCredential();
2795
+ if (!(credential === null || credential === void 0 ? void 0 : credential.accessToken)) {
2796
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active GitHub session', this.provider);
2797
+ }
2798
+ try {
2799
+ // Validate token by fetching user data
2800
+ const userData = await this.fetchUserData(credential.accessToken);
2801
+ const user = await this.createUserFromGitHubData(userData, credential.accessToken);
2802
+ await this.setCurrentUser(user);
2803
+ return this.createAuthResult(user, credential, false);
2804
+ }
2805
+ catch (error) {
2806
+ // Token is invalid, need to re-authenticate
2807
+ this.logger.error('Token validation failed, re-authenticating', error);
2808
+ return await this.signIn();
2809
+ }
2810
+ }
2811
+ async isSupported() {
2812
+ return typeof window !== 'undefined' && 'open' in window;
2813
+ }
2814
+ async linkAccount() {
2815
+ // GitHub doesn't support account linking
2816
+ // Re-authenticate to ensure current credentials
2817
+ return await this.signIn();
2818
+ }
2819
+ async unlinkAccount() {
2820
+ await this.signOut();
2821
+ }
2822
+ async revokeAccess(_token) {
2823
+ // GitHub token revocation requires server-side implementation
2824
+ // for security reasons (needs client secret)
2825
+ this.logger.warn('GitHub token revocation should be implemented server-side');
2826
+ await this.signOut({ revokeToken: true });
2827
+ }
2828
+ buildAuthUrl(state) {
2829
+ const params = new URLSearchParams({
2830
+ client_id: this.clientId,
2831
+ redirect_uri: this.redirectUri,
2832
+ scope: this.scopes.join(' '),
2833
+ state: state,
2834
+ allow_signup: 'true',
2835
+ });
2836
+ return `https://github.com/login/oauth/authorize?${params.toString()}`;
2837
+ }
2838
+ generateState() {
2839
+ return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));
2840
+ }
2841
+ async handleAuthMessage(event) {
2842
+ var _a;
2843
+ // Validate origin
2844
+ if (!event.origin.startsWith(window.location.origin)) {
2845
+ return;
2846
+ }
2847
+ // Check if this is our auth message
2848
+ if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) !== 'github-auth-callback') {
2849
+ return;
2850
+ }
2851
+ if (this.authWindow) {
2852
+ this.authWindow.close();
2853
+ this.authWindow = null;
2854
+ }
2855
+ if (!this.authPromise) {
2856
+ return;
2857
+ }
2858
+ const { resolve, reject } = this.authPromise;
2859
+ this.authPromise = null;
2860
+ try {
2861
+ if (event.data.error) {
2862
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, event.data.error, this.provider);
2863
+ }
2864
+ if (!event.data.code) {
2865
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, 'No authorization code received', this.provider);
2866
+ }
2867
+ // Exchange code for token (this should be done server-side in production)
2868
+ const tokenData = await this.exchangeCodeForToken(event.data.code);
2869
+ // Get user data
2870
+ const userData = await this.fetchUserData(tokenData.access_token);
2871
+ const user = await this.createUserFromGitHubData(userData, tokenData.access_token);
2872
+ await this.setCurrentUser(user);
2873
+ const credential = {
2874
+ providerId: this.provider,
2875
+ signInMethod: 'oauth',
2876
+ accessToken: tokenData.access_token,
2877
+ idToken: undefined,
2878
+ refreshToken: tokenData.refresh_token,
2879
+ expiresAt: tokenData.expires_in
2880
+ ? Date.now() + tokenData.expires_in * 1000
2881
+ : undefined,
2882
+ tokenType: tokenData.token_type || 'bearer',
2883
+ scope: tokenData.scope || this.scopes.join(' '),
2884
+ };
2885
+ await this.saveCredential(credential);
2886
+ const result = this.createAuthResult(user, credential, true);
2887
+ resolve(result);
2888
+ }
2889
+ catch (error) {
2890
+ reject(AuthError.fromError(error, this.provider));
2891
+ }
2892
+ }
2893
+ async exchangeCodeForToken(_code) {
2894
+ // NOTE: This should be done server-side in production to keep client secret secure
2895
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'GitHub token exchange must be implemented server-side. Please set up a backend endpoint to exchange the authorization code for an access token.', this.provider);
2896
+ }
2897
+ async fetchUserData(accessToken) {
2898
+ const response = await fetch('https://api.github.com/user', {
2899
+ headers: {
2900
+ Authorization: `Bearer ${accessToken}`,
2901
+ Accept: 'application/vnd.github.v3+json',
2902
+ },
2903
+ });
2904
+ if (!response.ok) {
2905
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to fetch user data: ${response.statusText}`, this.provider);
2906
+ }
2907
+ return await response.json();
2908
+ }
2909
+ async fetchUserEmails(accessToken) {
2910
+ const response = await fetch('https://api.github.com/user/emails', {
2911
+ headers: {
2912
+ Authorization: `Bearer ${accessToken}`,
2913
+ Accept: 'application/vnd.github.v3+json',
2914
+ },
2915
+ });
2916
+ if (!response.ok) {
2917
+ return [];
2918
+ }
2919
+ return await response.json();
2920
+ }
2921
+ async createUserFromGitHubData(userData, accessToken) {
2922
+ // Get primary email
2923
+ const emails = await this.fetchUserEmails(accessToken);
2924
+ const primaryEmail = emails.find((e) => e.primary) || emails[0];
2925
+ return {
2926
+ uid: userData.id.toString(),
2927
+ email: (primaryEmail === null || primaryEmail === void 0 ? void 0 : primaryEmail.email) || userData.email || null,
2928
+ emailVerified: (primaryEmail === null || primaryEmail === void 0 ? void 0 : primaryEmail.verified) || false,
2929
+ displayName: userData.name || userData.login,
2930
+ photoURL: userData.avatar_url || null,
2931
+ phoneNumber: null,
2932
+ isAnonymous: false,
2933
+ tenantId: null,
2934
+ providerData: [
2935
+ {
2936
+ providerId: this.provider,
2937
+ uid: userData.id.toString(),
2938
+ displayName: userData.name || userData.login,
2939
+ email: (primaryEmail === null || primaryEmail === void 0 ? void 0 : primaryEmail.email) || userData.email || null,
2940
+ phoneNumber: null,
2941
+ photoURL: userData.avatar_url || null,
2942
+ },
2943
+ ],
2944
+ metadata: {
2945
+ creationTime: userData.created_at
2946
+ ? new Date(userData.created_at).toISOString()
2947
+ : undefined,
2948
+ lastSignInTime: new Date().toISOString(),
2949
+ },
2950
+ customClaims: {
2951
+ login: userData.login,
2952
+ company: userData.company,
2953
+ location: userData.location,
2954
+ bio: userData.bio,
2955
+ public_repos: userData.public_repos,
2956
+ followers: userData.followers,
2957
+ following: userData.following,
2958
+ },
2959
+ };
2960
+ }
2961
+ }
2962
+
2963
+ var githubProvider = /*#__PURE__*/Object.freeze({
2964
+ __proto__: null,
2965
+ GitHubAuthProviderWeb: GitHubAuthProviderWeb
2966
+ });
2967
+
2968
+ class FirebaseAuthProviderWeb extends BaseAuthProvider {
2969
+ constructor() {
2970
+ super(...arguments);
2971
+ this.unsubscribeAuth = null;
2972
+ }
2973
+ async initialize() {
2974
+ const options = this.options;
2975
+ if (!options.apiKey || !options.authDomain || !options.projectId) {
2976
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'Firebase configuration (apiKey, authDomain, projectId) is required', this.provider);
2977
+ }
2978
+ try {
2979
+ // Check if Firebase is available
2980
+ const firebase = window.firebase;
2981
+ if (!firebase) {
2982
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded. Please include the Firebase scripts in your HTML.', this.provider);
2983
+ }
2984
+ // Initialize Firebase app
2985
+ const firebaseConfig = {
2986
+ apiKey: options.apiKey,
2987
+ authDomain: options.authDomain,
2988
+ projectId: options.projectId,
2989
+ storageBucket: options.storageBucket,
2990
+ messagingSenderId: options.messagingSenderId,
2991
+ appId: options.appId,
2992
+ measurementId: options.measurementId,
2993
+ };
2994
+ // Check if app already exists
2995
+ this.firebaseApp =
2996
+ firebase.apps.length > 0
2997
+ ? firebase.app()
2998
+ : firebase.initializeApp(firebaseConfig);
2999
+ this.firebaseAuth = firebase.auth(this.firebaseApp);
3000
+ // Configure persistence
3001
+ const persistenceMode = this.getPersistenceMode();
3002
+ await this.firebaseAuth.setPersistence(persistenceMode);
3003
+ // Set up auth state listener
3004
+ this.unsubscribeAuth = this.firebaseAuth.onAuthStateChanged(async (firebaseUser) => {
3005
+ if (firebaseUser) {
3006
+ const user = await this.createUserFromFirebaseUser(firebaseUser);
3007
+ await this.setCurrentUser(user);
3008
+ }
3009
+ else {
3010
+ await this.setCurrentUser(null);
3011
+ }
3012
+ });
3013
+ // Wait for auth state to be determined
3014
+ await new Promise((resolve) => {
3015
+ const unsubscribe = this.firebaseAuth.onAuthStateChanged(() => {
3016
+ unsubscribe();
3017
+ resolve(undefined);
3018
+ });
3019
+ });
3020
+ this.isInitialized = true;
3021
+ this.logger.info('Firebase auth provider initialized');
3022
+ }
3023
+ catch (error) {
3024
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_INIT_FAILED, `Failed to initialize Firebase auth: ${error}`, this.provider);
3025
+ }
3026
+ }
3027
+ getPersistenceMode() {
3028
+ const firebase = window.firebase;
3029
+ switch (this.persistence) {
3030
+ case 'session':
3031
+ return firebase.auth.Auth.Persistence.SESSION;
3032
+ case 'none':
3033
+ return firebase.auth.Auth.Persistence.NONE;
3034
+ default:
3035
+ return firebase.auth.Auth.Persistence.LOCAL;
3036
+ }
3037
+ }
3038
+ async signIn(options) {
3039
+ this.validateInitialized();
3040
+ const signInOptions = options || {};
3041
+ try {
3042
+ let firebaseUser;
3043
+ let credential;
3044
+ let additionalUserInfo;
3045
+ // Determine sign-in method
3046
+ if (signInOptions.method === 'google') {
3047
+ const provider = new window.firebase.auth.GoogleAuthProvider();
3048
+ if (signInOptions.scopes) {
3049
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3050
+ }
3051
+ const result = await this.firebaseAuth.signInWithPopup(provider);
3052
+ firebaseUser = result.user;
3053
+ credential = result.credential;
3054
+ additionalUserInfo = result.additionalUserInfo;
3055
+ }
3056
+ else if (signInOptions.method === 'facebook') {
3057
+ const provider = new window.firebase.auth.FacebookAuthProvider();
3058
+ if (signInOptions.scopes) {
3059
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3060
+ }
3061
+ const result = await this.firebaseAuth.signInWithPopup(provider);
3062
+ firebaseUser = result.user;
3063
+ credential = result.credential;
3064
+ additionalUserInfo = result.additionalUserInfo;
3065
+ }
3066
+ else if (signInOptions.method === 'github') {
3067
+ const provider = new window.firebase.auth.GithubAuthProvider();
3068
+ if (signInOptions.scopes) {
3069
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3070
+ }
3071
+ const result = await this.firebaseAuth.signInWithPopup(provider);
3072
+ firebaseUser = result.user;
3073
+ credential = result.credential;
3074
+ additionalUserInfo = result.additionalUserInfo;
3075
+ }
3076
+ else if (signInOptions.method === 'microsoft') {
3077
+ const provider = new window.firebase.auth.OAuthProvider('microsoft.com');
3078
+ if (signInOptions.scopes) {
3079
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3080
+ }
3081
+ const result = await this.firebaseAuth.signInWithPopup(provider);
3082
+ firebaseUser = result.user;
3083
+ credential = result.credential;
3084
+ additionalUserInfo = result.additionalUserInfo;
3085
+ }
3086
+ else if (signInOptions.method === 'apple') {
3087
+ const provider = new window.firebase.auth.OAuthProvider('apple.com');
3088
+ if (signInOptions.scopes) {
3089
+ signInOptions.scopes.forEach((scope) => provider.addScope(scope));
3090
+ }
3091
+ const result = await this.firebaseAuth.signInWithPopup(provider);
3092
+ firebaseUser = result.user;
3093
+ credential = result.credential;
3094
+ additionalUserInfo = result.additionalUserInfo;
3095
+ }
3096
+ else if (signInOptions.method === 'email' &&
3097
+ signInOptions.email &&
3098
+ signInOptions.password) {
3099
+ const result = await this.firebaseAuth.signInWithEmailAndPassword(signInOptions.email, signInOptions.password);
3100
+ firebaseUser = result.user;
3101
+ credential = {
3102
+ providerId: 'password',
3103
+ signInMethod: 'password',
3104
+ };
3105
+ additionalUserInfo = { isNewUser: false, providerId: 'password' };
3106
+ }
3107
+ else if (signInOptions.method === 'anonymous') {
3108
+ const result = await this.firebaseAuth.signInAnonymously();
3109
+ firebaseUser = result.user;
3110
+ credential = {
3111
+ providerId: 'anonymous',
3112
+ signInMethod: 'anonymous',
3113
+ };
3114
+ additionalUserInfo = { isNewUser: true, providerId: 'anonymous' };
3115
+ }
3116
+ else {
3117
+ throw new AuthError(exports.AuthErrorCode.INVALID_REQUEST, 'Invalid sign-in method or missing credentials', this.provider);
3118
+ }
3119
+ const user = await this.createUserFromFirebaseUser(firebaseUser);
3120
+ const authCredential = await this.createCredentialFromFirebase(credential, firebaseUser);
3121
+ await this.saveCredential(authCredential);
3122
+ return this.createAuthResult(user, authCredential, (additionalUserInfo === null || additionalUserInfo === void 0 ? void 0 : additionalUserInfo.isNewUser) || false);
3123
+ }
3124
+ catch (error) {
3125
+ this.logger.error('Firebase sign in failed', error);
3126
+ if (error.code === 'auth/popup-closed-by-user' ||
3127
+ error.code === 'auth/cancelled-popup-request') {
3128
+ throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
3129
+ }
3130
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${error.message}`, this.provider);
3131
+ }
3132
+ }
3133
+ async signOut(options) {
3134
+ this.validateInitialized();
3135
+ try {
3136
+ await this.firebaseAuth.signOut();
3137
+ if (options === null || options === void 0 ? void 0 : options.redirectUrl) {
3138
+ window.location.href = options.redirectUrl;
3139
+ }
3140
+ }
3141
+ catch (error) {
3142
+ this.logger.error('Firebase sign out failed', error);
3143
+ throw new AuthError(exports.AuthErrorCode.SIGN_OUT_FAILED, `Firebase sign out failed: ${error}`, this.provider);
3144
+ }
3145
+ }
3146
+ async refreshToken() {
3147
+ this.validateInitialized();
3148
+ try {
3149
+ const currentUser = this.firebaseAuth.currentUser;
3150
+ if (!currentUser) {
3151
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active Firebase session', this.provider);
3152
+ }
3153
+ // Force token refresh
3154
+ const idToken = await currentUser.getIdToken(true);
3155
+ const user = await this.createUserFromFirebaseUser(currentUser);
3156
+ const credential = {
3157
+ providerId: this.provider,
3158
+ signInMethod: 'firebase',
3159
+ idToken: idToken,
3160
+ accessToken: undefined,
3161
+ refreshToken: currentUser.refreshToken,
3162
+ expiresAt: undefined, // Firebase handles token expiry internally
3163
+ tokenType: 'Bearer',
3164
+ };
3165
+ await this.saveCredential(credential);
3166
+ return this.createAuthResult(user, credential, false);
3167
+ }
3168
+ catch (error) {
3169
+ this.logger.error('Token refresh failed', error);
3170
+ throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${error}`, this.provider);
3171
+ }
3172
+ }
3173
+ async isSupported() {
3174
+ return typeof window !== 'undefined' && !!window.firebase;
3175
+ }
3176
+ async linkAccount(options) {
3177
+ this.validateInitialized();
3178
+ const currentUser = this.firebaseAuth.currentUser;
3179
+ if (!currentUser) {
3180
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session to link account to', this.provider);
3181
+ }
3182
+ try {
3183
+ let result;
3184
+ if (options.method === 'google') {
3185
+ const provider = new window.firebase.auth.GoogleAuthProvider();
3186
+ result = await currentUser.linkWithPopup(provider);
3187
+ }
3188
+ else if (options.method === 'email' &&
3189
+ options.email &&
3190
+ options.password) {
3191
+ const credential = window.firebase.auth.EmailAuthProvider.credential(options.email, options.password);
3192
+ result = await currentUser.linkWithCredential(credential);
3193
+ }
3194
+ else {
3195
+ throw new AuthError(exports.AuthErrorCode.INVALID_REQUEST, 'Invalid link method or missing credentials', this.provider);
3196
+ }
3197
+ const user = await this.createUserFromFirebaseUser(result.user);
3198
+ const authCredential = await this.createCredentialFromFirebase(result.credential, result.user);
3199
+ return this.createAuthResult(user, authCredential, false, 'link');
3200
+ }
3201
+ catch (error) {
3202
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to link account: ${error.message}`, this.provider);
3203
+ }
3204
+ }
3205
+ async unlinkAccount(options) {
3206
+ this.validateInitialized();
3207
+ const currentUser = this.firebaseAuth.currentUser;
3208
+ if (!currentUser) {
3209
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session', this.provider);
3210
+ }
3211
+ try {
3212
+ await currentUser.unlink(options.providerId);
3213
+ }
3214
+ catch (error) {
3215
+ throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to unlink account: ${error.message}`, this.provider);
3216
+ }
3217
+ }
3218
+ async revokeAccess() {
3219
+ // Firebase doesn't support token revocation directly
3220
+ await this.signOut();
3221
+ }
3222
+ async createUserFromFirebaseUser(firebaseUser) {
3223
+ const idTokenResult = await firebaseUser.getIdTokenResult();
3224
+ return {
3225
+ uid: firebaseUser.uid,
3226
+ email: firebaseUser.email,
3227
+ emailVerified: firebaseUser.emailVerified,
3228
+ displayName: firebaseUser.displayName,
3229
+ photoURL: firebaseUser.photoURL,
3230
+ phoneNumber: firebaseUser.phoneNumber,
3231
+ isAnonymous: firebaseUser.isAnonymous,
3232
+ tenantId: firebaseUser.tenantId,
3233
+ providerData: firebaseUser.providerData.map((provider) => ({
3234
+ providerId: provider.providerId,
3235
+ uid: provider.uid,
3236
+ displayName: provider.displayName,
3237
+ email: provider.email,
3238
+ phoneNumber: provider.phoneNumber,
3239
+ photoURL: provider.photoURL,
3240
+ })),
3241
+ metadata: {
3242
+ creationTime: firebaseUser.metadata.creationTime,
3243
+ lastSignInTime: firebaseUser.metadata.lastSignInTime,
3244
+ },
3245
+ customClaims: idTokenResult.claims,
3246
+ refreshToken: firebaseUser.refreshToken,
3247
+ };
3248
+ }
3249
+ async createCredentialFromFirebase(credential, user) {
3250
+ const idToken = await user.getIdToken();
3251
+ return {
3252
+ providerId: (credential === null || credential === void 0 ? void 0 : credential.providerId) || this.provider,
3253
+ signInMethod: (credential === null || credential === void 0 ? void 0 : credential.signInMethod) || 'firebase',
3254
+ accessToken: credential === null || credential === void 0 ? void 0 : credential.accessToken,
3255
+ idToken: idToken,
3256
+ refreshToken: user.refreshToken,
3257
+ expiresAt: undefined, // Firebase manages token expiry
3258
+ tokenType: 'Bearer',
3259
+ rawNonce: credential === null || credential === void 0 ? void 0 : credential.nonce,
3260
+ };
3261
+ }
3262
+ dispose() {
3263
+ if (this.unsubscribeAuth) {
3264
+ this.unsubscribeAuth();
3265
+ this.unsubscribeAuth = null;
3266
+ }
3267
+ super.dispose();
3268
+ }
3269
+ }
3270
+
3271
+ var firebaseProvider = /*#__PURE__*/Object.freeze({
3272
+ __proto__: null,
3273
+ FirebaseAuthProviderWeb: FirebaseAuthProviderWeb
3274
+ });
3275
+
3276
+ class MagicLinkProvider {
3277
+ constructor(config) {
3278
+ this.name = 'magic-link';
3279
+ this.pendingVerification = new Map();
3280
+ // Initialize with config
3281
+ this.config = config;
3282
+ // Check for magic link callback on initialization
3283
+ this.checkForMagicLinkCallback();
3284
+ }
3285
+ async signIn(options) {
3286
+ if (!(options === null || options === void 0 ? void 0 : options.email)) {
3287
+ throw new AuthError('EMAIL_REQUIRED', 'Email is required for magic link authentication');
3288
+ }
3289
+ try {
3290
+ // Send magic link to email
3291
+ const token = this.generateToken();
3292
+ const magicLink = this.generateMagicLink(token);
3293
+ // Store pending verification
3294
+ this.pendingVerification.set(token, {
3295
+ email: options.email,
3296
+ expires: Date.now() + 15 * 60 * 1000, // 15 minutes
3297
+ });
3298
+ // Send email via backend API
3299
+ const response = await fetch(this.config.sendLinkUrl, {
3300
+ method: 'POST',
3301
+ headers: {
3302
+ 'Content-Type': 'application/json',
3303
+ },
3304
+ body: JSON.stringify({
3305
+ email: options.email,
3306
+ magicLink,
3307
+ clientId: this.config.clientId,
3308
+ template: this.config.emailTemplate,
3309
+ }),
3310
+ });
3311
+ if (!response.ok) {
3312
+ throw new AuthError('SEND_LINK_FAILED', 'Failed to send magic link');
3313
+ }
3314
+ // Return partial auth result for pending state
3315
+ const tempUser = {
3316
+ uid: `magic-link-pending:${token}`,
3317
+ email: options.email,
3318
+ displayName: options.email.split('@')[0],
3319
+ photoURL: null,
3320
+ emailVerified: false,
3321
+ providerData: [],
3322
+ metadata: {
3323
+ creationTime: new Date().toISOString(),
3324
+ lastSignInTime: new Date().toISOString(),
3325
+ },
3326
+ };
3327
+ return {
3328
+ user: tempUser,
3329
+ credential: {
3330
+ providerId: this.name,
3331
+ signInMethod: 'magic-link',
3332
+ accessToken: token,
3333
+ },
3334
+ additionalUserInfo: {
3335
+ isNewUser: false,
3336
+ providerId: this.name,
3337
+ profile: {
3338
+ email: options.email,
3339
+ message: 'Magic link sent. Check your email to complete sign in.',
3340
+ pending: true,
3341
+ },
3342
+ },
3343
+ };
3344
+ }
3345
+ catch (error) {
3346
+ throw new AuthError('MAGIC_LINK_ERROR', error.message || 'Failed to send magic link');
3347
+ }
3348
+ }
3349
+ async verifyMagicLink(token) {
3350
+ const pending = this.pendingVerification.get(token);
3351
+ if (!pending) {
3352
+ throw new AuthError('INVALID_TOKEN', 'Invalid or expired magic link');
3353
+ }
3354
+ if (Date.now() > pending.expires) {
3355
+ this.pendingVerification.delete(token);
3356
+ throw new AuthError('TOKEN_EXPIRED', 'Magic link has expired');
3357
+ }
3358
+ try {
3359
+ // Verify token with backend if configured
3360
+ if (this.config.verifyUrl) {
3361
+ const response = await fetch(this.config.verifyUrl, {
3362
+ method: 'POST',
3363
+ headers: {
3364
+ 'Content-Type': 'application/json',
3365
+ },
3366
+ body: JSON.stringify({
3367
+ token,
3368
+ email: pending.email,
3369
+ clientId: this.config.clientId,
3370
+ }),
3371
+ });
3372
+ if (!response.ok) {
3373
+ throw new AuthError('VERIFICATION_FAILED', 'Failed to verify magic link');
3374
+ }
3375
+ const data = await response.json();
3376
+ // Create user from verified data
3377
+ const user = {
3378
+ uid: data.uid || this.generateUid(pending.email),
3379
+ email: pending.email,
3380
+ displayName: data.displayName || pending.email.split('@')[0],
3381
+ photoURL: data.photoURL || null,
3382
+ emailVerified: true,
3383
+ providerData: [
3384
+ {
3385
+ providerId: this.name,
3386
+ uid: data.uid || pending.email,
3387
+ displayName: data.displayName || pending.email.split('@')[0],
3388
+ email: pending.email,
3389
+ phoneNumber: null,
3390
+ photoURL: data.photoURL || null,
3391
+ },
3392
+ ],
3393
+ metadata: {
3394
+ creationTime: data.createdAt || new Date().toISOString(),
3395
+ lastSignInTime: new Date().toISOString(),
3396
+ },
3397
+ };
3398
+ // Clean up pending verification
3399
+ this.pendingVerification.delete(token);
3400
+ return {
3401
+ user,
3402
+ credential: {
3403
+ providerId: this.name,
3404
+ signInMethod: 'magic-link',
3405
+ accessToken: data.accessToken || token,
3406
+ expiresAt: data.expiresAt,
3407
+ },
3408
+ additionalUserInfo: {
3409
+ isNewUser: data.isNewUser || false,
3410
+ providerId: this.name,
3411
+ },
3412
+ };
3413
+ }
3414
+ else {
3415
+ // Simple verification without backend
3416
+ const user = {
3417
+ uid: this.generateUid(pending.email),
3418
+ email: pending.email,
3419
+ displayName: pending.email.split('@')[0],
3420
+ photoURL: null,
3421
+ emailVerified: true,
3422
+ providerData: [
3423
+ {
3424
+ providerId: this.name,
3425
+ uid: pending.email,
3426
+ displayName: pending.email.split('@')[0],
3427
+ email: pending.email,
3428
+ phoneNumber: null,
3429
+ photoURL: null,
3430
+ },
3431
+ ],
3432
+ metadata: {
3433
+ creationTime: new Date().toISOString(),
3434
+ lastSignInTime: new Date().toISOString(),
3435
+ },
3436
+ };
3437
+ // Clean up pending verification
3438
+ this.pendingVerification.delete(token);
3439
+ return {
3440
+ user,
3441
+ credential: {
3442
+ providerId: this.name,
3443
+ signInMethod: 'magic-link',
3444
+ accessToken: token,
3445
+ },
3446
+ additionalUserInfo: {
3447
+ isNewUser: true,
3448
+ providerId: this.name,
3449
+ },
3450
+ };
3451
+ }
3452
+ }
3453
+ catch (error) {
3454
+ throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify magic link');
3455
+ }
3456
+ }
3457
+ async signOut() {
3458
+ // Clear any pending verifications
3459
+ this.pendingVerification.clear();
3460
+ }
3461
+ async getCurrentUser() {
3462
+ // Magic link doesn't persist sessions by default
3463
+ return null;
3464
+ }
3465
+ async refreshToken() {
3466
+ throw new AuthError('NOT_SUPPORTED', 'Token refresh is not supported for magic link authentication');
3467
+ }
3468
+ generateToken() {
3469
+ const array = new Uint8Array(32);
3470
+ crypto.getRandomValues(array);
3471
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');
3472
+ }
3473
+ generateMagicLink(token) {
3474
+ const redirectUrl = this.config.redirectUrl || window.location.origin;
3475
+ const url = new URL(redirectUrl);
3476
+ url.searchParams.set('token', token);
3477
+ url.searchParams.set('provider', 'magic-link');
3478
+ return url.toString();
3479
+ }
3480
+ generateUid(email) {
3481
+ return `magic-link:${email.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
3482
+ }
3483
+ checkForMagicLinkCallback() {
3484
+ if (typeof window === 'undefined')
3485
+ return;
3486
+ const urlParams = new URLSearchParams(window.location.search);
3487
+ const token = urlParams.get('token');
3488
+ const provider = urlParams.get('provider');
3489
+ if (token && provider === 'magic-link') {
3490
+ // Store token for later verification
3491
+ sessionStorage.setItem('magic-link-token', token);
3492
+ // Clean up URL
3493
+ urlParams.delete('token');
3494
+ urlParams.delete('provider');
3495
+ const newUrl = window.location.pathname +
3496
+ (urlParams.toString() ? '?' + urlParams.toString() : '');
3497
+ window.history.replaceState({}, document.title, newUrl);
3498
+ }
3499
+ }
3500
+ async checkStoredToken() {
3501
+ if (typeof window === 'undefined')
3502
+ return null;
3503
+ const token = sessionStorage.getItem('magic-link-token');
3504
+ if (!token)
3505
+ return null;
3506
+ try {
3507
+ const result = await this.verifyMagicLink(token);
3508
+ sessionStorage.removeItem('magic-link-token');
3509
+ return result;
3510
+ }
3511
+ catch (error) {
3512
+ sessionStorage.removeItem('magic-link-token');
3513
+ throw error;
3514
+ }
3515
+ }
3516
+ async initialize() {
3517
+ // Magic link provider doesn't require initialization
3518
+ }
3519
+ async isSupported() {
3520
+ // Magic link auth is supported if we have the required config
3521
+ return !!this.config.sendLinkUrl;
3522
+ }
3523
+ async linkAccount(_options) {
3524
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for magic link authentication');
3525
+ }
3526
+ async unlinkAccount(_options) {
3527
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for magic link authentication');
3528
+ }
3529
+ async revokeAccess(_token) {
3530
+ // Magic link doesn't have persistent access to revoke
3531
+ this.pendingVerification.clear();
3532
+ }
3533
+ }
3534
+
3535
+ var magicLinkProvider = /*#__PURE__*/Object.freeze({
3536
+ __proto__: null,
3537
+ MagicLinkProvider: MagicLinkProvider
3538
+ });
3539
+
3540
+ class SMSProvider {
3541
+ constructor(config) {
3542
+ this.name = 'sms';
3543
+ this.pendingVerifications = new Map();
3544
+ this.MAX_ATTEMPTS = 3;
3545
+ // Initialize with config
3546
+ this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, config);
3547
+ }
3548
+ async signIn(options) {
3549
+ if (!(options === null || options === void 0 ? void 0 : options.phoneNumber)) {
3550
+ throw new AuthError('PHONE_REQUIRED', 'Phone number is required for SMS authentication');
3551
+ }
3552
+ // If code is provided, verify it
3553
+ if (options.code) {
3554
+ return this.verifyCode(options.phoneNumber, options.code);
3555
+ }
3556
+ // Otherwise, send code
3557
+ return this.sendCode(options.phoneNumber);
3558
+ }
3559
+ async sendCode(phoneNumber) {
3560
+ try {
3561
+ // Format phone number
3562
+ const formattedPhone = this.formatPhoneNumber(phoneNumber);
3563
+ // Check if we can resend
3564
+ const existing = this.pendingVerifications.get(formattedPhone);
3565
+ if (existing && existing.lastResent) {
3566
+ const timeSinceLastResend = Date.now() - existing.lastResent;
3567
+ if (timeSinceLastResend < this.config.resendDelay) {
3568
+ const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
3569
+ throw new AuthError('RESEND_DELAY', `Please wait ${waitTime} seconds before requesting a new code`);
3570
+ }
3571
+ }
3572
+ // Send SMS code via backend
3573
+ const response = await fetch(this.config.sendCodeUrl, {
3574
+ method: 'POST',
3575
+ headers: {
3576
+ 'Content-Type': 'application/json',
3577
+ },
3578
+ body: JSON.stringify({
3579
+ phoneNumber: formattedPhone,
3580
+ clientId: this.config.clientId,
3581
+ codeLength: this.config.codeLength,
3582
+ }),
3583
+ });
3584
+ if (!response.ok) {
3585
+ const error = await response.json().catch(() => ({}));
3586
+ throw new AuthError('SEND_CODE_FAILED', error.message || 'Failed to send SMS code');
3587
+ }
3588
+ const data = await response.json();
3589
+ // Store pending verification
3590
+ this.pendingVerifications.set(formattedPhone, {
3591
+ phoneNumber: formattedPhone,
3592
+ sessionId: data.sessionId,
3593
+ expires: Date.now() + 10 * 60 * 1000, // 10 minutes
3594
+ attempts: 0,
3595
+ lastResent: Date.now(),
3596
+ });
3597
+ // Return partial auth result for pending state
3598
+ // SMS requires two-step process, so we return a temporary user
3599
+ const tempUser = {
3600
+ uid: `sms-pending:${data.sessionId}`,
3601
+ email: null,
3602
+ displayName: this.maskPhoneNumber(formattedPhone),
3603
+ photoURL: null,
3604
+ phoneNumber: formattedPhone,
3605
+ emailVerified: false,
3606
+ providerData: [],
3607
+ metadata: {
3608
+ creationTime: new Date().toISOString(),
3609
+ lastSignInTime: new Date().toISOString(),
3610
+ },
3611
+ };
3612
+ return {
3613
+ user: tempUser,
3614
+ credential: {
3615
+ providerId: this.name,
3616
+ signInMethod: 'sms',
3617
+ accessToken: data.sessionId,
3618
+ },
3619
+ additionalUserInfo: {
3620
+ isNewUser: false,
3621
+ providerId: this.name,
3622
+ profile: {
3623
+ phoneNumber: formattedPhone,
3624
+ sessionId: data.sessionId,
3625
+ message: `SMS code sent to ${this.maskPhoneNumber(formattedPhone)}`,
3626
+ pending: true,
3627
+ },
3628
+ },
3629
+ };
3630
+ }
3631
+ catch (error) {
3632
+ if (error instanceof AuthError)
3633
+ throw error;
3634
+ throw new AuthError('SMS_ERROR', error.message || 'Failed to send SMS code');
3635
+ }
3636
+ }
3637
+ async verifyCode(phoneNumber, code) {
3638
+ const formattedPhone = this.formatPhoneNumber(phoneNumber);
3639
+ const pending = this.pendingVerifications.get(formattedPhone);
3640
+ if (!pending) {
3641
+ throw new AuthError('NO_PENDING_VERIFICATION', 'No pending SMS verification found');
3642
+ }
3643
+ if (Date.now() > pending.expires) {
3644
+ this.pendingVerifications.delete(formattedPhone);
3645
+ throw new AuthError('CODE_EXPIRED', 'SMS code has expired');
3646
+ }
3647
+ if (pending.attempts >= this.MAX_ATTEMPTS) {
3648
+ this.pendingVerifications.delete(formattedPhone);
3649
+ throw new AuthError('TOO_MANY_ATTEMPTS', 'Too many failed attempts');
3650
+ }
3651
+ try {
3652
+ // Increment attempts
3653
+ pending.attempts++;
3654
+ // Verify code with backend
3655
+ const response = await fetch(this.config.verifyCodeUrl, {
3656
+ method: 'POST',
3657
+ headers: {
3658
+ 'Content-Type': 'application/json',
3659
+ },
3660
+ body: JSON.stringify({
3661
+ phoneNumber: formattedPhone,
3662
+ code,
3663
+ sessionId: pending.sessionId,
3664
+ clientId: this.config.clientId,
3665
+ }),
3666
+ });
3667
+ if (!response.ok) {
3668
+ const error = await response.json().catch(() => ({}));
3669
+ if (response.status === 401) {
3670
+ throw new AuthError('INVALID_CODE', 'Invalid SMS code');
3671
+ }
3672
+ throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to verify SMS code');
3673
+ }
3674
+ const data = await response.json();
3675
+ // Create user from verified data
3676
+ const user = {
3677
+ uid: data.uid || this.generateUid(formattedPhone),
3678
+ email: data.email || null,
3679
+ displayName: data.displayName || formattedPhone,
3680
+ photoURL: data.photoURL || null,
3681
+ phoneNumber: formattedPhone,
3682
+ emailVerified: false,
3683
+ providerData: [
3684
+ {
3685
+ providerId: this.name,
3686
+ uid: data.uid || phoneNumber,
3687
+ displayName: phoneNumber,
3688
+ email: null,
3689
+ phoneNumber: phoneNumber,
3690
+ photoURL: null,
3691
+ },
3692
+ ],
3693
+ metadata: {
3694
+ creationTime: data.createdAt || new Date().toISOString(),
3695
+ lastSignInTime: new Date().toISOString(),
3696
+ },
3697
+ };
3698
+ // Clean up pending verification
3699
+ this.pendingVerifications.delete(formattedPhone);
3700
+ return {
3701
+ user,
3702
+ credential: {
3703
+ providerId: this.name,
3704
+ signInMethod: 'sms',
3705
+ accessToken: data.accessToken,
3706
+ refreshToken: data.refreshToken,
3707
+ expiresAt: data.expiresAt,
3708
+ },
3709
+ additionalUserInfo: {
3710
+ isNewUser: data.isNewUser || false,
3711
+ providerId: this.name,
3712
+ },
3713
+ };
3714
+ }
3715
+ catch (error) {
3716
+ if (error instanceof AuthError)
3717
+ throw error;
3718
+ throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to verify SMS code');
3719
+ }
3720
+ }
3721
+ async signOut() {
3722
+ // Clear any pending verifications
3723
+ this.pendingVerifications.clear();
3724
+ }
3725
+ async getCurrentUser() {
3726
+ // SMS auth doesn't persist sessions by default
3727
+ return null;
3728
+ }
3729
+ async refreshToken(_options) {
3730
+ // Token refresh would be implemented based on backend requirements
3731
+ throw new AuthError('NOT_IMPLEMENTED', 'Token refresh is not yet implemented for SMS authentication');
3732
+ }
3733
+ formatPhoneNumber(phoneNumber) {
3734
+ // Remove all non-numeric characters
3735
+ let cleaned = phoneNumber.replace(/\D/g, '');
3736
+ // Add country code if not present
3737
+ if (!phoneNumber.startsWith('+')) {
3738
+ if (cleaned.length === 10) {
3739
+ // Assume US number without country code
3740
+ cleaned = '1' + cleaned;
3741
+ }
3742
+ cleaned = this.config.countryCode.replace('+', '') + cleaned;
3743
+ }
3744
+ return '+' + cleaned;
3745
+ }
3746
+ maskPhoneNumber(phoneNumber) {
3747
+ // Show only last 4 digits
3748
+ const digits = phoneNumber.replace(/\D/g, '');
3749
+ const lastFour = digits.slice(-4);
3750
+ return `***-***-${lastFour}`;
3751
+ }
3752
+ generateUid(phoneNumber) {
3753
+ return `sms:${phoneNumber.replace(/\D/g, '')}`;
3754
+ }
3755
+ // Public method to resend code
3756
+ async resendCode(phoneNumber) {
3757
+ return this.sendCode(phoneNumber);
3758
+ }
3759
+ // Public method to check if can resend
3760
+ canResendCode(phoneNumber) {
3761
+ const formattedPhone = this.formatPhoneNumber(phoneNumber);
3762
+ const pending = this.pendingVerifications.get(formattedPhone);
3763
+ if (!pending || !pending.lastResent) {
3764
+ return { canResend: true };
3765
+ }
3766
+ const timeSinceLastResend = Date.now() - pending.lastResent;
3767
+ if (timeSinceLastResend < this.config.resendDelay) {
3768
+ return {
3769
+ canResend: false,
3770
+ waitTime: Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000),
3771
+ };
3772
+ }
3773
+ return { canResend: true };
3774
+ }
3775
+ async initialize() {
3776
+ // SMS provider doesn't require initialization
3777
+ }
3778
+ async isSupported() {
3779
+ // SMS auth is supported if we have the required config
3780
+ return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
3781
+ }
3782
+ async linkAccount(_options) {
3783
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for SMS authentication');
3784
+ }
3785
+ async unlinkAccount(_options) {
3786
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for SMS authentication');
3787
+ }
3788
+ async revokeAccess(_token) {
3789
+ // SMS auth doesn't have persistent access to revoke
3790
+ this.pendingVerifications.clear();
3791
+ }
3792
+ }
3793
+
3794
+ var smsProvider = /*#__PURE__*/Object.freeze({
3795
+ __proto__: null,
3796
+ SMSProvider: SMSProvider
3797
+ });
3798
+
3799
+ class EmailPasswordProvider {
3800
+ constructor(config) {
3801
+ this.name = 'email-password';
3802
+ this.currentUser = null;
3803
+ this.authToken = null;
3804
+ this.refreshTokenValue = null;
3805
+ // Initialize with config
3806
+ this.config = Object.assign({ allowSignUp: true, passwordRequirements: {
3807
+ minLength: 8,
3808
+ requireUppercase: true,
3809
+ requireLowercase: true,
3810
+ requireNumbers: true,
3811
+ requireSpecialChars: false,
3812
+ } }, config);
3813
+ }
3814
+ async signIn(options) {
3815
+ if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3816
+ throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
3817
+ }
3818
+ try {
3819
+ const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
3820
+ method: 'POST',
3821
+ headers: {
3822
+ 'Content-Type': 'application/json',
3823
+ },
3824
+ body: JSON.stringify({
3825
+ email: options.email,
3826
+ password: options.password,
3827
+ clientId: this.config.clientId,
3828
+ }),
3829
+ });
3830
+ if (!response.ok) {
3831
+ const error = await response.json().catch(() => ({}));
3832
+ if (response.status === 401) {
3833
+ throw new AuthError('INVALID_CREDENTIALS', 'Invalid email or password');
3834
+ }
3835
+ throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
3836
+ }
3837
+ const data = await response.json();
3838
+ // Create user object
3839
+ const user = {
3840
+ uid: data.uid,
3841
+ email: data.email,
3842
+ displayName: data.displayName || data.email.split('@')[0],
3843
+ photoURL: data.photoURL || null,
3844
+ emailVerified: data.emailVerified || false,
3845
+ providerData: [
3846
+ {
3847
+ providerId: this.name,
3848
+ uid: data.uid,
3849
+ displayName: data.displayName || data.email.split('@')[0],
3850
+ email: data.email,
3851
+ phoneNumber: null,
3852
+ photoURL: data.photoURL || null,
3853
+ },
3854
+ ],
3855
+ metadata: {
3856
+ creationTime: data.createdAt || new Date().toISOString(),
3857
+ lastSignInTime: new Date().toISOString(),
3858
+ },
3859
+ };
3860
+ // Store auth state
3861
+ this.currentUser = user;
3862
+ this.authToken = data.accessToken;
3863
+ this.refreshTokenValue = data.refreshToken;
3864
+ return {
3865
+ user,
3866
+ credential: {
3867
+ providerId: this.name,
3868
+ signInMethod: 'password',
3869
+ accessToken: data.accessToken,
3870
+ refreshToken: data.refreshToken,
3871
+ expiresAt: data.expiresAt,
3872
+ },
3873
+ additionalUserInfo: {
3874
+ isNewUser: false,
3875
+ providerId: this.name,
3876
+ },
3877
+ };
3878
+ }
3879
+ catch (error) {
3880
+ if (error instanceof AuthError)
3881
+ throw error;
3882
+ throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with email and password');
3883
+ }
3884
+ }
3885
+ async signUp(options) {
3886
+ if (!this.config.allowSignUp) {
3887
+ throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
3888
+ }
3889
+ if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
3890
+ throw new AuthError('CREDENTIALS_REQUIRED', 'Email and password are required');
3891
+ }
3892
+ // Validate email
3893
+ if (!this.isValidEmail(options.email)) {
3894
+ throw new AuthError('INVALID_EMAIL', 'Invalid email address');
3895
+ }
3896
+ // Validate password
3897
+ const passwordError = this.validatePassword(options.password);
3898
+ if (passwordError) {
3899
+ throw new AuthError('WEAK_PASSWORD', passwordError);
3900
+ }
3901
+ try {
3902
+ const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
3903
+ method: 'POST',
3904
+ headers: {
3905
+ 'Content-Type': 'application/json',
3906
+ },
3907
+ body: JSON.stringify({
3908
+ email: options.email,
3909
+ password: options.password,
3910
+ displayName: options.displayName,
3911
+ photoURL: options.photoURL,
3912
+ clientId: this.config.clientId,
3913
+ }),
3914
+ });
3915
+ if (!response.ok) {
3916
+ const error = await response.json().catch(() => ({}));
3917
+ if (response.status === 409) {
3918
+ throw new AuthError('EMAIL_EXISTS', 'Email already in use');
3919
+ }
3920
+ throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
3921
+ }
3922
+ const data = await response.json();
3923
+ // Create user object
3924
+ const user = {
3925
+ uid: data.uid,
3926
+ email: data.email,
3927
+ displayName: options.displayName || data.email.split('@')[0],
3928
+ photoURL: options.photoURL || null,
3929
+ emailVerified: false,
3930
+ providerData: [
3931
+ {
3932
+ providerId: this.name,
3933
+ uid: data.uid,
3934
+ displayName: data.displayName || data.email.split('@')[0],
3935
+ email: data.email,
3936
+ phoneNumber: null,
3937
+ photoURL: data.photoURL || null,
3938
+ },
3939
+ ],
3940
+ metadata: {
3941
+ creationTime: new Date().toISOString(),
3942
+ lastSignInTime: new Date().toISOString(),
3943
+ },
3944
+ };
3945
+ // Store auth state
3946
+ this.currentUser = user;
3947
+ this.authToken = data.accessToken;
3948
+ this.refreshTokenValue = data.refreshToken;
3949
+ return {
3950
+ user,
3951
+ credential: {
3952
+ providerId: this.name,
3953
+ signInMethod: 'password',
3954
+ accessToken: data.accessToken,
3955
+ refreshToken: data.refreshToken,
3956
+ expiresAt: data.expiresAt,
3957
+ },
3958
+ additionalUserInfo: {
3959
+ isNewUser: true,
3960
+ providerId: this.name,
3961
+ },
3962
+ };
3963
+ }
3964
+ catch (error) {
3965
+ if (error instanceof AuthError)
3966
+ throw error;
3967
+ throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
3968
+ }
3969
+ }
3970
+ async signOut() {
3971
+ if (this.authToken) {
3972
+ try {
3973
+ await fetch(`${this.config.apiUrl}/auth/signout`, {
3974
+ method: 'POST',
3975
+ headers: {
3976
+ Authorization: `Bearer ${this.authToken}`,
3977
+ 'Content-Type': 'application/json',
3978
+ },
3979
+ body: JSON.stringify({
3980
+ clientId: this.config.clientId,
3981
+ }),
3982
+ });
3983
+ }
3984
+ catch (_a) {
3985
+ // Ignore signout errors
3986
+ }
3987
+ }
3988
+ this.currentUser = null;
3989
+ this.authToken = null;
3990
+ this.refreshTokenValue = null;
3991
+ }
3992
+ async getCurrentUser() {
3993
+ return this.currentUser;
3994
+ }
3995
+ async refreshToken(_options) {
3996
+ if (!this.refreshTokenValue) {
3997
+ throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
3998
+ }
3999
+ try {
4000
+ const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
4001
+ method: 'POST',
4002
+ headers: {
4003
+ 'Content-Type': 'application/json',
4004
+ },
4005
+ body: JSON.stringify({
4006
+ refreshToken: this.refreshTokenValue,
4007
+ clientId: this.config.clientId,
4008
+ }),
4009
+ });
4010
+ if (!response.ok) {
4011
+ throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
4012
+ }
4013
+ const data = await response.json();
4014
+ // Update tokens
4015
+ this.authToken = data.accessToken;
4016
+ if (data.refreshToken) {
4017
+ this.refreshTokenValue = data.refreshToken;
4018
+ }
4019
+ return {
4020
+ user: this.currentUser,
4021
+ credential: {
4022
+ providerId: this.name,
4023
+ signInMethod: 'password',
4024
+ accessToken: data.accessToken,
4025
+ refreshToken: data.refreshToken,
4026
+ expiresAt: data.expiresAt,
4027
+ },
4028
+ };
4029
+ }
4030
+ catch (error) {
4031
+ if (error instanceof AuthError)
4032
+ throw error;
4033
+ throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
4034
+ }
4035
+ }
4036
+ async updatePassword(currentPassword, newPassword) {
4037
+ if (!this.currentUser || !this.authToken) {
4038
+ throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
4039
+ }
4040
+ // Validate new password
4041
+ const passwordError = this.validatePassword(newPassword);
4042
+ if (passwordError) {
4043
+ throw new AuthError('WEAK_PASSWORD', passwordError);
4044
+ }
4045
+ try {
4046
+ const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
4047
+ method: 'POST',
4048
+ headers: {
4049
+ Authorization: `Bearer ${this.authToken}`,
4050
+ 'Content-Type': 'application/json',
4051
+ },
4052
+ body: JSON.stringify({
4053
+ currentPassword,
4054
+ newPassword,
4055
+ clientId: this.config.clientId,
4056
+ }),
4057
+ });
4058
+ if (!response.ok) {
4059
+ const error = await response.json().catch(() => ({}));
4060
+ if (response.status === 401) {
4061
+ throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
4062
+ }
4063
+ throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
4064
+ }
4065
+ }
4066
+ catch (error) {
4067
+ if (error instanceof AuthError)
4068
+ throw error;
4069
+ throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
4070
+ }
4071
+ }
4072
+ async sendPasswordResetEmail(email) {
4073
+ if (!this.isValidEmail(email)) {
4074
+ throw new AuthError('INVALID_EMAIL', 'Invalid email address');
4075
+ }
4076
+ try {
4077
+ const response = await fetch(`${this.config.apiUrl}/auth/reset-password`, {
4078
+ method: 'POST',
4079
+ headers: {
4080
+ 'Content-Type': 'application/json',
4081
+ },
4082
+ body: JSON.stringify({
4083
+ email,
4084
+ clientId: this.config.clientId,
4085
+ }),
4086
+ });
4087
+ if (!response.ok) {
4088
+ const error = await response.json().catch(() => ({}));
4089
+ throw new AuthError('RESET_FAILED', error.message || 'Failed to send reset email');
4090
+ }
4091
+ }
4092
+ catch (error) {
4093
+ if (error instanceof AuthError)
4094
+ throw error;
4095
+ throw new AuthError('RESET_ERROR', error.message || 'Failed to send password reset email');
4096
+ }
4097
+ }
4098
+ async sendEmailVerification() {
4099
+ if (!this.currentUser || !this.authToken) {
4100
+ throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
4101
+ }
4102
+ if (this.currentUser.emailVerified) {
4103
+ throw new AuthError('ALREADY_VERIFIED', 'Email already verified');
4104
+ }
4105
+ try {
4106
+ const response = await fetch(`${this.config.apiUrl}/auth/verify-email`, {
4107
+ method: 'POST',
4108
+ headers: {
4109
+ Authorization: `Bearer ${this.authToken}`,
4110
+ 'Content-Type': 'application/json',
4111
+ },
4112
+ body: JSON.stringify({
4113
+ clientId: this.config.clientId,
4114
+ }),
4115
+ });
4116
+ if (!response.ok) {
4117
+ const error = await response.json().catch(() => ({}));
4118
+ throw new AuthError('VERIFICATION_FAILED', error.message || 'Failed to send verification email');
4119
+ }
4120
+ }
4121
+ catch (error) {
4122
+ if (error instanceof AuthError)
4123
+ throw error;
4124
+ throw new AuthError('VERIFICATION_ERROR', error.message || 'Failed to send verification email');
4125
+ }
4126
+ }
4127
+ isValidEmail(email) {
4128
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4129
+ return emailRegex.test(email);
4130
+ }
4131
+ validatePassword(password) {
4132
+ const requirements = this.config.passwordRequirements;
4133
+ if (password.length < requirements.minLength) {
4134
+ return `Password must be at least ${requirements.minLength} characters long`;
4135
+ }
4136
+ if (requirements.requireUppercase && !/[A-Z]/.test(password)) {
4137
+ return 'Password must contain at least one uppercase letter';
4138
+ }
4139
+ if (requirements.requireLowercase && !/[a-z]/.test(password)) {
4140
+ return 'Password must contain at least one lowercase letter';
4141
+ }
4142
+ if (requirements.requireNumbers && !/\d/.test(password)) {
4143
+ return 'Password must contain at least one number';
4144
+ }
4145
+ if (requirements.requireSpecialChars &&
4146
+ !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
4147
+ return 'Password must contain at least one special character';
4148
+ }
4149
+ return null;
4150
+ }
4151
+ async initialize() {
4152
+ // Email/Password provider doesn't require initialization
4153
+ }
4154
+ async isSupported() {
4155
+ // Email/Password auth is supported if we have the required config
4156
+ return !!this.config.apiUrl;
4157
+ }
4158
+ async linkAccount(_options) {
4159
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for email/password authentication');
4160
+ }
4161
+ async unlinkAccount(_options) {
4162
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for email/password authentication');
4163
+ }
4164
+ async revokeAccess(_token) {
4165
+ // For email/password auth, revoking access means signing out
4166
+ await this.signOut();
4167
+ }
4168
+ }
4169
+
4170
+ var emailPasswordProvider = /*#__PURE__*/Object.freeze({
4171
+ __proto__: null,
4172
+ EmailPasswordProvider: EmailPasswordProvider
4173
+ });
4174
+
4175
+ class BiometricProvider {
4176
+ constructor(config = {}) {
4177
+ this.name = 'biometric';
4178
+ this.biometricAuth = null;
4179
+ this.config = Object.assign({ reason: 'Authenticate to access your account', title: 'Authentication Required', subtitle: 'Access your account securely', fallbackTitle: 'Use Passcode', requireRecentAuth: true, recentAuthTimeout: 5 * 60 * 1000 }, config);
4180
+ this.storageKey =
4181
+ config.storageKey || 'capacitor-auth-biometric-credentials';
4182
+ // Try to load biometric plugin
4183
+ this.loadBiometricPlugin();
4184
+ }
4185
+ async loadBiometricPlugin() {
4186
+ try {
4187
+ // Dynamic import to avoid errors if plugin not installed
4188
+ const { BiometricAuth } = await import('capacitor-biometric-authentication');
4189
+ this.biometricAuth = BiometricAuth;
4190
+ }
4191
+ catch (_a) {
4192
+ console.warn('Biometric authentication plugin not available');
4193
+ }
4194
+ }
4195
+ async signIn(_options) {
4196
+ var _a, _b, _c;
4197
+ if (!this.biometricAuth) {
4198
+ throw new AuthError('BIOMETRIC_NOT_AVAILABLE', 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
4199
+ }
4200
+ try {
4201
+ // Check if biometry is available
4202
+ const checkResult = await this.biometricAuth.checkBiometry();
4203
+ if (!checkResult.isAvailable) {
4204
+ throw new AuthError('BIOMETRIC_NOT_AVAILABLE', checkResult.reason ||
4205
+ 'Biometric authentication is not available on this device');
4206
+ }
4207
+ // Check if we have stored credentials
4208
+ const storedCredentials = await this.getStoredCredentials();
4209
+ if (!storedCredentials) {
4210
+ throw new AuthError('NO_STORED_CREDENTIALS', 'No stored credentials found. Please sign in with another method first.');
4211
+ }
4212
+ // Check if recent auth is required
4213
+ if (this.config.requireRecentAuth) {
4214
+ const timeSinceLastAuth = Date.now() - storedCredentials.lastAuthTime;
4215
+ if (timeSinceLastAuth > this.config.recentAuthTimeout) {
4216
+ throw new AuthError('AUTH_EXPIRED', 'Authentication expired. Please sign in with another method.');
4217
+ }
4218
+ }
4219
+ // Perform biometric authentication
4220
+ await this.biometricAuth.authenticate({
4221
+ reason: this.config.reason,
4222
+ title: this.config.title,
4223
+ subtitle: this.config.subtitle,
4224
+ fallbackTitle: this.config.fallbackTitle,
4225
+ });
4226
+ // Update last auth time
4227
+ storedCredentials.lastAuthTime = Date.now();
4228
+ await this.storeCredentials(storedCredentials);
4229
+ // Return stored user data
4230
+ return {
4231
+ user: storedCredentials.user,
4232
+ credential: {
4233
+ providerId: this.name,
4234
+ signInMethod: 'biometric',
4235
+ accessToken: storedCredentials.accessToken,
4236
+ refreshToken: storedCredentials.refreshToken,
4237
+ },
4238
+ additionalUserInfo: {
4239
+ isNewUser: false,
4240
+ providerId: this.name,
4241
+ profile: {
4242
+ biometryType: checkResult.biometryType,
4243
+ },
4244
+ },
4245
+ };
4246
+ }
4247
+ catch (error) {
4248
+ if (error instanceof AuthError)
4249
+ throw error;
4250
+ // Handle biometric errors
4251
+ if (error.code === 'userCancel' || ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('cancel'))) {
4252
+ throw new AuthError('USER_CANCELLED', 'Authentication cancelled by user');
4253
+ }
4254
+ else if (error.code === 'biometryLockout' ||
4255
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('lockout'))) {
4256
+ throw new AuthError('BIOMETRY_LOCKOUT', 'Too many failed attempts. Biometry is locked.');
4257
+ }
4258
+ else if (error.code === 'biometryNotEnrolled' ||
4259
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('enrolled'))) {
4260
+ throw new AuthError('NOT_ENROLLED', 'No biometric credentials are enrolled');
4261
+ }
4262
+ throw new AuthError('BIOMETRIC_ERROR', error.message || 'Biometric authentication failed');
4263
+ }
4264
+ }
4265
+ async signOut() {
4266
+ // Clear stored credentials
4267
+ await this.clearStoredCredentials();
4268
+ }
4269
+ async getCurrentUser() {
4270
+ const stored = await this.getStoredCredentials();
4271
+ return (stored === null || stored === void 0 ? void 0 : stored.user) || null;
4272
+ }
4273
+ async refreshToken() {
4274
+ // Re-authenticate with biometrics
4275
+ return this.signIn();
4276
+ }
4277
+ // Store credentials for biometric access
4278
+ async storeUserCredentials(user, credential) {
4279
+ const credentials = {
4280
+ user,
4281
+ accessToken: credential === null || credential === void 0 ? void 0 : credential.accessToken,
4282
+ refreshToken: credential === null || credential === void 0 ? void 0 : credential.refreshToken,
4283
+ lastAuthTime: Date.now(),
4284
+ };
4285
+ await this.storeCredentials(credentials);
4286
+ }
4287
+ // Check if biometric authentication is available
4288
+ async isAvailable() {
4289
+ if (!this.biometricAuth) {
4290
+ await this.loadBiometricPlugin();
4291
+ if (!this.biometricAuth) {
4292
+ return {
4293
+ available: false,
4294
+ reason: 'Biometric authentication plugin not installed',
4295
+ };
4296
+ }
4297
+ }
4298
+ try {
4299
+ const result = await this.biometricAuth.checkBiometry();
4300
+ return {
4301
+ available: result.isAvailable,
4302
+ biometryType: result.biometryType,
4303
+ reason: result.reason,
4304
+ };
4305
+ }
4306
+ catch (_a) {
4307
+ return {
4308
+ available: false,
4309
+ reason: 'Failed to check biometry availability',
4310
+ };
4311
+ }
4312
+ }
4313
+ // Check if credentials are stored
4314
+ async hasStoredCredentials() {
4315
+ const stored = await this.getStoredCredentials();
4316
+ if (!stored)
4317
+ return false;
4318
+ // Check if auth is still valid
4319
+ if (this.config.requireRecentAuth) {
4320
+ const timeSinceLastAuth = Date.now() - stored.lastAuthTime;
4321
+ return timeSinceLastAuth <= this.config.recentAuthTimeout;
4322
+ }
4323
+ return true;
4324
+ }
4325
+ async getStoredCredentials() {
4326
+ try {
4327
+ const stored = localStorage.getItem(this.storageKey);
4328
+ if (!stored)
4329
+ return null;
4330
+ const decrypted = await this.decrypt(stored);
4331
+ return JSON.parse(decrypted);
4332
+ }
4333
+ catch (_a) {
4334
+ return null;
4335
+ }
4336
+ }
4337
+ async storeCredentials(credentials) {
4338
+ try {
4339
+ const encrypted = await this.encrypt(JSON.stringify(credentials));
4340
+ localStorage.setItem(this.storageKey, encrypted);
4341
+ }
4342
+ catch (_a) {
4343
+ throw new AuthError('STORAGE_ERROR', 'Failed to store credentials');
4344
+ }
4345
+ }
4346
+ async clearStoredCredentials() {
4347
+ localStorage.removeItem(this.storageKey);
4348
+ }
4349
+ // Simple encryption/decryption (in production, use proper encryption)
4350
+ async encrypt(data) {
4351
+ // In a real implementation, use Web Crypto API or similar
4352
+ return btoa(data);
4353
+ }
4354
+ async decrypt(data) {
4355
+ // In a real implementation, use Web Crypto API or similar
4356
+ return atob(data);
4357
+ }
4358
+ async initialize() {
4359
+ // Biometric provider is initialized in constructor
4360
+ // Provider is initialized
4361
+ }
4362
+ async isSupported() {
4363
+ // Check if biometric authentication is available
4364
+ const result = await this.isAvailable();
4365
+ return result.available;
4366
+ }
4367
+ async linkAccount(_options) {
4368
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for biometric authentication');
4369
+ }
4370
+ async unlinkAccount(_options) {
4371
+ // Unlinking biometric auth means clearing stored credentials
4372
+ await this.clearStoredCredentials();
4373
+ }
4374
+ async revokeAccess(_token) {
4375
+ // For biometric auth, revoking access means clearing stored credentials
4376
+ await this.clearStoredCredentials();
4377
+ }
4378
+ }
4379
+
4380
+ var biometricProvider = /*#__PURE__*/Object.freeze({
4381
+ __proto__: null,
4382
+ BiometricProvider: BiometricProvider
4383
+ });
4384
+
4385
+ class SlackProvider extends OAuthProvider {
4386
+ constructor(config) {
4387
+ super(config);
4388
+ this.provider = exports.AuthProvider.SLACK;
4389
+ this.clientId = '';
4390
+ this.redirectUri = '';
4391
+ this.scopes = [];
4392
+ this.authWindow = null;
4393
+ const options = config.options;
4394
+ this.clientId = options.clientId || '';
4395
+ this.redirectUri = options.redirectUri || '';
4396
+ this.scopes = options.scopes || ['openid', 'profile', 'email'];
4397
+ this.teamId = options.teamId;
4398
+ }
4399
+ async initialize() {
4400
+ this.isInitialized = true;
4401
+ }
4402
+ async signIn(options) {
4403
+ return this.performOAuthFlow(options);
4404
+ }
4405
+ async refreshToken(_options) {
4406
+ throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for Slack provider');
4407
+ }
4408
+ getOAuthConfig() {
4409
+ return {
4410
+ clientId: this.clientId,
4411
+ redirectUri: this.redirectUri,
4412
+ authorizationEndpoint: 'https://slack.com/oauth/v2/authorize',
4413
+ tokenEndpoint: 'https://slack.com/api/oauth.v2.access',
4414
+ scopes: this.scopes,
4415
+ additionalParams: this.teamId ? { team: this.teamId } : {},
4416
+ };
4417
+ }
4418
+ async parseUserFromTokenResponse(_response) {
4419
+ // In a real implementation, you would parse the user info from the token response
4420
+ // or make an additional API call to get user details
4421
+ return {
4422
+ id: 'U1234567890',
4423
+ email: 'user@workspace.slack.com',
4424
+ name: 'Slack User',
4425
+ picture: 'https://ui-avatars.com/api/?name=Slack+User',
4426
+ email_verified: true,
4427
+ isNewUser: false,
4428
+ };
4429
+ }
4430
+ async openAuthorizationUrl(url) {
4431
+ return new Promise((resolve, reject) => {
4432
+ // Open OAuth window
4433
+ this.authWindow = window.open(url, 'SlackAuth', 'width=500,height=600');
4434
+ if (!this.authWindow) {
4435
+ reject(new Error('Failed to open authentication window'));
4436
+ return;
4437
+ }
4438
+ // Listen for OAuth callback
4439
+ const checkInterval = setInterval(() => {
4440
+ var _a, _b;
4441
+ try {
4442
+ if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
4443
+ clearInterval(checkInterval);
4444
+ reject(new Error('Authentication cancelled'));
4445
+ return;
4446
+ }
4447
+ if ((_b = this.authWindow) === null || _b === void 0 ? void 0 : _b.location.href.startsWith(this.redirectUri)) {
4448
+ clearInterval(checkInterval);
4449
+ const url = new URL(this.authWindow.location.href);
4450
+ const code = url.searchParams.get('code');
4451
+ const state = url.searchParams.get('state');
4452
+ const error = url.searchParams.get('error');
4453
+ this.authWindow.close();
4454
+ this.authWindow = null;
4455
+ resolve({
4456
+ code: code || undefined,
4457
+ state: state || undefined,
4458
+ error: error || undefined,
4459
+ });
4460
+ }
4461
+ }
4462
+ catch (_c) {
4463
+ // Cross-origin error, ignore
4464
+ }
4465
+ }, 1000);
4466
+ });
4467
+ }
4468
+ async isSupported() {
4469
+ return true;
4470
+ }
4471
+ async linkAccount(_options) {
4472
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for Slack provider');
4473
+ }
4474
+ async unlinkAccount(_options) {
4475
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for Slack provider');
4476
+ }
4477
+ async revokeAccess(token) {
4478
+ await super.revokeAccess(token);
4479
+ }
4480
+ async signOut(_options) {
4481
+ await this.clearStoredData();
4482
+ await this.setCurrentUser(null);
4483
+ }
4484
+ }
4485
+
4486
+ var slackProvider = /*#__PURE__*/Object.freeze({
4487
+ __proto__: null,
4488
+ SlackProvider: SlackProvider
4489
+ });
4490
+
4491
+ class LinkedInProvider extends OAuthProvider {
4492
+ constructor(config) {
4493
+ super(config);
4494
+ this.provider = exports.AuthProvider.LINKEDIN;
4495
+ this.clientId = '';
4496
+ this.redirectUri = '';
4497
+ this.scopes = [];
4498
+ this.authWindow = null;
4499
+ const options = config.options;
4500
+ this.clientId = options.clientId || '';
4501
+ this.redirectUri = options.redirectUri || '';
4502
+ this.scopes = options.scopes || ['openid', 'profile', 'email'];
4503
+ }
4504
+ async initialize() {
4505
+ this.isInitialized = true;
4506
+ }
4507
+ async signIn(options) {
4508
+ return this.performOAuthFlow(options);
4509
+ }
4510
+ async signOut(_options) {
4511
+ await this.clearStoredData();
4512
+ await this.setCurrentUser(null);
4513
+ }
4514
+ async refreshToken(_options) {
4515
+ throw new AuthError('NOT_IMPLEMENTED', 'Token refresh not implemented for LinkedIn provider');
4516
+ }
4517
+ getOAuthConfig() {
4518
+ return {
4519
+ clientId: this.clientId,
4520
+ redirectUri: this.redirectUri,
4521
+ authorizationEndpoint: 'https://www.linkedin.com/oauth/v2/authorization',
4522
+ tokenEndpoint: 'https://www.linkedin.com/oauth/v2/accessToken',
4523
+ scopes: this.scopes,
4524
+ };
4525
+ }
4526
+ async parseUserFromTokenResponse(_response) {
4527
+ // In a real implementation, you would parse the user info from the token response
4528
+ // or make an additional API call to get user details
4529
+ return {
4530
+ id: 'linkedin_user_123',
4531
+ email: 'user@linkedin.com',
4532
+ name: 'LinkedIn User',
4533
+ picture: 'https://ui-avatars.com/api/?name=LinkedIn+User',
4534
+ email_verified: true,
4535
+ isNewUser: false,
4536
+ };
4537
+ }
4538
+ async openAuthorizationUrl(url) {
4539
+ return new Promise((resolve, reject) => {
4540
+ // Open OAuth window
4541
+ this.authWindow = window.open(url, 'LinkedInAuth', 'width=500,height=600');
4542
+ if (!this.authWindow) {
4543
+ reject(new Error('Failed to open authentication window'));
4544
+ return;
4545
+ }
4546
+ // Listen for OAuth callback
4547
+ const checkInterval = setInterval(() => {
4548
+ var _a, _b;
4549
+ try {
4550
+ if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
4551
+ clearInterval(checkInterval);
4552
+ reject(new Error('Authentication cancelled'));
4553
+ return;
4554
+ }
4555
+ if ((_b = this.authWindow) === null || _b === void 0 ? void 0 : _b.location.href.startsWith(this.redirectUri)) {
4556
+ clearInterval(checkInterval);
4557
+ const url = new URL(this.authWindow.location.href);
4558
+ const code = url.searchParams.get('code');
4559
+ const state = url.searchParams.get('state');
4560
+ const error = url.searchParams.get('error');
4561
+ const errorDescription = url.searchParams.get('error_description');
4562
+ this.authWindow.close();
4563
+ this.authWindow = null;
4564
+ resolve({
4565
+ code: code || undefined,
4566
+ state: state || undefined,
4567
+ error: error ? `${error} - ${errorDescription}` : undefined,
4568
+ });
4569
+ }
4570
+ }
4571
+ catch (_c) {
4572
+ // Cross-origin error, ignore
4573
+ }
4574
+ }, 1000);
4575
+ });
4576
+ }
4577
+ async isSupported() {
4578
+ return true;
4579
+ }
4580
+ async linkAccount(_options) {
4581
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for LinkedIn provider');
4582
+ }
4583
+ async unlinkAccount(_options) {
4584
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for LinkedIn provider');
4585
+ }
4586
+ async revokeAccess(token) {
4587
+ await super.revokeAccess(token);
4588
+ }
4589
+ }
4590
+
4591
+ var linkedinProvider = /*#__PURE__*/Object.freeze({
4592
+ __proto__: null,
4593
+ LinkedInProvider: LinkedInProvider
4594
+ });
4595
+
4596
+ class UsernamePasswordProvider {
4597
+ constructor(config) {
4598
+ this.name = 'username-password';
4599
+ this.currentUser = null;
4600
+ this.authToken = null;
4601
+ this.refreshTokenValue = null;
4602
+ this.config = Object.assign({ allowSignUp: true, usernameRequirements: Object.assign({ minLength: 3, maxLength: 20, allowedCharacters: /^[a-zA-Z0-9_-]+$/, reservedUsernames: ['admin', 'root', 'system', 'user'] }, config.usernameRequirements), passwordRequirements: Object.assign({ minLength: 8, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSpecialChars: false }, config.passwordRequirements) }, config);
4603
+ }
4604
+ async signIn(options) {
4605
+ if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4606
+ throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
4607
+ }
4608
+ try {
4609
+ const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
4610
+ method: 'POST',
4611
+ headers: {
4612
+ 'Content-Type': 'application/json',
4613
+ },
4614
+ body: JSON.stringify({
4615
+ username: options.username,
4616
+ password: options.password,
4617
+ clientId: this.config.clientId,
4618
+ }),
4619
+ });
4620
+ if (!response.ok) {
4621
+ const error = await response.json().catch(() => ({}));
4622
+ if (response.status === 401) {
4623
+ throw new AuthError('INVALID_CREDENTIALS', 'Invalid username or password');
4624
+ }
4625
+ throw new AuthError('SIGN_IN_FAILED', error.message || 'Failed to sign in');
4626
+ }
4627
+ const data = await response.json();
4628
+ // Create user object
4629
+ const user = {
4630
+ uid: data.uid,
4631
+ email: data.email || null,
4632
+ displayName: data.displayName || options.username,
4633
+ photoURL: data.photoURL || null,
4634
+ emailVerified: data.emailVerified || false,
4635
+ providerData: [
4636
+ {
4637
+ providerId: this.name,
4638
+ uid: data.uid,
4639
+ displayName: data.displayName || options.username,
4640
+ email: data.email || null,
4641
+ phoneNumber: null,
4642
+ photoURL: data.photoURL || null,
4643
+ },
4644
+ ],
4645
+ metadata: {
4646
+ creationTime: data.createdAt || new Date().toISOString(),
4647
+ lastSignInTime: new Date().toISOString(),
4648
+ },
4649
+ };
4650
+ // Store auth state
4651
+ this.currentUser = user;
4652
+ this.authToken = data.accessToken;
4653
+ this.refreshTokenValue = data.refreshToken;
4654
+ return {
4655
+ user,
4656
+ credential: {
4657
+ providerId: this.name,
4658
+ signInMethod: 'password',
4659
+ accessToken: data.accessToken,
4660
+ refreshToken: data.refreshToken,
4661
+ expiresAt: data.expiresAt,
4662
+ },
4663
+ additionalUserInfo: {
4664
+ isNewUser: false,
4665
+ providerId: this.name,
4666
+ username: options.username,
4667
+ },
4668
+ };
4669
+ }
4670
+ catch (error) {
4671
+ if (error instanceof AuthError)
4672
+ throw error;
4673
+ throw new AuthError('SIGN_IN_ERROR', error.message || 'Failed to sign in with username and password');
4674
+ }
4675
+ }
4676
+ async signUp(options) {
4677
+ if (!this.config.allowSignUp) {
4678
+ throw new AuthError('SIGN_UP_DISABLED', 'Sign up is not allowed');
4679
+ }
4680
+ if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
4681
+ throw new AuthError('CREDENTIALS_REQUIRED', 'Username and password are required');
964
4682
  }
965
- this.initPromise = this._initialize();
966
- try {
967
- await this.initPromise;
4683
+ // Validate username
4684
+ const usernameError = this.validateUsername(options.username);
4685
+ if (usernameError) {
4686
+ throw new AuthError('INVALID_USERNAME', usernameError);
968
4687
  }
969
- finally {
970
- this.initPromise = null;
4688
+ // Validate password
4689
+ const passwordError = this.validatePassword(options.password);
4690
+ if (passwordError) {
4691
+ throw new AuthError('WEAK_PASSWORD', passwordError);
4692
+ }
4693
+ // Validate email if provided
4694
+ if (options.email && !this.isValidEmail(options.email)) {
4695
+ throw new AuthError('INVALID_EMAIL', 'Invalid email address');
971
4696
  }
972
- }
973
- async _initialize() {
974
- const options = this.options;
975
4697
  try {
976
- // Load Apple JS SDK
977
- await this.loadAppleSDK();
978
- // Initialize Apple ID auth
979
- window.AppleID.auth.init({
980
- clientId: options.clientId,
981
- scope: this.mapAppleScopes(options.scopes).join(' '),
982
- redirectURI: options.redirectUri,
983
- state: options.state,
984
- nonce: options.nonce,
985
- usePopup: options.usePopup !== false, // Default to true
4698
+ const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
4699
+ method: 'POST',
4700
+ headers: {
4701
+ 'Content-Type': 'application/json',
4702
+ },
4703
+ body: JSON.stringify({
4704
+ username: options.username,
4705
+ password: options.password,
4706
+ email: options.email,
4707
+ displayName: options.displayName,
4708
+ photoURL: options.photoURL,
4709
+ clientId: this.config.clientId,
4710
+ }),
986
4711
  });
987
- // Load previously authenticated user
988
- await this.loadCurrentUser();
989
- this.isInitialized = true;
990
- this.logger.info('Apple Auth provider initialized');
4712
+ if (!response.ok) {
4713
+ const error = await response.json().catch(() => ({}));
4714
+ if (response.status === 409) {
4715
+ throw new AuthError('USERNAME_EXISTS', 'Username already taken');
4716
+ }
4717
+ throw new AuthError('SIGN_UP_FAILED', error.message || 'Failed to create account');
4718
+ }
4719
+ const data = await response.json();
4720
+ // Create user object
4721
+ const user = {
4722
+ uid: data.uid,
4723
+ email: options.email || null,
4724
+ displayName: options.displayName || options.username,
4725
+ photoURL: options.photoURL || null,
4726
+ emailVerified: false,
4727
+ providerData: [
4728
+ {
4729
+ providerId: this.name,
4730
+ uid: data.uid,
4731
+ displayName: options.displayName || options.username,
4732
+ email: options.email || null,
4733
+ phoneNumber: null,
4734
+ photoURL: options.photoURL || null,
4735
+ },
4736
+ ],
4737
+ metadata: {
4738
+ creationTime: new Date().toISOString(),
4739
+ lastSignInTime: new Date().toISOString(),
4740
+ },
4741
+ };
4742
+ // Store auth state
4743
+ this.currentUser = user;
4744
+ this.authToken = data.accessToken;
4745
+ this.refreshTokenValue = data.refreshToken;
4746
+ return {
4747
+ user,
4748
+ credential: {
4749
+ providerId: this.name,
4750
+ signInMethod: 'password',
4751
+ accessToken: data.accessToken,
4752
+ refreshToken: data.refreshToken,
4753
+ expiresAt: data.expiresAt,
4754
+ },
4755
+ additionalUserInfo: {
4756
+ isNewUser: true,
4757
+ providerId: this.name,
4758
+ username: options.username,
4759
+ },
4760
+ };
991
4761
  }
992
4762
  catch (error) {
993
- this.logger.error('Failed to initialize Apple Auth', error);
994
- throw AuthError.fromError(error, this.provider);
4763
+ if (error instanceof AuthError)
4764
+ throw error;
4765
+ throw new AuthError('SIGN_UP_ERROR', error.message || 'Failed to create account');
995
4766
  }
996
4767
  }
997
- async signIn(options) {
998
- var _a, _b, _c;
999
- this.validateInitialized();
4768
+ async signOut() {
4769
+ if (this.authToken) {
4770
+ try {
4771
+ await fetch(`${this.config.apiUrl}/auth/signout`, {
4772
+ method: 'POST',
4773
+ headers: {
4774
+ Authorization: `Bearer ${this.authToken}`,
4775
+ 'Content-Type': 'application/json',
4776
+ },
4777
+ body: JSON.stringify({
4778
+ clientId: this.config.clientId,
4779
+ }),
4780
+ });
4781
+ }
4782
+ catch (_a) {
4783
+ // Ignore signout errors
4784
+ }
4785
+ }
4786
+ this.currentUser = null;
4787
+ this.authToken = null;
4788
+ this.refreshTokenValue = null;
4789
+ }
4790
+ async getCurrentUser() {
4791
+ return this.currentUser;
4792
+ }
4793
+ async refreshToken(_options) {
4794
+ if (!this.refreshTokenValue) {
4795
+ throw new AuthError('NO_REFRESH_TOKEN', 'No refresh token available');
4796
+ }
1000
4797
  try {
1001
- const appleOptions = this.options;
1002
- // Generate state and nonce for security
1003
- const state = ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.state) || this.generateSecureRandomString();
1004
- const nonce = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.nonce) || this.generateSecureRandomString();
1005
- // Store state and nonce for validation
1006
- await this.storage.set(`${this.provider}_oauth_state`, state);
1007
- await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
1008
- // Configure sign-in options
1009
- const signInConfig = {
1010
- clientId: appleOptions.clientId,
1011
- scope: this.mapAppleScopes(((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.scopes) || appleOptions.scopes).join(' '),
1012
- redirectURI: appleOptions.redirectUri,
1013
- state,
1014
- nonce,
1015
- usePopup: appleOptions.usePopup !== false,
4798
+ const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
4799
+ method: 'POST',
4800
+ headers: {
4801
+ 'Content-Type': 'application/json',
4802
+ },
4803
+ body: JSON.stringify({
4804
+ refreshToken: this.refreshTokenValue,
4805
+ clientId: this.config.clientId,
4806
+ }),
4807
+ });
4808
+ if (!response.ok) {
4809
+ throw new AuthError('REFRESH_FAILED', 'Failed to refresh token');
4810
+ }
4811
+ const data = await response.json();
4812
+ // Update tokens
4813
+ this.authToken = data.accessToken;
4814
+ if (data.refreshToken) {
4815
+ this.refreshTokenValue = data.refreshToken;
4816
+ }
4817
+ return {
4818
+ user: this.currentUser,
4819
+ credential: {
4820
+ providerId: this.name,
4821
+ signInMethod: 'password',
4822
+ accessToken: data.accessToken,
4823
+ refreshToken: data.refreshToken,
4824
+ expiresAt: data.expiresAt,
4825
+ },
1016
4826
  };
1017
- // Perform sign in
1018
- const response = await window.AppleID.auth.signIn(signInConfig);
1019
- // Validate response
1020
- await this.validateAppleResponse(response, state, nonce);
1021
- // Parse user information from response
1022
- const user = this.createAppleAuthUser(response);
1023
- const credential = this.createAppleCredential(response);
1024
- // Save user and credential
1025
- await this.setCurrentUser(user);
1026
- await this.saveCredential(credential);
1027
- return this.createAuthResult(user, credential, response.user ? true : false);
1028
4827
  }
1029
4828
  catch (error) {
1030
- this.logger.error('Apple sign in failed', error);
1031
- if (error && typeof error === 'object' && 'error' in error) {
1032
- throw new AuthError(this.mapAppleError(error.error), error.error, this.provider);
1033
- }
1034
- throw AuthError.fromError(error, this.provider);
1035
- }
1036
- finally {
1037
- // Clean up temporary storage
1038
- await this.storage.remove(`${this.provider}_oauth_state`);
1039
- await this.storage.remove(`${this.provider}_oauth_nonce`);
4829
+ if (error instanceof AuthError)
4830
+ throw error;
4831
+ throw new AuthError('REFRESH_ERROR', error.message || 'Failed to refresh token');
1040
4832
  }
1041
4833
  }
1042
- async signOut(_options) {
1043
- this.validateInitialized();
4834
+ async updatePassword(currentPassword, newPassword) {
4835
+ if (!this.currentUser || !this.authToken) {
4836
+ throw new AuthError('NOT_AUTHENTICATED', 'User not authenticated');
4837
+ }
4838
+ // Validate new password
4839
+ const passwordError = this.validatePassword(newPassword);
4840
+ if (passwordError) {
4841
+ throw new AuthError('WEAK_PASSWORD', passwordError);
4842
+ }
1044
4843
  try {
1045
- // Apple doesn't provide a sign-out method in their JS SDK
1046
- // Just clear local data
1047
- await this.clearStoredData();
1048
- await this.setCurrentUser(null);
1049
- this.logger.info('Signed out from Apple');
4844
+ const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
4845
+ method: 'POST',
4846
+ headers: {
4847
+ Authorization: `Bearer ${this.authToken}`,
4848
+ 'Content-Type': 'application/json',
4849
+ },
4850
+ body: JSON.stringify({
4851
+ currentPassword,
4852
+ newPassword,
4853
+ clientId: this.config.clientId,
4854
+ }),
4855
+ });
4856
+ if (!response.ok) {
4857
+ const error = await response.json().catch(() => ({}));
4858
+ if (response.status === 401) {
4859
+ throw new AuthError('INVALID_PASSWORD', 'Current password is incorrect');
4860
+ }
4861
+ throw new AuthError('UPDATE_FAILED', error.message || 'Failed to update password');
4862
+ }
1050
4863
  }
1051
4864
  catch (error) {
1052
- this.logger.error('Failed to sign out from Apple', error);
1053
- throw AuthError.fromError(error, this.provider);
4865
+ if (error instanceof AuthError)
4866
+ throw error;
4867
+ throw new AuthError('UPDATE_ERROR', error.message || 'Failed to update password');
1054
4868
  }
1055
4869
  }
1056
- async isSupported() {
1057
- // Check if we're in a browser environment
1058
- if (typeof window === 'undefined' || typeof document === 'undefined') {
4870
+ async checkUsernameAvailability(username) {
4871
+ // Validate username format first
4872
+ const usernameError = this.validateUsername(username);
4873
+ if (usernameError) {
1059
4874
  return false;
1060
4875
  }
1061
- // Check if we're on HTTPS (required for Apple Sign In)
1062
- if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost') {
4876
+ try {
4877
+ const response = await fetch(`${this.config.apiUrl}/auth/check-username`, {
4878
+ method: 'POST',
4879
+ headers: {
4880
+ 'Content-Type': 'application/json',
4881
+ },
4882
+ body: JSON.stringify({
4883
+ username,
4884
+ clientId: this.config.clientId,
4885
+ }),
4886
+ });
4887
+ if (!response.ok) {
4888
+ return false;
4889
+ }
4890
+ const data = await response.json();
4891
+ return data.available || false;
4892
+ }
4893
+ catch (_a) {
1063
4894
  return false;
1064
4895
  }
1065
- return true;
1066
- }
1067
- async linkAccount(options) {
1068
- // For web, linking is the same as signing in
1069
- return this.signIn(options);
1070
- }
1071
- async unlinkAccount(_options) {
1072
- // For web, unlinking is the same as signing out
1073
- await this.signOut();
1074
- }
1075
- async openAuthorizationUrl(_url) {
1076
- // This method is not used in Apple JS SDK flow
1077
- throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Direct OAuth flow not supported for Apple. Use signIn method instead.', this.provider);
1078
4896
  }
1079
- async parseUserFromTokenResponse(response) {
1080
- // Apple provides user info directly in the authorization response
1081
- return response.user || {};
4897
+ isValidEmail(email) {
4898
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4899
+ return emailRegex.test(email);
1082
4900
  }
1083
- async loadAppleSDK() {
1084
- var _a;
1085
- if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
1086
- return;
4901
+ validateUsername(username) {
4902
+ const requirements = this.config.usernameRequirements;
4903
+ if (username.length < requirements.minLength) {
4904
+ return `Username must be at least ${requirements.minLength} characters long`;
1087
4905
  }
1088
- return new Promise((resolve, reject) => {
1089
- const script = document.createElement('script');
1090
- script.src = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
1091
- script.async = true;
1092
- script.defer = true;
1093
- script.onload = () => {
1094
- var _a;
1095
- if ((_a = window.AppleID) === null || _a === void 0 ? void 0 : _a.auth) {
1096
- resolve();
1097
- }
1098
- else {
1099
- reject(new Error('Apple ID SDK failed to load'));
1100
- }
1101
- };
1102
- script.onerror = () => {
1103
- reject(new Error('Failed to load Apple ID SDK'));
1104
- };
1105
- document.head.appendChild(script);
1106
- });
1107
- }
1108
- mapAppleScopes(scopes) {
1109
- if (!scopes || scopes.length === 0) {
1110
- return [];
4906
+ if (username.length > requirements.maxLength) {
4907
+ return `Username must be no more than ${requirements.maxLength} characters long`;
1111
4908
  }
1112
- return scopes.map(scope => {
1113
- switch (scope) {
1114
- case exports.AppleAuthScope.EMAIL:
1115
- return 'email';
1116
- case exports.AppleAuthScope.NAME:
1117
- return 'name';
1118
- default:
1119
- return scope;
1120
- }
1121
- });
1122
- }
1123
- async validateAppleResponse(response, expectedState, _expectedNonce) {
1124
- if (response.error) {
1125
- throw new AuthError(this.mapAppleError(response.error), response.error, this.provider);
4909
+ if (requirements.allowedCharacters &&
4910
+ !requirements.allowedCharacters.test(username)) {
4911
+ return 'Username contains invalid characters. Only letters, numbers, underscores, and hyphens are allowed';
1126
4912
  }
1127
- if (response.state !== expectedState) {
1128
- throw new AuthError(exports.AuthErrorCode.INVALID_STATE, 'OAuth state mismatch', this.provider);
4913
+ if (requirements.reservedUsernames &&
4914
+ requirements.reservedUsernames.includes(username.toLowerCase())) {
4915
+ return 'This username is reserved and cannot be used';
1129
4916
  }
1130
- // ID token validation with nonce would be done here
1131
- // For production, you should validate the ID token on your backend
4917
+ return null;
1132
4918
  }
1133
- createAppleAuthUser(response) {
1134
- var _a, _b, _c, _d;
1135
- const user = response.user || {};
1136
- const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
1137
- // Parse ID token claims (in production, do this on backend)
1138
- let claims = {};
1139
- if (idToken) {
1140
- try {
1141
- const payload = idToken.split('.')[1];
1142
- claims = JSON.parse(atob(payload));
1143
- }
1144
- catch (error) {
1145
- this.logger.error('Failed to parse ID token', error);
1146
- }
4919
+ validatePassword(password) {
4920
+ const requirements = this.config.passwordRequirements;
4921
+ if (password.length < requirements.minLength) {
4922
+ return `Password must be at least ${requirements.minLength} characters long`;
1147
4923
  }
1148
- return {
1149
- uid: claims.sub || ((_b = response.authorization) === null || _b === void 0 ? void 0 : _b.code) || this.generateUniqueId(),
1150
- email: user.email || claims.email || null,
1151
- emailVerified: claims.email_verified || false,
1152
- displayName: user.name ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim() : null,
1153
- photoURL: null, // Apple doesn't provide profile photos
1154
- phoneNumber: null,
1155
- isAnonymous: false,
1156
- tenantId: null,
1157
- providerData: [{
1158
- providerId: exports.AuthProvider.APPLE,
1159
- uid: claims.sub || ((_c = response.authorization) === null || _c === void 0 ? void 0 : _c.code),
1160
- displayName: user.name ? `${user.name.firstName || ''} ${user.name.lastName || ''}`.trim() : null,
1161
- email: user.email || claims.email || null,
1162
- phoneNumber: null,
1163
- photoURL: null,
1164
- }],
1165
- metadata: {
1166
- creationTime: new Date().toISOString(),
1167
- lastSignInTime: new Date().toISOString(),
1168
- },
1169
- refreshToken: (_d = response.authorization) === null || _d === void 0 ? void 0 : _d.refresh_token,
1170
- };
4924
+ if (requirements.requireUppercase && !/[A-Z]/.test(password)) {
4925
+ return 'Password must contain at least one uppercase letter';
4926
+ }
4927
+ if (requirements.requireLowercase && !/[a-z]/.test(password)) {
4928
+ return 'Password must contain at least one lowercase letter';
4929
+ }
4930
+ if (requirements.requireNumbers && !/\d/.test(password)) {
4931
+ return 'Password must contain at least one number';
4932
+ }
4933
+ if (requirements.requireSpecialChars &&
4934
+ !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
4935
+ return 'Password must contain at least one special character';
4936
+ }
4937
+ return null;
1171
4938
  }
1172
- createAppleCredential(response) {
1173
- var _a, _b, _c, _d, _e;
1174
- return {
1175
- providerId: exports.AuthProvider.APPLE,
1176
- signInMethod: 'oauth',
1177
- accessToken: (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.access_token,
1178
- idToken: (_b = response.authorization) === null || _b === void 0 ? void 0 : _b.id_token,
1179
- refreshToken: (_c = response.authorization) === null || _c === void 0 ? void 0 : _c.refresh_token,
1180
- expiresAt: ((_d = response.authorization) === null || _d === void 0 ? void 0 : _d.expires_in)
1181
- ? this.calculateTokenExpiry(response.authorization.expires_in)
1182
- : undefined,
1183
- tokenType: 'Bearer',
1184
- scope: (_e = response.authorization) === null || _e === void 0 ? void 0 : _e.scope,
1185
- rawNonce: response.nonce,
1186
- };
4939
+ async initialize() {
4940
+ // Username/Password provider doesn't require initialization
1187
4941
  }
1188
- mapAppleError(error) {
1189
- const errorMap = {
1190
- 'user_cancelled_authorize': exports.AuthErrorCode.USER_CANCELLED,
1191
- 'popup_closed_by_user': exports.AuthErrorCode.POPUP_CLOSED_BY_USER,
1192
- 'popup_blocked': exports.AuthErrorCode.POPUP_BLOCKED,
1193
- 'invalid_request': exports.AuthErrorCode.INVALID_REQUEST,
1194
- 'invalid_client': exports.AuthErrorCode.CLIENT_NOT_FOUND,
1195
- 'invalid_scope': exports.AuthErrorCode.INVALID_SCOPE,
1196
- 'unauthorized_client': exports.AuthErrorCode.APP_NOT_AUTHORIZED,
1197
- 'access_denied': exports.AuthErrorCode.ACCESS_DENIED,
1198
- 'unsupported_response_type': exports.AuthErrorCode.UNSUPPORTED_GRANT_TYPE,
1199
- 'server_error': exports.AuthErrorCode.SERVER_ERROR,
1200
- 'temporarily_unavailable': exports.AuthErrorCode.TEMPORARILY_UNAVAILABLE,
1201
- };
1202
- return errorMap[error] || exports.AuthErrorCode.INTERNAL_ERROR;
4942
+ async isSupported() {
4943
+ // Username/Password auth is supported if we have the required config
4944
+ return !!this.config.apiUrl;
4945
+ }
4946
+ async linkAccount(_options) {
4947
+ throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for username/password authentication');
4948
+ }
4949
+ async unlinkAccount(_options) {
4950
+ throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for username/password authentication');
4951
+ }
4952
+ async revokeAccess(_token) {
4953
+ // For username/password auth, revoking access means signing out
4954
+ await this.signOut();
1203
4955
  }
1204
4956
  }
1205
4957
 
4958
+ var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
4959
+ __proto__: null,
4960
+ UsernamePasswordProvider: UsernamePasswordProvider
4961
+ });
4962
+
1206
4963
  class ProviderFactory {
1207
4964
  static async createProvider(config, storage, logger, persistence) {
1208
4965
  const providerConfig = {
@@ -1436,7 +5193,7 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
1436
5193
  const handle = {
1437
5194
  remove: async () => {
1438
5195
  unsubscribe();
1439
- }
5196
+ },
1440
5197
  };
1441
5198
  // Emit current user state
1442
5199
  const currentUser = await this.getCurrentUser();
@@ -1463,7 +5220,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
1463
5220
  const isSupported = await provider.isSupported();
1464
5221
  return {
1465
5222
  isSupported,
1466
- reason: isSupported ? undefined : 'Provider not supported on this platform',
5223
+ reason: isSupported
5224
+ ? undefined
5225
+ : 'Provider not supported on this platform',
1467
5226
  availableProviders: Array.from(this.providers.keys()),
1468
5227
  };
1469
5228
  }
@@ -1614,7 +5373,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
1614
5373
  }
1615
5374
  }
1616
5375
  async createProvider(config) {
1617
- return ProviderFactory.createProvider(config, this.storage, this.logger, this.storage instanceof WebStorage ? exports.AuthPersistence.LOCAL : exports.AuthPersistence.NONE);
5376
+ return ProviderFactory.createProvider(config, this.storage, this.logger, this.storage instanceof WebStorage
5377
+ ? exports.AuthPersistence.LOCAL
5378
+ : exports.AuthPersistence.NONE);
1618
5379
  }
1619
5380
  setupTokenRefresh(provider, credential) {
1620
5381
  // Cancel existing refresh timer
@@ -1649,5 +5410,9 @@ var web = /*#__PURE__*/Object.freeze({
1649
5410
  CapacitorAuthManagerWeb: CapacitorAuthManagerWeb
1650
5411
  });
1651
5412
 
5413
+ exports.AuthError = AuthError;
1652
5414
  exports.CapacitorAuthManager = CapacitorAuthManager;
5415
+ exports.PlatformDetector = PlatformDetector;
5416
+ exports.auth = auth;
5417
+ exports.isAuthError = isAuthError;
1653
5418
  //# sourceMappingURL=plugin.cjs.js.map