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