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