capacitor-auth-manager 2.1.0 → 2.3.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/CapacitorAuthManager.podspec +1 -1
- package/Readme.md +223 -103
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +28 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +109 -15
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/FacebookAuthProvider.java +389 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +353 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/MicrosoftAuthProvider.java +455 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +180 -0
- package/dist/angular.cjs.js +7036 -0
- package/dist/angular.cjs.js.map +1 -0
- package/dist/core.cjs.js +2216 -486
- package/dist/core.cjs.js.map +1 -1
- package/dist/esm/angular/auth.guard.d.ts +18 -0
- package/dist/esm/angular/auth.guard.js +82 -0
- package/dist/esm/angular/auth.guard.js.map +1 -0
- package/dist/esm/angular/auth.module.d.ts +18 -0
- package/dist/esm/angular/auth.module.js +56 -0
- package/dist/esm/angular/auth.module.js.map +1 -0
- package/dist/esm/angular/auth.service.d.ts +108 -0
- package/dist/esm/angular/auth.service.js +224 -0
- package/dist/esm/angular/auth.service.js.map +1 -0
- package/dist/esm/angular/index.d.ts +3 -0
- package/dist/esm/angular/index.js +4 -0
- package/dist/esm/angular/index.js.map +1 -0
- package/dist/esm/core/auth-manager.d.ts +61 -1
- package/dist/esm/core/auth-manager.js +285 -24
- package/dist/esm/core/auth-manager.js.map +1 -1
- package/dist/esm/core/platform.d.ts +7 -0
- package/dist/esm/core/platform.js +30 -10
- package/dist/esm/core/platform.js.map +1 -1
- package/dist/esm/core/provider-manifests.d.ts +9 -0
- package/dist/esm/core/provider-manifests.js +471 -0
- package/dist/esm/core/provider-manifests.js.map +1 -0
- package/dist/esm/core/provider-registry.d.ts +19 -1
- package/dist/esm/core/provider-registry.js +72 -480
- package/dist/esm/core/provider-registry.js.map +1 -1
- package/dist/esm/core/types.d.ts +18 -7
- package/dist/esm/definitions.d.ts +42 -1
- package/dist/esm/definitions.js +28 -0
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/providers/base-provider.d.ts +14 -3
- package/dist/esm/providers/base-provider.js +53 -1
- package/dist/esm/providers/base-provider.js.map +1 -1
- package/dist/esm/providers/oauth-provider.d.ts +23 -2
- package/dist/esm/providers/oauth-provider.js +134 -17
- package/dist/esm/providers/oauth-provider.js.map +1 -1
- package/dist/esm/providers/provider-factory.d.ts +3 -1
- package/dist/esm/providers/provider-factory.js +29 -41
- package/dist/esm/providers/provider-factory.js.map +1 -1
- package/dist/esm/providers/web/apple-provider.d.ts +2 -1
- package/dist/esm/providers/web/apple-provider.js +25 -9
- package/dist/esm/providers/web/apple-provider.js.map +1 -1
- package/dist/esm/providers/web/biometric-provider.d.ts +20 -7
- package/dist/esm/providers/web/biometric-provider.js +124 -23
- package/dist/esm/providers/web/biometric-provider.js.map +1 -1
- package/dist/esm/providers/web/email-code-provider.d.ts +46 -0
- package/dist/esm/providers/web/email-code-provider.js +294 -0
- package/dist/esm/providers/web/email-code-provider.js.map +1 -0
- package/dist/esm/providers/web/email-password-provider.d.ts +4 -7
- package/dist/esm/providers/web/email-password-provider.js +38 -38
- package/dist/esm/providers/web/email-password-provider.js.map +1 -1
- package/dist/esm/providers/web/facebook-provider.d.ts +52 -1
- package/dist/esm/providers/web/facebook-provider.js +2 -2
- package/dist/esm/providers/web/facebook-provider.js.map +1 -1
- package/dist/esm/providers/web/firebase-provider.d.ts +5 -3
- package/dist/esm/providers/web/firebase-provider.js +74 -42
- package/dist/esm/providers/web/firebase-provider.js.map +1 -1
- package/dist/esm/providers/web/github-provider.d.ts +9 -0
- package/dist/esm/providers/web/github-provider.js +91 -14
- package/dist/esm/providers/web/github-provider.js.map +1 -1
- package/dist/esm/providers/web/index.d.ts +2 -0
- package/dist/esm/providers/web/index.js +2 -0
- package/dist/esm/providers/web/index.js.map +1 -1
- package/dist/esm/providers/web/linkedin-provider.d.ts +2 -3
- package/dist/esm/providers/web/linkedin-provider.js +40 -14
- package/dist/esm/providers/web/linkedin-provider.js.map +1 -1
- package/dist/esm/providers/web/magic-link-provider.d.ts +4 -6
- package/dist/esm/providers/web/magic-link-provider.js +49 -36
- package/dist/esm/providers/web/magic-link-provider.js.map +1 -1
- package/dist/esm/providers/web/microsoft-provider.d.ts +2 -0
- package/dist/esm/providers/web/microsoft-provider.js +45 -20
- package/dist/esm/providers/web/microsoft-provider.js.map +1 -1
- package/dist/esm/providers/web/phone-password-provider.d.ts +63 -0
- package/dist/esm/providers/web/phone-password-provider.js +440 -0
- package/dist/esm/providers/web/phone-password-provider.js.map +1 -0
- package/dist/esm/providers/web/slack-provider.d.ts +2 -3
- package/dist/esm/providers/web/slack-provider.js +38 -14
- package/dist/esm/providers/web/slack-provider.js.map +1 -1
- package/dist/esm/providers/web/sms-provider.d.ts +4 -6
- package/dist/esm/providers/web/sms-provider.js +33 -28
- package/dist/esm/providers/web/sms-provider.js.map +1 -1
- package/dist/esm/providers/web/username-password-provider.d.ts +4 -7
- package/dist/esm/providers/web/username-password-provider.js +32 -30
- package/dist/esm/providers/web/username-password-provider.js.map +1 -1
- package/dist/esm/react/hooks.d.ts +110 -0
- package/dist/esm/react/hooks.js +307 -0
- package/dist/esm/react/hooks.js.map +1 -0
- package/dist/esm/react/index.d.ts +2 -0
- package/dist/esm/react/index.js +3 -0
- package/dist/esm/react/index.js.map +1 -0
- package/dist/esm/react/types.d.ts +30 -0
- package/dist/esm/react/types.js +2 -0
- package/dist/esm/react/types.js.map +1 -0
- package/dist/esm/utils/auth-error.d.ts +7 -0
- package/dist/esm/utils/auth-error.js +31 -5
- package/dist/esm/utils/auth-error.js.map +1 -1
- package/dist/esm/utils/event-emitter.d.ts +7 -0
- package/dist/esm/utils/event-emitter.js +8 -2
- package/dist/esm/utils/event-emitter.js.map +1 -1
- package/dist/esm/utils/logger.d.ts +28 -1
- package/dist/esm/utils/logger.js +115 -1
- package/dist/esm/utils/logger.js.map +1 -1
- package/dist/esm/utils/pending-verification-store.d.ts +59 -0
- package/dist/esm/utils/pending-verification-store.js +103 -0
- package/dist/esm/utils/pending-verification-store.js.map +1 -0
- package/dist/esm/utils/storage.d.ts +29 -1
- package/dist/esm/utils/storage.js +64 -5
- package/dist/esm/utils/storage.js.map +1 -1
- package/dist/esm/vue/composables.d.ts +124 -0
- package/dist/esm/vue/composables.js +290 -0
- package/dist/esm/vue/composables.js.map +1 -0
- package/dist/esm/vue/index.d.ts +1 -0
- package/dist/esm/vue/index.js +2 -0
- package/dist/esm/vue/index.js.map +1 -0
- package/dist/esm/web.d.ts +32 -7
- package/dist/esm/web.js +247 -52
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +2674 -719
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +2674 -719
- package/dist/plugin.js.map +1 -1
- package/dist/react.cjs.js +6991 -0
- package/dist/react.cjs.js.map +1 -0
- package/dist/vue.cjs.js +6974 -0
- package/dist/vue.cjs.js.map +1 -0
- package/ios/Plugin/AppleAuthProvider.swift +288 -0
- package/ios/Plugin/AuthStorage.swift +49 -1
- package/ios/Plugin/CapacitorAuthManager.swift +45 -23
- package/ios/Plugin/FacebookAuthProvider.swift +297 -0
- package/ios/Plugin/GitHubAuthProvider.swift +54 -0
- package/ios/Plugin/GoogleAuthProvider.swift +265 -0
- package/ios/Plugin/LinkedInAuthProvider.swift +63 -0
- package/ios/Plugin/MicrosoftAuthProvider.swift +315 -0
- package/ios/Plugin/Models.swift +4 -1
- package/ios/Plugin/OAuthWebProvider.swift +415 -0
- package/ios/Plugin/SlackAuthProvider.swift +108 -0
- package/package.json +61 -40
package/dist/core.cjs.js
CHANGED
|
@@ -1,42 +1,65 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
3
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
4
|
+
/**
|
|
5
|
+
* Reads a default log level from the build/runtime environment WITHOUT assuming a particular
|
|
6
|
+
* bundler or host. Checked defensively (each access wrapped) so it is safe in:
|
|
7
|
+
* - Vite / bundlers that define `import.meta.env`
|
|
8
|
+
* - Node / SSR where `globalThis.process.env` exists
|
|
9
|
+
* - Plain browsers where neither is present (falls back to 'warn')
|
|
10
|
+
*
|
|
11
|
+
* Intentional omissions for a PUBLISHED LIBRARY (see F-42):
|
|
12
|
+
* - We do NOT patch the host application's global `console.*`. A library silencing the host's
|
|
13
|
+
* console would be hostile and surprising.
|
|
14
|
+
* - We do NOT read the host's `localStorage` for a log-level switch. The host owns its storage;
|
|
15
|
+
* the consumer configures logging explicitly via `auth.configure({ logLevel })` or
|
|
16
|
+
* `logger.setLevel()`.
|
|
17
|
+
*/
|
|
18
|
+
function readEnvLogLevel() {
|
|
19
|
+
var _a;
|
|
20
|
+
const candidates = [];
|
|
21
|
+
try {
|
|
22
|
+
// import.meta.env may not exist (CJS) — guard the whole access.
|
|
23
|
+
const metaEnv = (_a = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('core.cjs.js', document.baseURI).href)) })) === null || _a === void 0 ? void 0 : _a.env;
|
|
24
|
+
if (metaEnv) {
|
|
25
|
+
candidates.push(metaEnv.VITE_LOG_LEVEL, metaEnv.LOG_LEVEL);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch (_b) {
|
|
29
|
+
// import.meta unsupported in this environment — ignore.
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const proc = globalThis.process;
|
|
33
|
+
if (proc === null || proc === void 0 ? void 0 : proc.env) {
|
|
34
|
+
candidates.push(proc.env.VITE_LOG_LEVEL, proc.env.LOG_LEVEL);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch (_c) {
|
|
38
|
+
// process not available — ignore.
|
|
39
|
+
}
|
|
40
|
+
for (const value of candidates) {
|
|
41
|
+
if (value === 'debug' ||
|
|
42
|
+
value === 'info' ||
|
|
43
|
+
value === 'warn' ||
|
|
44
|
+
value === 'error' ||
|
|
45
|
+
value === 'silent') {
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
29
50
|
}
|
|
30
|
-
|
|
31
51
|
class Logger {
|
|
32
52
|
constructor(config) {
|
|
53
|
+
var _a, _b;
|
|
33
54
|
this.logLevels = {
|
|
34
55
|
debug: 0,
|
|
35
56
|
info: 1,
|
|
36
57
|
warn: 2,
|
|
37
58
|
error: 3,
|
|
59
|
+
silent: 4,
|
|
38
60
|
};
|
|
39
|
-
|
|
61
|
+
// An explicit logLevel from the caller wins; otherwise fall back to the env default, then 'warn'.
|
|
62
|
+
this.config = Object.assign(Object.assign({}, config), { logLevel: (_b = (_a = config.logLevel) !== null && _a !== void 0 ? _a : readEnvLogLevel()) !== null && _b !== void 0 ? _b : 'warn' });
|
|
40
63
|
}
|
|
41
64
|
shouldLog(level) {
|
|
42
65
|
if (!this.config.enableLogging)
|
|
@@ -68,13 +91,110 @@ class Logger {
|
|
|
68
91
|
console.error(this.formatMessage('error', message), error);
|
|
69
92
|
}
|
|
70
93
|
}
|
|
94
|
+
/** Verbose tracing — gated at `debug` level like {@link debug}. */
|
|
95
|
+
trace(message, ...args) {
|
|
96
|
+
if (this.shouldLog('debug')) {
|
|
97
|
+
console.trace(this.formatMessage('trace', message), ...args);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Tabular output — gated at `debug` level. Falls back to `debug` when `console.table` is absent. */
|
|
101
|
+
table(data, columns) {
|
|
102
|
+
if (this.shouldLog('debug')) {
|
|
103
|
+
if (typeof console.table === 'function') {
|
|
104
|
+
console.table(data, columns);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
console.debug(this.formatMessage('table', ''), data);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Opens a console group — gated at `debug` level. No-ops if `console.group` is absent. */
|
|
112
|
+
group(label) {
|
|
113
|
+
if (this.shouldLog('debug') && typeof console.group === 'function') {
|
|
114
|
+
console.group(label ? this.formatMessage('group', label) : undefined);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Closes a console group opened by {@link group}. */
|
|
118
|
+
groupEnd() {
|
|
119
|
+
if (this.shouldLog('debug') && typeof console.groupEnd === 'function') {
|
|
120
|
+
console.groupEnd();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** Starts a timer — gated at `debug` level. No-ops if `console.time` is absent. */
|
|
124
|
+
time(label) {
|
|
125
|
+
if (this.shouldLog('debug') && typeof console.time === 'function') {
|
|
126
|
+
console.time(label);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** Stops a timer started by {@link time} and logs the elapsed duration. */
|
|
130
|
+
timeEnd(label) {
|
|
131
|
+
if (this.shouldLog('debug') && typeof console.timeEnd === 'function') {
|
|
132
|
+
console.timeEnd(label);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
71
135
|
setLogLevel(level) {
|
|
72
136
|
this.config.logLevel = level;
|
|
73
137
|
}
|
|
138
|
+
/** Alias for {@link setLogLevel} matching the workspace logger convention. */
|
|
139
|
+
setLevel(level) {
|
|
140
|
+
this.config.logLevel = level;
|
|
141
|
+
}
|
|
142
|
+
getLevel() {
|
|
143
|
+
return this.config.logLevel;
|
|
144
|
+
}
|
|
74
145
|
setEnabled(enabled) {
|
|
75
146
|
this.config.enableLogging = enabled;
|
|
76
147
|
}
|
|
77
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Shared default logger instance used by package internals that don't receive a logger via
|
|
151
|
+
* dependency injection (e.g. {@link EventEmitter}, {@link WebStorage} defaults, the biometric
|
|
152
|
+
* provider). Enabled by default at `warn` level so only warnings + errors surface unless the
|
|
153
|
+
* consumer raises the level. Consumers can adjust it programmatically:
|
|
154
|
+
*
|
|
155
|
+
* ```ts
|
|
156
|
+
* import { defaultLogger } from 'capacitor-auth-manager';
|
|
157
|
+
* defaultLogger.setLevel('debug');
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
const defaultLogger = new Logger({
|
|
161
|
+
enableLogging: true,
|
|
162
|
+
logLevel: 'warn',
|
|
163
|
+
prefix: 'CapacitorAuthManager',
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
class EventEmitter {
|
|
167
|
+
/**
|
|
168
|
+
* @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
|
|
169
|
+
* so emitter errors honour the package log level instead of writing to `console` directly.
|
|
170
|
+
*/
|
|
171
|
+
constructor(logger = defaultLogger) {
|
|
172
|
+
this.listeners = new Set();
|
|
173
|
+
this.logger = logger;
|
|
174
|
+
}
|
|
175
|
+
emit(data) {
|
|
176
|
+
this.listeners.forEach((listener) => {
|
|
177
|
+
try {
|
|
178
|
+
listener(data);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
this.logger.error('Error in event listener:', error);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
subscribe(listener) {
|
|
186
|
+
this.listeners.add(listener);
|
|
187
|
+
return () => {
|
|
188
|
+
this.listeners.delete(listener);
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
clear() {
|
|
192
|
+
this.listeners.clear();
|
|
193
|
+
}
|
|
194
|
+
get listenerCount() {
|
|
195
|
+
return this.listeners.size;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
78
198
|
|
|
79
199
|
var AuthProvider;
|
|
80
200
|
(function (AuthProvider) {
|
|
@@ -188,11 +308,46 @@ var AuthErrorCode;
|
|
|
188
308
|
AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
|
|
189
309
|
AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
|
|
190
310
|
AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
|
|
311
|
+
// --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
|
|
312
|
+
// magic-link / biometric / email-password / username-password / phone-password) throw enum
|
|
313
|
+
// codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
|
|
314
|
+
AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
|
|
315
|
+
AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
|
|
316
|
+
AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
|
|
317
|
+
AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
|
|
318
|
+
AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
|
|
319
|
+
AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
|
|
320
|
+
AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
|
|
321
|
+
AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
|
|
322
|
+
AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
|
|
323
|
+
AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
|
|
324
|
+
AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
|
|
325
|
+
AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
|
|
326
|
+
AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
|
|
327
|
+
AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
|
|
328
|
+
AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
|
|
329
|
+
AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
|
|
330
|
+
AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
|
|
331
|
+
AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
|
|
332
|
+
AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
|
|
333
|
+
AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
|
|
334
|
+
AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
|
|
335
|
+
AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
|
|
336
|
+
AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
|
|
337
|
+
AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
|
|
338
|
+
AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
|
|
191
339
|
})(AuthErrorCode || (AuthErrorCode = {}));
|
|
192
340
|
|
|
193
341
|
class WebStorage {
|
|
194
|
-
|
|
342
|
+
/**
|
|
343
|
+
* @param persistence Where to persist values (local / session / in-memory).
|
|
344
|
+
* @param prefix Key prefix to namespace this package's storage.
|
|
345
|
+
* @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
|
|
346
|
+
* so storage failures honour the package log level instead of writing to `console` directly.
|
|
347
|
+
*/
|
|
348
|
+
constructor(persistence = AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
|
|
195
349
|
this.prefix = prefix;
|
|
350
|
+
this.logger = logger;
|
|
196
351
|
switch (persistence) {
|
|
197
352
|
case AuthPersistence.SESSION:
|
|
198
353
|
this.storage = window.sessionStorage;
|
|
@@ -222,7 +377,7 @@ class WebStorage {
|
|
|
222
377
|
return null;
|
|
223
378
|
}
|
|
224
379
|
catch (error) {
|
|
225
|
-
|
|
380
|
+
this.logger.error('Storage get error:', error);
|
|
226
381
|
return null;
|
|
227
382
|
}
|
|
228
383
|
}
|
|
@@ -232,7 +387,7 @@ class WebStorage {
|
|
|
232
387
|
this.storage.setItem(this.prefix + key, stringValue);
|
|
233
388
|
}
|
|
234
389
|
catch (error) {
|
|
235
|
-
|
|
390
|
+
this.logger.error('Storage set error:', error);
|
|
236
391
|
throw error;
|
|
237
392
|
}
|
|
238
393
|
}
|
|
@@ -241,7 +396,7 @@ class WebStorage {
|
|
|
241
396
|
this.storage.removeItem(this.prefix + key);
|
|
242
397
|
}
|
|
243
398
|
catch (error) {
|
|
244
|
-
|
|
399
|
+
this.logger.error('Storage remove error:', error);
|
|
245
400
|
}
|
|
246
401
|
}
|
|
247
402
|
async clear() {
|
|
@@ -256,7 +411,7 @@ class WebStorage {
|
|
|
256
411
|
keys.forEach((key) => this.storage.removeItem(key));
|
|
257
412
|
}
|
|
258
413
|
catch (error) {
|
|
259
|
-
|
|
414
|
+
this.logger.error('Storage clear error:', error);
|
|
260
415
|
}
|
|
261
416
|
}
|
|
262
417
|
}
|
|
@@ -291,11 +446,36 @@ class AuthError extends Error {
|
|
|
291
446
|
this.name = 'AuthError';
|
|
292
447
|
this.code = code;
|
|
293
448
|
this.provider = provider;
|
|
294
|
-
this.details = details;
|
|
295
|
-
// Maintains proper stack trace for where our error was thrown (only available on V8
|
|
296
|
-
|
|
297
|
-
|
|
449
|
+
this.details = AuthError.sanitizeDetails(details);
|
|
450
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8 engines:
|
|
451
|
+
// Node.js and Chromium). Typed locally so the package does not depend on @types/node globals.
|
|
452
|
+
const ErrorCtor = Error;
|
|
453
|
+
if (ErrorCtor.captureStackTrace) {
|
|
454
|
+
ErrorCtor.captureStackTrace(this, AuthError);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Produces a safe, shallow `details` object: redacts sensitive keys and keeps only JSON-safe
|
|
459
|
+
* primitives. Prevents tokens/PII embedded in a raw error or token-endpoint response body from
|
|
460
|
+
* being captured into AuthError.details (and thus logged or serialized via toJSON()).
|
|
461
|
+
*/
|
|
462
|
+
static sanitizeDetails(input) {
|
|
463
|
+
if (input === null || typeof input !== 'object') {
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
const out = {};
|
|
467
|
+
for (const [key, value] of Object.entries(input)) {
|
|
468
|
+
if (AuthError.SENSITIVE_KEY.test(key)) {
|
|
469
|
+
out[key] = '[redacted]';
|
|
470
|
+
}
|
|
471
|
+
else if (value === null ||
|
|
472
|
+
typeof value === 'string' ||
|
|
473
|
+
typeof value === 'number' ||
|
|
474
|
+
typeof value === 'boolean') {
|
|
475
|
+
out[key] = value;
|
|
476
|
+
}
|
|
298
477
|
}
|
|
478
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
299
479
|
}
|
|
300
480
|
static fromError(error, provider) {
|
|
301
481
|
if (error instanceof AuthError) {
|
|
@@ -303,7 +483,7 @@ class AuthError extends Error {
|
|
|
303
483
|
}
|
|
304
484
|
let code = AuthErrorCode.INTERNAL_ERROR;
|
|
305
485
|
let message = 'An unknown error occurred';
|
|
306
|
-
|
|
486
|
+
const details = error;
|
|
307
487
|
if (error instanceof Error) {
|
|
308
488
|
message = error.message;
|
|
309
489
|
// Try to map common error patterns to specific error codes
|
|
@@ -338,10 +518,20 @@ class AuthError extends Error {
|
|
|
338
518
|
};
|
|
339
519
|
}
|
|
340
520
|
}
|
|
521
|
+
AuthError.SENSITIVE_KEY = /(token|secret|password|authorization|code_verifier|client_secret|credential|api[-_]?key|cookie)/i;
|
|
341
522
|
|
|
523
|
+
function getPlatformWindow() {
|
|
524
|
+
return typeof window !== 'undefined'
|
|
525
|
+
? window
|
|
526
|
+
: undefined;
|
|
527
|
+
}
|
|
342
528
|
class PlatformDetector {
|
|
343
529
|
static getPlatform() {
|
|
344
|
-
|
|
530
|
+
// A cached NON-web result is final (native/electron never reverts to web). But a cached
|
|
531
|
+
// 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
|
|
532
|
+
// module first runs (the native bridge initializes asynchronously), so re-evaluate while
|
|
533
|
+
// the last verdict was 'web' to pick up a late native environment. See F-26.
|
|
534
|
+
if (this.platformInfo && this.platformInfo.platform !== 'web') {
|
|
345
535
|
return this.platformInfo;
|
|
346
536
|
}
|
|
347
537
|
const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
|
|
@@ -359,11 +549,21 @@ class PlatformDetector {
|
|
|
359
549
|
};
|
|
360
550
|
return this.platformInfo;
|
|
361
551
|
}
|
|
552
|
+
/**
|
|
553
|
+
* Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
|
|
554
|
+
* result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
|
|
555
|
+
* initializes late). Most callers can rely on the automatic re-check while the cached value is
|
|
556
|
+
* still 'web'.
|
|
557
|
+
*/
|
|
558
|
+
static reset() {
|
|
559
|
+
this.platformInfo = null;
|
|
560
|
+
}
|
|
362
561
|
static detectPlatform(userAgent) {
|
|
363
562
|
var _a, _b;
|
|
563
|
+
const win = getPlatformWindow();
|
|
364
564
|
// Check if running in Capacitor
|
|
365
|
-
if (
|
|
366
|
-
const capacitor =
|
|
565
|
+
if (win === null || win === void 0 ? void 0 : win.Capacitor) {
|
|
566
|
+
const capacitor = win.Capacitor;
|
|
367
567
|
if (capacitor.getPlatform) {
|
|
368
568
|
const platform = capacitor.getPlatform();
|
|
369
569
|
if (platform === 'ios' || platform === 'android') {
|
|
@@ -372,8 +572,7 @@ class PlatformDetector {
|
|
|
372
572
|
}
|
|
373
573
|
}
|
|
374
574
|
// Check if running in Electron
|
|
375
|
-
if (
|
|
376
|
-
((_b = (_a = window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron)) {
|
|
575
|
+
if ((_b = (_a = win === null || win === void 0 ? void 0 : win.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron) {
|
|
377
576
|
return 'electron';
|
|
378
577
|
}
|
|
379
578
|
// Check for React Native
|
|
@@ -402,124 +601,34 @@ class PlatformDetector {
|
|
|
402
601
|
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
|
|
403
602
|
}
|
|
404
603
|
static isCapacitorAvailable() {
|
|
405
|
-
|
|
604
|
+
var _a;
|
|
605
|
+
return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
|
|
406
606
|
}
|
|
407
607
|
static async checkCapacitorPlugin(pluginName) {
|
|
408
|
-
|
|
608
|
+
var _a;
|
|
609
|
+
const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
|
|
610
|
+
if (!capacitor) {
|
|
409
611
|
return false;
|
|
410
612
|
}
|
|
411
613
|
try {
|
|
412
|
-
|
|
413
|
-
return !!(Capacitor.Plugins && Capacitor.Plugins[pluginName]);
|
|
614
|
+
return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
|
|
414
615
|
}
|
|
415
|
-
catch (
|
|
616
|
+
catch (_b) {
|
|
416
617
|
return false;
|
|
417
618
|
}
|
|
418
619
|
}
|
|
419
620
|
}
|
|
420
621
|
PlatformDetector.platformInfo = null;
|
|
421
622
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
return this.manifests.get(name);
|
|
432
|
-
}
|
|
433
|
-
static async getProvider(name, config) {
|
|
434
|
-
var _b, _c;
|
|
435
|
-
// Check if already loaded
|
|
436
|
-
const existing = this.providers.get(name);
|
|
437
|
-
if (existing) {
|
|
438
|
-
return existing;
|
|
439
|
-
}
|
|
440
|
-
// Check if loader exists
|
|
441
|
-
const loader = this.loaders.get(name);
|
|
442
|
-
if (!loader) {
|
|
443
|
-
const manifest = this.manifests.get(name);
|
|
444
|
-
if (manifest) {
|
|
445
|
-
throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
|
|
446
|
-
}
|
|
447
|
-
throw new Error(`Unknown provider: ${name}`);
|
|
448
|
-
}
|
|
449
|
-
// Check platform support
|
|
450
|
-
const manifest = this.manifests.get(name);
|
|
451
|
-
if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
|
|
452
|
-
const platform = PlatformDetector.getPlatform();
|
|
453
|
-
if (!manifest.platforms.includes(platform.platform)) {
|
|
454
|
-
throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
try {
|
|
458
|
-
// Load the provider
|
|
459
|
-
const module = await loader();
|
|
460
|
-
const ProviderClass = module.default;
|
|
461
|
-
// Create instance
|
|
462
|
-
const provider = new ProviderClass(config);
|
|
463
|
-
// Initialize if needed
|
|
464
|
-
if (provider.initialize) {
|
|
465
|
-
await provider.initialize(config);
|
|
466
|
-
}
|
|
467
|
-
// Cache the provider
|
|
468
|
-
this.providers.set(name, provider);
|
|
469
|
-
return provider;
|
|
470
|
-
}
|
|
471
|
-
catch (error) {
|
|
472
|
-
// Check if it's a missing dependency error
|
|
473
|
-
if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot find module')) ||
|
|
474
|
-
((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Failed to resolve module'))) {
|
|
475
|
-
const manifest = this.manifests.get(name);
|
|
476
|
-
if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
|
|
477
|
-
throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
|
|
478
|
-
`Install the required package:\n` +
|
|
479
|
-
`npm install ${manifest.packageName}\n\n` +
|
|
480
|
-
`Then try again.`);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
throw error;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
static clearProvider(name) {
|
|
487
|
-
const provider = this.providers.get(name);
|
|
488
|
-
if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
|
|
489
|
-
provider.dispose();
|
|
490
|
-
}
|
|
491
|
-
this.providers.delete(name);
|
|
492
|
-
}
|
|
493
|
-
static clearAll() {
|
|
494
|
-
for (const [, provider] of this.providers) {
|
|
495
|
-
if (provider.dispose) {
|
|
496
|
-
provider.dispose();
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
this.providers.clear();
|
|
500
|
-
}
|
|
501
|
-
static getAvailableProviders() {
|
|
502
|
-
return Array.from(this.manifests.keys());
|
|
503
|
-
}
|
|
504
|
-
static getSupportedProviders() {
|
|
505
|
-
const platform = PlatformDetector.getPlatform();
|
|
506
|
-
const supported = [];
|
|
507
|
-
for (const [name, manifest] of this.manifests) {
|
|
508
|
-
if (!manifest.platforms ||
|
|
509
|
-
manifest.platforms.includes(platform.platform)) {
|
|
510
|
-
supported.push(name);
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
return Promise.resolve(supported);
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
_a = ProviderRegistry;
|
|
517
|
-
ProviderRegistry.providers = new Map();
|
|
518
|
-
ProviderRegistry.loaders = new Map();
|
|
519
|
-
ProviderRegistry.manifests = new Map();
|
|
520
|
-
(() => {
|
|
521
|
-
// Register built-in provider manifests
|
|
522
|
-
_a.registerManifest({
|
|
623
|
+
/**
|
|
624
|
+
* Built-in provider manifests (display metadata + human-readable setup instructions).
|
|
625
|
+
*
|
|
626
|
+
* Extracted from `provider-registry.ts` as a pure data module (zero logic) so the registry stays
|
|
627
|
+
* under the project's file-size guideline. `ProviderRegistry` imports this array and registers each
|
|
628
|
+
* entry in its static initializer — behaviour is unchanged (see F-40).
|
|
629
|
+
*/
|
|
630
|
+
const BUILT_IN_PROVIDER_MANIFESTS = [
|
|
631
|
+
{
|
|
523
632
|
name: 'google',
|
|
524
633
|
displayName: 'Google',
|
|
525
634
|
packageName: '@google/gsi',
|
|
@@ -551,8 +660,8 @@ To use Google authentication, you need to:
|
|
|
551
660
|
scopes: { type: 'array', items: 'string' },
|
|
552
661
|
hostedDomain: { type: 'string' },
|
|
553
662
|
},
|
|
554
|
-
}
|
|
555
|
-
|
|
663
|
+
},
|
|
664
|
+
{
|
|
556
665
|
name: 'apple',
|
|
557
666
|
displayName: 'Apple',
|
|
558
667
|
setupInstructions: `
|
|
@@ -580,8 +689,8 @@ To use Apple authentication:
|
|
|
580
689
|
redirectUri: { type: 'string', required: true },
|
|
581
690
|
scopes: { type: 'array', items: 'string' },
|
|
582
691
|
},
|
|
583
|
-
}
|
|
584
|
-
|
|
692
|
+
},
|
|
693
|
+
{
|
|
585
694
|
name: 'firebase',
|
|
586
695
|
displayName: 'Firebase Auth',
|
|
587
696
|
packageName: 'firebase',
|
|
@@ -615,8 +724,8 @@ To use Firebase authentication:
|
|
|
615
724
|
authDomain: { type: 'string', required: true },
|
|
616
725
|
projectId: { type: 'string', required: true },
|
|
617
726
|
},
|
|
618
|
-
}
|
|
619
|
-
|
|
727
|
+
},
|
|
728
|
+
{
|
|
620
729
|
name: 'microsoft',
|
|
621
730
|
displayName: 'Microsoft',
|
|
622
731
|
packageName: '@azure/msal-browser',
|
|
@@ -650,8 +759,8 @@ To use Microsoft authentication:
|
|
|
650
759
|
redirectUri: { type: 'string' },
|
|
651
760
|
scopes: { type: 'array', items: 'string' },
|
|
652
761
|
},
|
|
653
|
-
}
|
|
654
|
-
|
|
762
|
+
},
|
|
763
|
+
{
|
|
655
764
|
name: 'facebook',
|
|
656
765
|
displayName: 'Facebook',
|
|
657
766
|
setupInstructions: `
|
|
@@ -664,7 +773,7 @@ To use Facebook authentication:
|
|
|
664
773
|
- Configure OAuth redirect URIs
|
|
665
774
|
|
|
666
775
|
2. Add Facebook SDK to your HTML:
|
|
667
|
-
<script async defer crossorigin="anonymous"
|
|
776
|
+
<script async defer crossorigin="anonymous"
|
|
668
777
|
src="https://connect.facebook.net/en_US/sdk.js"></script>
|
|
669
778
|
|
|
670
779
|
3. Configure the provider:
|
|
@@ -683,8 +792,8 @@ To use Facebook authentication:
|
|
|
683
792
|
version: { type: 'string' },
|
|
684
793
|
scopes: { type: 'array', items: 'string' },
|
|
685
794
|
},
|
|
686
|
-
}
|
|
687
|
-
|
|
795
|
+
},
|
|
796
|
+
{
|
|
688
797
|
name: 'github',
|
|
689
798
|
displayName: 'GitHub',
|
|
690
799
|
setupInstructions: `
|
|
@@ -713,9 +822,8 @@ Note: You'll need a backend service to exchange the authorization code for an ac
|
|
|
713
822
|
redirectUri: { type: 'string' },
|
|
714
823
|
scopes: { type: 'array', items: 'string' },
|
|
715
824
|
},
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
_a.registerManifest({
|
|
825
|
+
},
|
|
826
|
+
{
|
|
719
827
|
name: 'magic-link',
|
|
720
828
|
displayName: 'Email Magic Link',
|
|
721
829
|
setupInstructions: `
|
|
@@ -742,8 +850,8 @@ To use Email Magic Link authentication:
|
|
|
742
850
|
verifyUrl: { type: 'string' },
|
|
743
851
|
redirectUrl: { type: 'string' },
|
|
744
852
|
},
|
|
745
|
-
}
|
|
746
|
-
|
|
853
|
+
},
|
|
854
|
+
{
|
|
747
855
|
name: 'sms',
|
|
748
856
|
displayName: 'SMS Authentication',
|
|
749
857
|
setupInstructions: `
|
|
@@ -772,8 +880,8 @@ To use SMS authentication:
|
|
|
772
880
|
countryCode: { type: 'string' },
|
|
773
881
|
codeLength: { type: 'number' },
|
|
774
882
|
},
|
|
775
|
-
}
|
|
776
|
-
|
|
883
|
+
},
|
|
884
|
+
{
|
|
777
885
|
name: 'email-password',
|
|
778
886
|
displayName: 'Email & Password',
|
|
779
887
|
setupInstructions: `
|
|
@@ -800,8 +908,8 @@ To use Email/Password authentication:
|
|
|
800
908
|
apiUrl: { type: 'string', required: true },
|
|
801
909
|
passwordRequirements: { type: 'object' },
|
|
802
910
|
},
|
|
803
|
-
}
|
|
804
|
-
|
|
911
|
+
},
|
|
912
|
+
{
|
|
805
913
|
name: 'biometric',
|
|
806
914
|
displayName: 'Biometric Authentication',
|
|
807
915
|
packageName: 'capacitor-biometric-authentication',
|
|
@@ -830,8 +938,8 @@ Note: Users must first authenticate with another method before enabling biometri
|
|
|
830
938
|
title: { type: 'string' },
|
|
831
939
|
subtitle: { type: 'string' },
|
|
832
940
|
},
|
|
833
|
-
}
|
|
834
|
-
|
|
941
|
+
},
|
|
942
|
+
{
|
|
835
943
|
name: 'slack',
|
|
836
944
|
displayName: 'Slack',
|
|
837
945
|
setupInstructions: `
|
|
@@ -874,8 +982,8 @@ Note: Slack OAuth requires a backend service to exchange the authorization code
|
|
|
874
982
|
scopes: { type: 'array', items: 'string' },
|
|
875
983
|
teamId: { type: 'string' },
|
|
876
984
|
},
|
|
877
|
-
}
|
|
878
|
-
|
|
985
|
+
},
|
|
986
|
+
{
|
|
879
987
|
name: 'linkedin',
|
|
880
988
|
displayName: 'LinkedIn',
|
|
881
989
|
setupInstructions: `
|
|
@@ -919,8 +1027,8 @@ The redirect URI must be HTTPS in production (LinkedIn requirement).
|
|
|
919
1027
|
redirectUri: { type: 'string', required: true },
|
|
920
1028
|
scopes: { type: 'array', items: 'string' },
|
|
921
1029
|
},
|
|
922
|
-
}
|
|
923
|
-
|
|
1030
|
+
},
|
|
1031
|
+
{
|
|
924
1032
|
name: 'username-password',
|
|
925
1033
|
displayName: 'Username & Password',
|
|
926
1034
|
setupInstructions: `
|
|
@@ -980,7 +1088,153 @@ Note: This provider requires a backend service to handle authentication.
|
|
|
980
1088
|
passwordRequirements: { type: 'object' },
|
|
981
1089
|
allowSignUp: { type: 'boolean' },
|
|
982
1090
|
},
|
|
983
|
-
}
|
|
1091
|
+
},
|
|
1092
|
+
];
|
|
1093
|
+
|
|
1094
|
+
var _a;
|
|
1095
|
+
class ProviderRegistry {
|
|
1096
|
+
static registerManifest(manifest) {
|
|
1097
|
+
this.manifests.set(manifest.name, manifest);
|
|
1098
|
+
}
|
|
1099
|
+
static registerLoader(name, loader) {
|
|
1100
|
+
this.loaders.set(name, loader);
|
|
1101
|
+
}
|
|
1102
|
+
static getManifest(name) {
|
|
1103
|
+
return this.manifests.get(name);
|
|
1104
|
+
}
|
|
1105
|
+
static canonicalName(name) {
|
|
1106
|
+
var _b;
|
|
1107
|
+
return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
|
|
1108
|
+
}
|
|
1109
|
+
static async getProvider(name, options, deps) {
|
|
1110
|
+
var _b, _c, _d, _e;
|
|
1111
|
+
const key = this.canonicalName(name);
|
|
1112
|
+
// Check if already loaded
|
|
1113
|
+
const existing = this.providers.get(key);
|
|
1114
|
+
if (existing) {
|
|
1115
|
+
return existing;
|
|
1116
|
+
}
|
|
1117
|
+
// Check if loader exists
|
|
1118
|
+
const loader = this.loaders.get(key);
|
|
1119
|
+
if (!loader) {
|
|
1120
|
+
const manifest = this.manifests.get(key);
|
|
1121
|
+
if (manifest) {
|
|
1122
|
+
throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
|
|
1123
|
+
}
|
|
1124
|
+
throw new Error(`Unknown provider: ${name}`);
|
|
1125
|
+
}
|
|
1126
|
+
// Check platform support
|
|
1127
|
+
const manifest = this.manifests.get(key);
|
|
1128
|
+
if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
|
|
1129
|
+
const platform = PlatformDetector.getPlatform();
|
|
1130
|
+
if (!manifest.platforms.includes(platform.platform)) {
|
|
1131
|
+
throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
try {
|
|
1135
|
+
// Load the provider class
|
|
1136
|
+
const module = await loader();
|
|
1137
|
+
const ProviderClass = module.default;
|
|
1138
|
+
// Build the constructor argument. BaseAuthProvider subclasses need a full
|
|
1139
|
+
// BaseProviderConfig ({ provider, options, storage, logger, persistence });
|
|
1140
|
+
// standalone providers take their options object directly.
|
|
1141
|
+
const storage = (_b = deps === null || deps === void 0 ? void 0 : deps.storage) !== null && _b !== void 0 ? _b : new WebStorage(AuthPersistence.LOCAL);
|
|
1142
|
+
const logger = (_c = deps === null || deps === void 0 ? void 0 : deps.logger) !== null && _c !== void 0 ? _c : new Logger({
|
|
1143
|
+
enableLogging: false,
|
|
1144
|
+
logLevel: 'warn',
|
|
1145
|
+
prefix: 'AuthManager',
|
|
1146
|
+
});
|
|
1147
|
+
const constructorArg = this.STANDALONE_PROVIDERS.has(key)
|
|
1148
|
+
? (options !== null && options !== void 0 ? options : {})
|
|
1149
|
+
: {
|
|
1150
|
+
provider: key,
|
|
1151
|
+
options: (options !== null && options !== void 0 ? options : {}),
|
|
1152
|
+
storage,
|
|
1153
|
+
logger,
|
|
1154
|
+
persistence: deps === null || deps === void 0 ? void 0 : deps.persistence,
|
|
1155
|
+
};
|
|
1156
|
+
// Create instance
|
|
1157
|
+
const provider = new ProviderClass(constructorArg);
|
|
1158
|
+
// Initialize if supported (BaseAuthProvider.initialize takes no arguments)
|
|
1159
|
+
if (provider.initialize) {
|
|
1160
|
+
await provider.initialize();
|
|
1161
|
+
}
|
|
1162
|
+
// Cache the provider under its canonical key
|
|
1163
|
+
this.providers.set(key, provider);
|
|
1164
|
+
return provider;
|
|
1165
|
+
}
|
|
1166
|
+
catch (error) {
|
|
1167
|
+
// Check if it's a missing dependency error
|
|
1168
|
+
if (((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot find module')) ||
|
|
1169
|
+
((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to resolve module'))) {
|
|
1170
|
+
const manifest = this.manifests.get(this.canonicalName(name));
|
|
1171
|
+
if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
|
|
1172
|
+
throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
|
|
1173
|
+
`Install the required package:\n` +
|
|
1174
|
+
`npm install ${manifest.packageName}\n\n` +
|
|
1175
|
+
`Then try again.`);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
throw error;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
static clearProvider(name) {
|
|
1182
|
+
const key = this.canonicalName(name);
|
|
1183
|
+
const provider = this.providers.get(key);
|
|
1184
|
+
if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
|
|
1185
|
+
provider.dispose();
|
|
1186
|
+
}
|
|
1187
|
+
this.providers.delete(key);
|
|
1188
|
+
}
|
|
1189
|
+
static clearAll() {
|
|
1190
|
+
for (const [, provider] of this.providers) {
|
|
1191
|
+
if (provider.dispose) {
|
|
1192
|
+
provider.dispose();
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
this.providers.clear();
|
|
1196
|
+
}
|
|
1197
|
+
static getAvailableProviders() {
|
|
1198
|
+
return Array.from(this.manifests.keys());
|
|
1199
|
+
}
|
|
1200
|
+
static getSupportedProviders() {
|
|
1201
|
+
const platform = PlatformDetector.getPlatform();
|
|
1202
|
+
const supported = [];
|
|
1203
|
+
for (const [name, manifest] of this.manifests) {
|
|
1204
|
+
if (!manifest.platforms ||
|
|
1205
|
+
manifest.platforms.includes(platform.platform)) {
|
|
1206
|
+
supported.push(name);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return Promise.resolve(supported);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
_a = ProviderRegistry;
|
|
1213
|
+
ProviderRegistry.providers = new Map();
|
|
1214
|
+
ProviderRegistry.loaders = new Map();
|
|
1215
|
+
ProviderRegistry.manifests = new Map();
|
|
1216
|
+
/** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
|
|
1217
|
+
ProviderRegistry.STANDALONE_PROVIDERS = new Set([
|
|
1218
|
+
'magic-link',
|
|
1219
|
+
'sms',
|
|
1220
|
+
'email-password',
|
|
1221
|
+
'username-password',
|
|
1222
|
+
'biometric',
|
|
1223
|
+
'phone-password',
|
|
1224
|
+
'email-code',
|
|
1225
|
+
]);
|
|
1226
|
+
/** Maps AuthProvider enum values (some underscored) to the registered hyphenated loader keys. */
|
|
1227
|
+
ProviderRegistry.NAME_ALIASES = {
|
|
1228
|
+
email_magic_link: 'magic-link',
|
|
1229
|
+
username_password: 'username-password',
|
|
1230
|
+
phone_password: 'phone-password',
|
|
1231
|
+
email_code: 'email-code',
|
|
1232
|
+
};
|
|
1233
|
+
(() => {
|
|
1234
|
+
// Register built-in provider manifests (data lives in provider-manifests.ts — F-40).
|
|
1235
|
+
for (const manifest of BUILT_IN_PROVIDER_MANIFESTS) {
|
|
1236
|
+
_a.registerManifest(manifest);
|
|
1237
|
+
}
|
|
984
1238
|
// Register provider loaders
|
|
985
1239
|
_a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
|
|
986
1240
|
default: m.GoogleAuthProviderWeb,
|
|
@@ -1021,8 +1275,31 @@ Note: This provider requires a backend service to handle authentication.
|
|
|
1021
1275
|
_a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
|
|
1022
1276
|
default: m.UsernamePasswordProvider,
|
|
1023
1277
|
})));
|
|
1278
|
+
_a.registerLoader('email-code', () => Promise.resolve().then(function () { return emailCodeProvider; }).then((m) => ({
|
|
1279
|
+
default: m.EmailCodeProvider,
|
|
1280
|
+
})));
|
|
1281
|
+
_a.registerLoader('phone-password', () => Promise.resolve().then(function () { return phonePasswordProvider; }).then((m) => ({
|
|
1282
|
+
default: m.PhonePasswordProvider,
|
|
1283
|
+
})));
|
|
1024
1284
|
})();
|
|
1025
1285
|
|
|
1286
|
+
/**
|
|
1287
|
+
* Maps the config's persistence literal to the {@link AuthPersistence} enum WebStorage expects.
|
|
1288
|
+
* Critically, `'memory'` maps to {@link AuthPersistence.NONE} (`'none'`) — previously the literal
|
|
1289
|
+
* was cast via `as any` and fell through WebStorage's switch to localStorage, silently breaking
|
|
1290
|
+
* in-memory persistence.
|
|
1291
|
+
*/
|
|
1292
|
+
function toAuthPersistence(persistence) {
|
|
1293
|
+
switch (persistence) {
|
|
1294
|
+
case 'session':
|
|
1295
|
+
return AuthPersistence.SESSION;
|
|
1296
|
+
case 'memory':
|
|
1297
|
+
return AuthPersistence.NONE;
|
|
1298
|
+
case 'local':
|
|
1299
|
+
default:
|
|
1300
|
+
return AuthPersistence.LOCAL;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1026
1303
|
class AuthManagerCore {
|
|
1027
1304
|
constructor() {
|
|
1028
1305
|
this.state = {
|
|
@@ -1035,12 +1312,14 @@ class AuthManagerCore {
|
|
|
1035
1312
|
this.config = {};
|
|
1036
1313
|
this.isInitialized = false;
|
|
1037
1314
|
this.tokenRefreshTimers = new Map();
|
|
1038
|
-
this.
|
|
1315
|
+
this.initPromise = null;
|
|
1039
1316
|
this.logger = new Logger({
|
|
1040
1317
|
enableLogging: false,
|
|
1041
1318
|
logLevel: 'info',
|
|
1042
1319
|
prefix: 'AuthManager',
|
|
1043
1320
|
});
|
|
1321
|
+
this.storage = new WebStorage(AuthPersistence.LOCAL, undefined, this.logger);
|
|
1322
|
+
this.currentPersistence = 'local';
|
|
1044
1323
|
// Auto-initialize on first use
|
|
1045
1324
|
if (typeof window !== 'undefined') {
|
|
1046
1325
|
this.initialize().catch((err) => {
|
|
@@ -1052,7 +1331,12 @@ class AuthManagerCore {
|
|
|
1052
1331
|
if (this.isInitialized && !config) {
|
|
1053
1332
|
return;
|
|
1054
1333
|
}
|
|
1055
|
-
|
|
1334
|
+
// Coalesce concurrent first-time initialization (e.g. the constructor's auto-init
|
|
1335
|
+
// racing with an explicit initialize()) so restoreAuthState does not run twice.
|
|
1336
|
+
if (this.initPromise && !config) {
|
|
1337
|
+
return this.initPromise;
|
|
1338
|
+
}
|
|
1339
|
+
if (config) {
|
|
1056
1340
|
this.config = Object.assign(Object.assign({}, this.config), config);
|
|
1057
1341
|
}
|
|
1058
1342
|
// Configure logger
|
|
@@ -1062,12 +1346,21 @@ class AuthManagerCore {
|
|
|
1062
1346
|
if (this.config.logLevel) {
|
|
1063
1347
|
this.logger.setLogLevel(this.config.logLevel);
|
|
1064
1348
|
}
|
|
1065
|
-
//
|
|
1066
|
-
|
|
1067
|
-
|
|
1349
|
+
// A custom storage backend (e.g. secure native storage) takes precedence. Otherwise only
|
|
1350
|
+
// recreate storage when persistence actually changes (don't discard in-memory state on a
|
|
1351
|
+
// no-op re-initialize).
|
|
1352
|
+
if (this.config.storage) {
|
|
1353
|
+
this.storage = this.config.storage;
|
|
1354
|
+
this.currentPersistence = 'custom';
|
|
1355
|
+
}
|
|
1356
|
+
else if (this.config.persistence &&
|
|
1357
|
+
this.config.persistence !== this.currentPersistence) {
|
|
1358
|
+
this.storage = new WebStorage(toAuthPersistence(this.config.persistence), undefined, this.logger);
|
|
1359
|
+
this.currentPersistence = this.config.persistence;
|
|
1068
1360
|
}
|
|
1069
1361
|
// Restore auth state
|
|
1070
|
-
|
|
1362
|
+
this.initPromise = this.restoreAuthState();
|
|
1363
|
+
await this.initPromise;
|
|
1071
1364
|
this.isInitialized = true;
|
|
1072
1365
|
this.logger.info('Auth manager initialized');
|
|
1073
1366
|
}
|
|
@@ -1079,12 +1372,23 @@ class AuthManagerCore {
|
|
|
1079
1372
|
if (config.logLevel) {
|
|
1080
1373
|
this.logger.setLogLevel(config.logLevel);
|
|
1081
1374
|
}
|
|
1082
|
-
if (config.
|
|
1083
|
-
this.storage =
|
|
1375
|
+
if (config.storage) {
|
|
1376
|
+
this.storage = config.storage;
|
|
1377
|
+
this.currentPersistence = 'custom';
|
|
1378
|
+
}
|
|
1379
|
+
else if (config.persistence &&
|
|
1380
|
+
config.persistence !== this.currentPersistence) {
|
|
1381
|
+
this.storage = new WebStorage(toAuthPersistence(config.persistence), undefined, this.logger);
|
|
1382
|
+
this.currentPersistence = config.persistence;
|
|
1383
|
+
}
|
|
1384
|
+
// Now that providers may be configured, (re)attempt session restore so a persisted
|
|
1385
|
+
// session is rehydrated even when the singleton auto-initialized before configure().
|
|
1386
|
+
if (config.providers && Object.keys(config.providers).length > 0) {
|
|
1387
|
+
void this.restoreAuthState();
|
|
1084
1388
|
}
|
|
1085
1389
|
}
|
|
1086
1390
|
async signIn(providerOrOptions) {
|
|
1087
|
-
var _a;
|
|
1391
|
+
var _a, _b, _c;
|
|
1088
1392
|
await this.ensureInitialized();
|
|
1089
1393
|
let providerName;
|
|
1090
1394
|
let signInOptions = {};
|
|
@@ -1110,10 +1414,12 @@ class AuthManagerCore {
|
|
|
1110
1414
|
throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
|
|
1111
1415
|
}
|
|
1112
1416
|
// Get provider instance
|
|
1113
|
-
const provider = await ProviderRegistry.getProvider(providerName, providerConfig);
|
|
1114
|
-
// Sign in
|
|
1417
|
+
const provider = await ProviderRegistry.getProvider(providerName, providerConfig, this.getProviderDeps());
|
|
1418
|
+
// Sign in. Credentials are spread to the top level (where credential providers read
|
|
1419
|
+
// email/password/phoneNumber/username) AND kept nested under `credentials` for
|
|
1420
|
+
// providers that read them there.
|
|
1115
1421
|
this.logger.info(`Signing in with ${providerName}`);
|
|
1116
|
-
const result = await provider.signIn(Object.assign(Object.assign({}, signInOptions.options), { credentials: signInOptions.credentials }));
|
|
1422
|
+
const result = await provider.signIn(Object.assign(Object.assign(Object.assign({}, signInOptions.options), ((_b = signInOptions.credentials) !== null && _b !== void 0 ? _b : {})), { credentials: signInOptions.credentials }));
|
|
1117
1423
|
// Update state
|
|
1118
1424
|
this.updateState({
|
|
1119
1425
|
user: result.user,
|
|
@@ -1128,7 +1434,7 @@ class AuthManagerCore {
|
|
|
1128
1434
|
credential: result.credential,
|
|
1129
1435
|
});
|
|
1130
1436
|
// Setup token refresh
|
|
1131
|
-
if (this.config.autoRefreshToken && result.credential.refreshToken) {
|
|
1437
|
+
if (this.config.autoRefreshToken && ((_c = result.credential) === null || _c === void 0 ? void 0 : _c.refreshToken)) {
|
|
1132
1438
|
this.setupTokenRefresh(providerName, result.credential);
|
|
1133
1439
|
}
|
|
1134
1440
|
return result;
|
|
@@ -1151,11 +1457,17 @@ class AuthManagerCore {
|
|
|
1151
1457
|
try {
|
|
1152
1458
|
// Get provider instance
|
|
1153
1459
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
|
|
1154
|
-
const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig);
|
|
1460
|
+
const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig, this.getProviderDeps());
|
|
1155
1461
|
// Sign out
|
|
1156
1462
|
await providerInstance.signOut(options);
|
|
1157
|
-
// Clear token refresh
|
|
1158
|
-
|
|
1463
|
+
// Clear token refresh. When no specific provider was targeted, clear ALL refresh timers
|
|
1464
|
+
// (not just the active provider's) so a global sign-out leaves no orphaned timers behind.
|
|
1465
|
+
if (options === null || options === void 0 ? void 0 : options.provider) {
|
|
1466
|
+
this.clearTokenRefresh(provider);
|
|
1467
|
+
}
|
|
1468
|
+
else {
|
|
1469
|
+
this.clearAllTokenRefresh();
|
|
1470
|
+
}
|
|
1159
1471
|
// Clear state
|
|
1160
1472
|
this.updateState({
|
|
1161
1473
|
user: null,
|
|
@@ -1186,7 +1498,7 @@ class AuthManagerCore {
|
|
|
1186
1498
|
return this.state.provider;
|
|
1187
1499
|
}
|
|
1188
1500
|
async refreshToken(provider) {
|
|
1189
|
-
var _a;
|
|
1501
|
+
var _a, _b;
|
|
1190
1502
|
await this.ensureInitialized();
|
|
1191
1503
|
const targetProvider = provider || this.state.provider;
|
|
1192
1504
|
if (!targetProvider) {
|
|
@@ -1194,7 +1506,7 @@ class AuthManagerCore {
|
|
|
1194
1506
|
}
|
|
1195
1507
|
try {
|
|
1196
1508
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
|
|
1197
|
-
const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig);
|
|
1509
|
+
const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig, this.getProviderDeps());
|
|
1198
1510
|
if (!providerInstance.refreshToken) {
|
|
1199
1511
|
throw new AuthError('auth/operation-not-supported', `Provider '${targetProvider}' does not support token refresh`);
|
|
1200
1512
|
}
|
|
@@ -1202,7 +1514,7 @@ class AuthManagerCore {
|
|
|
1202
1514
|
// Update user
|
|
1203
1515
|
this.updateState({ user: result.user });
|
|
1204
1516
|
// Setup new token refresh
|
|
1205
|
-
if (this.config.autoRefreshToken && result.credential.refreshToken) {
|
|
1517
|
+
if (this.config.autoRefreshToken && ((_b = result.credential) === null || _b === void 0 ? void 0 : _b.refreshToken)) {
|
|
1206
1518
|
this.setupTokenRefresh(targetProvider, result.credential);
|
|
1207
1519
|
}
|
|
1208
1520
|
return result;
|
|
@@ -1212,6 +1524,177 @@ class AuthManagerCore {
|
|
|
1212
1524
|
throw AuthError.fromError(error);
|
|
1213
1525
|
}
|
|
1214
1526
|
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Links an additional auth credential to the current account, delegating to the resolved
|
|
1529
|
+
* provider's optional `linkAccount`. Throws `OPERATION_NOT_ALLOWED` if the provider doesn't
|
|
1530
|
+
* implement it. Mirrors `CapacitorAuthManagerWeb.linkAccount` so React/Vue/Angular consumers
|
|
1531
|
+
* reach the same capability through the `auth` singleton.
|
|
1532
|
+
*/
|
|
1533
|
+
async linkAccount(options) {
|
|
1534
|
+
await this.ensureInitialized();
|
|
1535
|
+
const providerName = typeof options.provider === 'string'
|
|
1536
|
+
? options.provider
|
|
1537
|
+
: AuthProvider[options.provider];
|
|
1538
|
+
const provider = await this.resolveProvider(providerName);
|
|
1539
|
+
if (typeof provider.linkAccount !== 'function') {
|
|
1540
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `linkAccount not supported for ${providerName}`);
|
|
1541
|
+
}
|
|
1542
|
+
try {
|
|
1543
|
+
const result = await provider.linkAccount(options);
|
|
1544
|
+
this.updateState({ user: result.user });
|
|
1545
|
+
return result;
|
|
1546
|
+
}
|
|
1547
|
+
catch (error) {
|
|
1548
|
+
this.logger.error(`Account linking failed for ${providerName}`, error);
|
|
1549
|
+
throw AuthError.fromError(error);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Unlinks a provider credential from the current account via the resolved provider's optional
|
|
1554
|
+
* `unlinkAccount`. Throws `OPERATION_NOT_ALLOWED` if unsupported.
|
|
1555
|
+
*/
|
|
1556
|
+
async unlinkAccount(options) {
|
|
1557
|
+
await this.ensureInitialized();
|
|
1558
|
+
const providerName = typeof options.provider === 'string'
|
|
1559
|
+
? options.provider
|
|
1560
|
+
: AuthProvider[options.provider];
|
|
1561
|
+
const provider = await this.resolveProvider(providerName);
|
|
1562
|
+
if (typeof provider.unlinkAccount !== 'function') {
|
|
1563
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `unlinkAccount not supported for ${providerName}`);
|
|
1564
|
+
}
|
|
1565
|
+
try {
|
|
1566
|
+
await provider.unlinkAccount(options);
|
|
1567
|
+
}
|
|
1568
|
+
catch (error) {
|
|
1569
|
+
this.logger.error(`Account unlinking failed for ${providerName}`, error);
|
|
1570
|
+
throw AuthError.fromError(error);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
/**
|
|
1574
|
+
* Revokes the access/refresh token for a provider (current provider when `provider` is omitted),
|
|
1575
|
+
* delegating to the provider's optional `revokeAccess`. Throws `OPERATION_NOT_ALLOWED` if
|
|
1576
|
+
* unsupported.
|
|
1577
|
+
*/
|
|
1578
|
+
async revokeAccess(token, provider) {
|
|
1579
|
+
await this.ensureInitialized();
|
|
1580
|
+
const targetProvider = provider || this.state.provider;
|
|
1581
|
+
if (!targetProvider) {
|
|
1582
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to revoke access for');
|
|
1583
|
+
}
|
|
1584
|
+
const providerInstance = await this.resolveProvider(targetProvider);
|
|
1585
|
+
if (typeof providerInstance.revokeAccess !== 'function') {
|
|
1586
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `revokeAccess not supported for ${targetProvider}`);
|
|
1587
|
+
}
|
|
1588
|
+
try {
|
|
1589
|
+
await providerInstance.revokeAccess(token);
|
|
1590
|
+
}
|
|
1591
|
+
catch (error) {
|
|
1592
|
+
this.logger.error(`Access revocation failed for ${targetProvider}`, error);
|
|
1593
|
+
throw AuthError.fromError(error);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Returns the current ID token for a provider (current provider when `provider` is omitted) by
|
|
1598
|
+
* delegating to the provider's optional `getIdToken`. Throws `OPERATION_NOT_ALLOWED` if the
|
|
1599
|
+
* provider doesn't issue/expose ID tokens.
|
|
1600
|
+
*/
|
|
1601
|
+
async getIdToken(options) {
|
|
1602
|
+
var _a;
|
|
1603
|
+
await this.ensureInitialized();
|
|
1604
|
+
const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
|
|
1605
|
+
? typeof options.provider === 'string'
|
|
1606
|
+
? options.provider
|
|
1607
|
+
: AuthProvider[options.provider]
|
|
1608
|
+
: undefined) || this.state.provider;
|
|
1609
|
+
if (!targetProvider) {
|
|
1610
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to get an ID token for');
|
|
1611
|
+
}
|
|
1612
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1613
|
+
const getIdTokenFn = provider.getIdToken;
|
|
1614
|
+
if (typeof getIdTokenFn !== 'function') {
|
|
1615
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `getIdToken not supported for ${targetProvider}`);
|
|
1616
|
+
}
|
|
1617
|
+
try {
|
|
1618
|
+
return await getIdTokenFn.call(provider, (_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
|
|
1619
|
+
}
|
|
1620
|
+
catch (error) {
|
|
1621
|
+
this.logger.error(`getIdToken failed for ${targetProvider}`, error);
|
|
1622
|
+
throw AuthError.fromError(error);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* Updates the signed-in user's profile via the current provider's optional `updateProfile`.
|
|
1627
|
+
* Throws `OPERATION_NOT_ALLOWED` if the provider doesn't implement it.
|
|
1628
|
+
*/
|
|
1629
|
+
async updateProfile(options) {
|
|
1630
|
+
await this.ensureInitialized();
|
|
1631
|
+
const targetProvider = this.state.provider;
|
|
1632
|
+
if (!targetProvider) {
|
|
1633
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
|
|
1634
|
+
}
|
|
1635
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1636
|
+
const updateFn = provider.updateProfile;
|
|
1637
|
+
if (typeof updateFn !== 'function') {
|
|
1638
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `updateProfile not supported for ${targetProvider}`);
|
|
1639
|
+
}
|
|
1640
|
+
try {
|
|
1641
|
+
const updatedUser = await updateFn.call(provider, options);
|
|
1642
|
+
this.updateState({ user: updatedUser });
|
|
1643
|
+
return updatedUser;
|
|
1644
|
+
}
|
|
1645
|
+
catch (error) {
|
|
1646
|
+
this.logger.error(`updateProfile failed for ${targetProvider}`, error);
|
|
1647
|
+
throw AuthError.fromError(error);
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Deletes the current account via the provider's optional `deleteAccount` (current provider when
|
|
1652
|
+
* `provider` is omitted), then clears local state. Throws `OPERATION_NOT_ALLOWED` if the provider
|
|
1653
|
+
* doesn't implement it.
|
|
1654
|
+
*/
|
|
1655
|
+
async deleteAccount(options) {
|
|
1656
|
+
await this.ensureInitialized();
|
|
1657
|
+
const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
|
|
1658
|
+
? typeof options.provider === 'string'
|
|
1659
|
+
? options.provider
|
|
1660
|
+
: AuthProvider[options.provider]
|
|
1661
|
+
: undefined) || this.state.provider;
|
|
1662
|
+
if (!targetProvider) {
|
|
1663
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
|
|
1664
|
+
}
|
|
1665
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1666
|
+
const deleteFn = provider.deleteAccount;
|
|
1667
|
+
if (typeof deleteFn !== 'function') {
|
|
1668
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
|
|
1669
|
+
}
|
|
1670
|
+
try {
|
|
1671
|
+
await deleteFn.call(provider);
|
|
1672
|
+
// Account deleted server-side: clear local session + timers.
|
|
1673
|
+
this.clearTokenRefresh(targetProvider);
|
|
1674
|
+
this.updateState({
|
|
1675
|
+
user: null,
|
|
1676
|
+
isAuthenticated: false,
|
|
1677
|
+
provider: null,
|
|
1678
|
+
});
|
|
1679
|
+
await this.storage.remove('auth_state');
|
|
1680
|
+
}
|
|
1681
|
+
catch (error) {
|
|
1682
|
+
this.logger.error(`deleteAccount failed for ${targetProvider}`, error);
|
|
1683
|
+
throw AuthError.fromError(error);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Whether a provider has been supplied to `configure()`/`initialize()`. Public accessor so
|
|
1688
|
+
* adapters (React/Vue/Angular) no longer reach into the private `config` via `as any`.
|
|
1689
|
+
*/
|
|
1690
|
+
isProviderConfigured(name) {
|
|
1691
|
+
var _a;
|
|
1692
|
+
return !!((_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name]);
|
|
1693
|
+
}
|
|
1694
|
+
/** Names of every provider supplied to `configure()`/`initialize()`. */
|
|
1695
|
+
getConfiguredProviders() {
|
|
1696
|
+
return this.config.providers ? Object.keys(this.config.providers) : [];
|
|
1697
|
+
}
|
|
1215
1698
|
onAuthStateChange(listener) {
|
|
1216
1699
|
// Immediately call with current state
|
|
1217
1700
|
listener(this.getAuthState());
|
|
@@ -1233,6 +1716,18 @@ class AuthManagerCore {
|
|
|
1233
1716
|
await this.initialize();
|
|
1234
1717
|
}
|
|
1235
1718
|
}
|
|
1719
|
+
getProviderDeps() {
|
|
1720
|
+
return { storage: this.storage, logger: this.logger };
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Resolves a provider instance through the registry, threading the configured options and the
|
|
1724
|
+
* manager's shared storage/logger. Shared by the capability methods (link/unlink/revoke/
|
|
1725
|
+
* getIdToken/updateProfile/deleteAccount).
|
|
1726
|
+
*/
|
|
1727
|
+
async resolveProvider(name) {
|
|
1728
|
+
var _a;
|
|
1729
|
+
return ProviderRegistry.getProvider(name, (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name], this.getProviderDeps());
|
|
1730
|
+
}
|
|
1236
1731
|
updateState(partial) {
|
|
1237
1732
|
this.state = Object.assign(Object.assign({}, this.state), partial);
|
|
1238
1733
|
this.stateEmitter.emit(this.state);
|
|
@@ -1246,7 +1741,7 @@ class AuthManagerCore {
|
|
|
1246
1741
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
|
|
1247
1742
|
if (providerConfig) {
|
|
1248
1743
|
try {
|
|
1249
|
-
const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig);
|
|
1744
|
+
const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
|
|
1250
1745
|
const currentUser = await provider.getCurrentUser();
|
|
1251
1746
|
if (currentUser) {
|
|
1252
1747
|
this.updateState({
|
|
@@ -1280,16 +1775,35 @@ class AuthManagerCore {
|
|
|
1280
1775
|
const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
|
|
1281
1776
|
const refreshTime = credential.expiresAt - buffer - Date.now();
|
|
1282
1777
|
if (refreshTime > 0) {
|
|
1283
|
-
|
|
1778
|
+
this.scheduleRefresh(provider, refreshTime, credential);
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
|
|
1783
|
+
* (2,147,483,647 ms ≈ 24.8 days). Without clamping, a far-future `expiresAt` overflows the
|
|
1784
|
+
* timer and fires almost immediately, causing a refresh storm. When clamped, the timer simply
|
|
1785
|
+
* re-schedules the remaining wait on fire instead of refreshing early.
|
|
1786
|
+
*/
|
|
1787
|
+
scheduleRefresh(provider, delayMs, credential) {
|
|
1788
|
+
const MAX_TIMEOUT = 2147483647;
|
|
1789
|
+
const clamped = Math.min(delayMs, MAX_TIMEOUT);
|
|
1790
|
+
const timer = setTimeout(() => {
|
|
1791
|
+
const remaining = delayMs - clamped;
|
|
1792
|
+
if (remaining > 0) {
|
|
1793
|
+
// We hit the clamp ceiling — reschedule the rest rather than refreshing prematurely.
|
|
1794
|
+
this.scheduleRefresh(provider, remaining, credential);
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
void (async () => {
|
|
1284
1798
|
try {
|
|
1285
1799
|
await this.refreshToken(provider);
|
|
1286
1800
|
}
|
|
1287
1801
|
catch (error) {
|
|
1288
1802
|
this.logger.error(`Auto token refresh failed for ${provider}`, error);
|
|
1289
1803
|
}
|
|
1290
|
-
}
|
|
1291
|
-
|
|
1292
|
-
|
|
1804
|
+
})();
|
|
1805
|
+
}, clamped);
|
|
1806
|
+
this.tokenRefreshTimers.set(provider, timer);
|
|
1293
1807
|
}
|
|
1294
1808
|
clearTokenRefresh(provider) {
|
|
1295
1809
|
const timer = this.tokenRefreshTimers.get(provider);
|
|
@@ -1298,6 +1812,13 @@ class AuthManagerCore {
|
|
|
1298
1812
|
this.tokenRefreshTimers.delete(provider);
|
|
1299
1813
|
}
|
|
1300
1814
|
}
|
|
1815
|
+
/** Clears every active refresh timer (used on a global, untargeted sign-out). */
|
|
1816
|
+
clearAllTokenRefresh() {
|
|
1817
|
+
for (const timer of this.tokenRefreshTimers.values()) {
|
|
1818
|
+
clearTimeout(timer);
|
|
1819
|
+
}
|
|
1820
|
+
this.tokenRefreshTimers.clear();
|
|
1821
|
+
}
|
|
1301
1822
|
dispose() {
|
|
1302
1823
|
// Clear all timers
|
|
1303
1824
|
for (const timer of this.tokenRefreshTimers.values()) {
|
|
@@ -1313,6 +1834,31 @@ class AuthManagerCore {
|
|
|
1313
1834
|
// Create singleton instance
|
|
1314
1835
|
const auth = new AuthManagerCore();
|
|
1315
1836
|
|
|
1837
|
+
/**
|
|
1838
|
+
* Normalize a provider constructor argument into a full {@link BaseProviderConfig}.
|
|
1839
|
+
*
|
|
1840
|
+
* The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
|
|
1841
|
+
* get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
|
|
1842
|
+
* tests and direct consumers pass the provider's own bare options object. This helper accepts
|
|
1843
|
+
* either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`, so it never
|
|
1844
|
+
* touches `window` and stays safe under SSR / Node test environments) plus the shared
|
|
1845
|
+
* {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
|
|
1846
|
+
*/
|
|
1847
|
+
function resolveProviderConfig(provider, input) {
|
|
1848
|
+
if (typeof input === 'object' &&
|
|
1849
|
+
input !== null &&
|
|
1850
|
+
'storage' in input &&
|
|
1851
|
+
'logger' in input &&
|
|
1852
|
+
'options' in input) {
|
|
1853
|
+
return input;
|
|
1854
|
+
}
|
|
1855
|
+
return {
|
|
1856
|
+
provider,
|
|
1857
|
+
options: (input !== null && input !== void 0 ? input : {}),
|
|
1858
|
+
storage: new WebStorage(AuthPersistence.NONE),
|
|
1859
|
+
logger: defaultLogger,
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1316
1862
|
class BaseAuthProvider {
|
|
1317
1863
|
get name() {
|
|
1318
1864
|
return this.provider;
|
|
@@ -1327,6 +1873,19 @@ class BaseAuthProvider {
|
|
|
1327
1873
|
this.persistence = config.persistence || AuthPersistence.LOCAL;
|
|
1328
1874
|
this.authStateEmitter = new EventEmitter();
|
|
1329
1875
|
}
|
|
1876
|
+
// Capability methods with concrete defaults: providers that support these operations override
|
|
1877
|
+
// them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
|
|
1878
|
+
// across every provider (see AuthProviderInterface, where they are optional). Marking them
|
|
1879
|
+
// abstract previously forced every subclass to re-implement them just to throw.
|
|
1880
|
+
async linkAccount(_options) {
|
|
1881
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking is not supported by provider ${this.provider}`, this.provider);
|
|
1882
|
+
}
|
|
1883
|
+
async unlinkAccount(_options) {
|
|
1884
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking is not supported by provider ${this.provider}`, this.provider);
|
|
1885
|
+
}
|
|
1886
|
+
async revokeAccess(_token) {
|
|
1887
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation is not supported by provider ${this.provider}`, this.provider);
|
|
1888
|
+
}
|
|
1330
1889
|
async getCurrentUser() {
|
|
1331
1890
|
if (!this.isInitialized) {
|
|
1332
1891
|
await this.initialize();
|
|
@@ -1404,7 +1963,19 @@ class BaseAuthProvider {
|
|
|
1404
1963
|
};
|
|
1405
1964
|
}
|
|
1406
1965
|
generateUniqueId() {
|
|
1407
|
-
|
|
1966
|
+
// Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
|
|
1967
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
1968
|
+
return crypto.randomUUID();
|
|
1969
|
+
}
|
|
1970
|
+
const bytes = new Uint8Array(16);
|
|
1971
|
+
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
|
|
1972
|
+
crypto.getRandomValues(bytes);
|
|
1973
|
+
}
|
|
1974
|
+
let hex = '';
|
|
1975
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
1976
|
+
hex += bytes[i].toString(16).padStart(2, '0');
|
|
1977
|
+
}
|
|
1978
|
+
return `${Date.now()}-${hex}`;
|
|
1408
1979
|
}
|
|
1409
1980
|
isTokenExpired(expiresAt) {
|
|
1410
1981
|
if (!expiresAt)
|
|
@@ -1432,11 +2003,26 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1432
2003
|
// Generate state and nonce for security
|
|
1433
2004
|
const state = this.generateSecureRandomString();
|
|
1434
2005
|
const nonce = this.generateSecureRandomString();
|
|
1435
|
-
//
|
|
2006
|
+
// PKCE (RFC 7636) — default on; requires Web Crypto 'subtle' (HTTPS / localhost).
|
|
2007
|
+
let codeVerifier;
|
|
2008
|
+
let codeChallenge;
|
|
2009
|
+
if (config.pkceEnabled !== false) {
|
|
2010
|
+
if (typeof crypto !== 'undefined' && crypto.subtle) {
|
|
2011
|
+
codeVerifier = this.generateCodeVerifier();
|
|
2012
|
+
codeChallenge = await this.generateCodeChallenge(codeVerifier);
|
|
2013
|
+
}
|
|
2014
|
+
else {
|
|
2015
|
+
this.logger.warn(`PKCE skipped for ${this.provider}: Web Crypto 'subtle' is unavailable (insecure context). Serve over HTTPS to enable PKCE.`);
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
// Store state, nonce, and PKCE verifier for validation
|
|
1436
2019
|
await this.storage.set(`${this.provider}_oauth_state`, state);
|
|
1437
2020
|
await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
|
|
2021
|
+
if (codeVerifier) {
|
|
2022
|
+
await this.storage.set(`${this.provider}_oauth_verifier`, codeVerifier);
|
|
2023
|
+
}
|
|
1438
2024
|
// Build authorization URL
|
|
1439
|
-
const authUrl = this.buildAuthorizationUrl(config, state, nonce, options);
|
|
2025
|
+
const authUrl = this.buildAuthorizationUrl(config, state, nonce, options, codeChallenge);
|
|
1440
2026
|
// Perform the OAuth flow (platform-specific implementation)
|
|
1441
2027
|
const authResponse = await this.openAuthorizationUrl(authUrl);
|
|
1442
2028
|
// Validate response
|
|
@@ -1445,7 +2031,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1445
2031
|
if (!authResponse.code) {
|
|
1446
2032
|
throw new AuthError(AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
|
|
1447
2033
|
}
|
|
1448
|
-
const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
|
|
2034
|
+
const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config, codeVerifier);
|
|
2035
|
+
// Validate the ID token's nonce + expiry (replay protection). NOTE: the signature is
|
|
2036
|
+
// NOT verified client-side — always re-validate ID tokens on your backend.
|
|
2037
|
+
this.validateIdToken(tokenResponse.id_token, nonce);
|
|
1449
2038
|
// Parse user information
|
|
1450
2039
|
const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
|
|
1451
2040
|
// Create AuthUser and AuthCredential
|
|
@@ -1464,31 +2053,47 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1464
2053
|
// Clean up temporary storage
|
|
1465
2054
|
await this.storage.remove(`${this.provider}_oauth_state`);
|
|
1466
2055
|
await this.storage.remove(`${this.provider}_oauth_nonce`);
|
|
2056
|
+
await this.storage.remove(`${this.provider}_oauth_verifier`);
|
|
1467
2057
|
}
|
|
1468
2058
|
}
|
|
1469
|
-
buildAuthorizationUrl(config, state, nonce, options) {
|
|
2059
|
+
buildAuthorizationUrl(config, state, nonce, options, codeChallenge) {
|
|
1470
2060
|
var _a, _b, _c, _d;
|
|
1471
|
-
const params = new URLSearchParams(
|
|
1472
|
-
|
|
1473
|
-
//
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
2061
|
+
const params = new URLSearchParams();
|
|
2062
|
+
// Developer-supplied params FIRST, so the security-critical params set below cannot be
|
|
2063
|
+
// overridden by additionalParams / customParameters.
|
|
2064
|
+
if (config.additionalParams) {
|
|
2065
|
+
for (const [key, value] of Object.entries(config.additionalParams)) {
|
|
2066
|
+
params.set(key, value);
|
|
2067
|
+
}
|
|
1477
2068
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
Object.entries(options.options.customParameters).forEach(([key, value]) => {
|
|
2069
|
+
if ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.customParameters) {
|
|
2070
|
+
for (const [key, value] of Object.entries(options.options.customParameters)) {
|
|
1481
2071
|
params.set(key, value);
|
|
1482
|
-
}
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
// Scopes
|
|
2075
|
+
const scopes = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.scopes) || config.scopes || [];
|
|
2076
|
+
if (scopes.length > 0) {
|
|
2077
|
+
params.set('scope', scopes.join(' '));
|
|
1483
2078
|
}
|
|
1484
|
-
//
|
|
2079
|
+
// Login hint / prompt
|
|
1485
2080
|
if ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) {
|
|
1486
2081
|
params.set('login_hint', options.options.loginHint);
|
|
1487
2082
|
}
|
|
1488
|
-
// Add prompt if provided
|
|
1489
2083
|
if ((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) {
|
|
1490
2084
|
params.set('prompt', options.options.prompt);
|
|
1491
2085
|
}
|
|
2086
|
+
// Security-critical parameters — set LAST so custom params cannot override them.
|
|
2087
|
+
params.set('client_id', config.clientId);
|
|
2088
|
+
params.set('redirect_uri', config.redirectUri);
|
|
2089
|
+
params.set('response_type', config.responseType || 'code');
|
|
2090
|
+
params.set('state', state);
|
|
2091
|
+
params.set('nonce', nonce);
|
|
2092
|
+
if (codeChallenge) {
|
|
2093
|
+
params.set('code_challenge', codeChallenge);
|
|
2094
|
+
params.set('code_challenge_method', 'S256');
|
|
2095
|
+
}
|
|
2096
|
+
this.assertSecureEndpoint(config.authorizationEndpoint);
|
|
1492
2097
|
return `${config.authorizationEndpoint}?${params.toString()}`;
|
|
1493
2098
|
}
|
|
1494
2099
|
async validateOAuthResponse(response, expectedState, _expectedNonce) {
|
|
@@ -1500,16 +2105,21 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1500
2105
|
}
|
|
1501
2106
|
// Nonce validation is done after ID token is received
|
|
1502
2107
|
}
|
|
1503
|
-
async exchangeCodeForTokens(code, config) {
|
|
2108
|
+
async exchangeCodeForTokens(code, config, codeVerifier) {
|
|
1504
2109
|
const params = new URLSearchParams({
|
|
1505
2110
|
grant_type: config.grantType || 'authorization_code',
|
|
1506
2111
|
code,
|
|
1507
2112
|
redirect_uri: config.redirectUri,
|
|
1508
2113
|
client_id: config.clientId,
|
|
1509
2114
|
});
|
|
2115
|
+
if (codeVerifier) {
|
|
2116
|
+
params.set('code_verifier', codeVerifier);
|
|
2117
|
+
}
|
|
1510
2118
|
if (config.clientSecret) {
|
|
2119
|
+
this.warnClientSecretInBrowser();
|
|
1511
2120
|
params.set('client_secret', config.clientSecret);
|
|
1512
2121
|
}
|
|
2122
|
+
this.assertSecureEndpoint(config.tokenEndpoint);
|
|
1513
2123
|
try {
|
|
1514
2124
|
const response = await fetch(config.tokenEndpoint, {
|
|
1515
2125
|
method: 'POST',
|
|
@@ -1546,8 +2156,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1546
2156
|
client_id: config.clientId,
|
|
1547
2157
|
});
|
|
1548
2158
|
if (config.clientSecret) {
|
|
2159
|
+
this.warnClientSecretInBrowser();
|
|
1549
2160
|
params.set('client_secret', config.clientSecret);
|
|
1550
2161
|
}
|
|
2162
|
+
this.assertSecureEndpoint(config.tokenEndpoint);
|
|
1551
2163
|
const response = await fetch(config.tokenEndpoint, {
|
|
1552
2164
|
method: 'POST',
|
|
1553
2165
|
headers: {
|
|
@@ -1594,8 +2206,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1594
2206
|
client_id: config.clientId,
|
|
1595
2207
|
});
|
|
1596
2208
|
if (config.clientSecret) {
|
|
2209
|
+
this.warnClientSecretInBrowser();
|
|
1597
2210
|
params.set('client_secret', config.clientSecret);
|
|
1598
2211
|
}
|
|
2212
|
+
this.assertSecureEndpoint(config.revokeEndpoint);
|
|
1599
2213
|
await fetch(config.revokeEndpoint, {
|
|
1600
2214
|
method: 'POST',
|
|
1601
2215
|
headers: {
|
|
@@ -1682,6 +2296,80 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1682
2296
|
}
|
|
1683
2297
|
return result;
|
|
1684
2298
|
}
|
|
2299
|
+
/** RFC 7636 PKCE code verifier: 64 chars from the unreserved set [A-Za-z0-9]. */
|
|
2300
|
+
generateCodeVerifier() {
|
|
2301
|
+
return this.generateSecureRandomString(64);
|
|
2302
|
+
}
|
|
2303
|
+
/** Derives the S256 PKCE code challenge: base64url(SHA-256(verifier)). */
|
|
2304
|
+
async generateCodeChallenge(verifier) {
|
|
2305
|
+
const data = new TextEncoder().encode(verifier);
|
|
2306
|
+
const digest = await crypto.subtle.digest('SHA-256', data);
|
|
2307
|
+
return this.base64UrlEncode(new Uint8Array(digest));
|
|
2308
|
+
}
|
|
2309
|
+
base64UrlEncode(bytes) {
|
|
2310
|
+
let binary = '';
|
|
2311
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2312
|
+
binary += String.fromCharCode(bytes[i]);
|
|
2313
|
+
}
|
|
2314
|
+
return btoa(binary)
|
|
2315
|
+
.replace(/\+/g, '-')
|
|
2316
|
+
.replace(/\//g, '_')
|
|
2317
|
+
.replace(/=+$/, '');
|
|
2318
|
+
}
|
|
2319
|
+
/** Decodes a JWT payload without verifying the signature. Returns null if malformed. */
|
|
2320
|
+
decodeJwtPayload(token) {
|
|
2321
|
+
try {
|
|
2322
|
+
const parts = token.split('.');
|
|
2323
|
+
if (parts.length < 2) {
|
|
2324
|
+
return null;
|
|
2325
|
+
}
|
|
2326
|
+
let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
2327
|
+
const pad = payload.length % 4;
|
|
2328
|
+
if (pad) {
|
|
2329
|
+
payload += '='.repeat(4 - pad);
|
|
2330
|
+
}
|
|
2331
|
+
return JSON.parse(atob(payload));
|
|
2332
|
+
}
|
|
2333
|
+
catch (_a) {
|
|
2334
|
+
return null;
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
/**
|
|
2338
|
+
* Validates the ID token's nonce (replay protection) and expiry. The signature is NOT
|
|
2339
|
+
* verified client-side — always re-validate ID tokens on your backend before trusting them.
|
|
2340
|
+
*/
|
|
2341
|
+
validateIdToken(idToken, expectedNonce) {
|
|
2342
|
+
if (!idToken) {
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
const payload = this.decodeJwtPayload(idToken);
|
|
2346
|
+
if (!payload) {
|
|
2347
|
+
return;
|
|
2348
|
+
}
|
|
2349
|
+
if (payload.nonce !== undefined && payload.nonce !== expectedNonce) {
|
|
2350
|
+
throw new AuthError(AuthErrorCode.INVALID_NONCE, 'OIDC nonce mismatch in ID token', this.provider);
|
|
2351
|
+
}
|
|
2352
|
+
if (typeof payload.exp === 'number' && payload.exp * 1000 < Date.now()) {
|
|
2353
|
+
throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'ID token is expired', this.provider);
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
warnClientSecretInBrowser() {
|
|
2357
|
+
this.logger.warn(`${this.provider}: a client secret was supplied to a browser-facing provider. Secrets ` +
|
|
2358
|
+
`placed in client config ship in the JS bundle and are recoverable by end users. Use a ` +
|
|
2359
|
+
`backend token-exchange proxy (set tokenEndpoint to your server) instead.`);
|
|
2360
|
+
}
|
|
2361
|
+
assertSecureEndpoint(url) {
|
|
2362
|
+
try {
|
|
2363
|
+
const parsed = new URL(url);
|
|
2364
|
+
const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
|
|
2365
|
+
if (parsed.protocol !== 'https:' && !isLocalhost) {
|
|
2366
|
+
this.logger.warn(`${this.provider}: endpoint ${url} is not HTTPS — credentials/tokens may be sent in cleartext.`);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
catch (_a) {
|
|
2370
|
+
// Malformed URL: let the subsequent fetch surface the error.
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
1685
2373
|
}
|
|
1686
2374
|
|
|
1687
2375
|
class GoogleAuthProviderWeb extends OAuthProvider {
|
|
@@ -2040,8 +2728,8 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2040
2728
|
const response = await window.AppleID.auth.signIn(signInConfig);
|
|
2041
2729
|
// Validate response
|
|
2042
2730
|
await this.validateAppleResponse(response, state, nonce);
|
|
2043
|
-
// Parse user information from response
|
|
2044
|
-
const user = this.createAppleAuthUser(response);
|
|
2731
|
+
// Parse user information from response (validates ID token nonce + expiry first)
|
|
2732
|
+
const user = this.createAppleAuthUser(response, nonce);
|
|
2045
2733
|
const credential = this.createAppleCredential(response);
|
|
2046
2734
|
// Save user and credential
|
|
2047
2735
|
await this.setCurrentUser(user);
|
|
@@ -2075,6 +2763,12 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2075
2763
|
throw AuthError.fromError(error, this.provider);
|
|
2076
2764
|
}
|
|
2077
2765
|
}
|
|
2766
|
+
async refreshToken(_options) {
|
|
2767
|
+
// Apple's JS (web) Sign In flow never issues a refresh token, so the inherited
|
|
2768
|
+
// OAuthProvider.refreshToken() would fail with a confusing "No refresh token available".
|
|
2769
|
+
// Surface an explicit, accurate error instead: callers must re-authenticate.
|
|
2770
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Apple web sign-in does not issue refresh tokens; re-authenticate instead.', this.provider);
|
|
2771
|
+
}
|
|
2078
2772
|
async isSupported() {
|
|
2079
2773
|
// Check if we're in a browser environment
|
|
2080
2774
|
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
@@ -2155,19 +2849,29 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2155
2849
|
// ID token validation with nonce would be done here
|
|
2156
2850
|
// For production, you should validate the ID token on your backend
|
|
2157
2851
|
}
|
|
2158
|
-
createAppleAuthUser(response) {
|
|
2852
|
+
createAppleAuthUser(response, expectedNonce) {
|
|
2159
2853
|
var _a, _b, _c;
|
|
2160
2854
|
const user = response.user || {};
|
|
2161
2855
|
const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
|
|
2162
|
-
//
|
|
2856
|
+
// Validate the ID token's nonce (replay protection) and expiry BEFORE trusting any
|
|
2857
|
+
// claims. The signature is NOT verified client-side — always re-validate on your backend.
|
|
2858
|
+
// Defensive: only enforce the nonce when both an expected nonce and a token nonce exist.
|
|
2163
2859
|
let claims = {};
|
|
2164
2860
|
if (idToken) {
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
claims =
|
|
2861
|
+
const payload = this.decodeJwtPayload(idToken);
|
|
2862
|
+
if (payload) {
|
|
2863
|
+
claims = payload;
|
|
2864
|
+
if (expectedNonce &&
|
|
2865
|
+
claims.nonce !== undefined &&
|
|
2866
|
+
claims.nonce !== expectedNonce) {
|
|
2867
|
+
throw new AuthError(AuthErrorCode.INVALID_NONCE, 'Apple ID token nonce does not match the expected value', this.provider);
|
|
2868
|
+
}
|
|
2869
|
+
if (typeof claims.exp === 'number' && claims.exp * 1000 < Date.now()) {
|
|
2870
|
+
throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Apple ID token is expired', this.provider);
|
|
2871
|
+
}
|
|
2168
2872
|
}
|
|
2169
|
-
|
|
2170
|
-
this.logger.error('Failed to
|
|
2873
|
+
else {
|
|
2874
|
+
this.logger.error('Failed to decode Apple ID token payload');
|
|
2171
2875
|
}
|
|
2172
2876
|
}
|
|
2173
2877
|
return {
|
|
@@ -2240,11 +2944,16 @@ var appleProvider = /*#__PURE__*/Object.freeze({
|
|
|
2240
2944
|
class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
2241
2945
|
constructor() {
|
|
2242
2946
|
super(...arguments);
|
|
2947
|
+
this.msalConfig = {};
|
|
2243
2948
|
this.clientId = '';
|
|
2244
2949
|
this.authority = '';
|
|
2245
2950
|
this.redirectUri = '';
|
|
2246
2951
|
this.scopes = [];
|
|
2247
2952
|
}
|
|
2953
|
+
/** Reads the host-page MSAL SDK, casting the `window` boundary exactly once. */
|
|
2954
|
+
getMsal() {
|
|
2955
|
+
return window.msal;
|
|
2956
|
+
}
|
|
2248
2957
|
async initialize() {
|
|
2249
2958
|
const options = this.options;
|
|
2250
2959
|
if (!options.clientId) {
|
|
@@ -2256,7 +2965,7 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2256
2965
|
this.redirectUri = options.redirectUri || window.location.origin;
|
|
2257
2966
|
this.scopes = options.scopes || ['openid', 'profile', 'email'];
|
|
2258
2967
|
// Check if MSAL is available
|
|
2259
|
-
const msal =
|
|
2968
|
+
const msal = this.getMsal();
|
|
2260
2969
|
if (!msal) {
|
|
2261
2970
|
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Microsoft Authentication Library (MSAL) is not loaded. Please include the MSAL script in your HTML.', this.provider);
|
|
2262
2971
|
}
|
|
@@ -2303,9 +3012,22 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2303
3012
|
}
|
|
2304
3013
|
}
|
|
2305
3014
|
async signIn(options) {
|
|
3015
|
+
var _a, _b, _c, _d;
|
|
2306
3016
|
this.validateInitialized();
|
|
2307
3017
|
try {
|
|
2308
|
-
|
|
3018
|
+
// Build the MSAL login request EXPLICITLY from the standard options shape — spreading
|
|
3019
|
+
// raw `options` here would leak junk (provider, credentials, …) into MSAL and ignore
|
|
3020
|
+
// per-sign-in scopes. Honour per-call scopes/loginHint/prompt, fall back to configured
|
|
3021
|
+
// scopes, and omit undefined keys.
|
|
3022
|
+
const loginRequest = {
|
|
3023
|
+
scopes: (_b = (_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : this.scopes,
|
|
3024
|
+
};
|
|
3025
|
+
if (((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) !== undefined) {
|
|
3026
|
+
loginRequest.loginHint = options.options.loginHint;
|
|
3027
|
+
}
|
|
3028
|
+
if (((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) !== undefined) {
|
|
3029
|
+
loginRequest.prompt = options.options.prompt;
|
|
3030
|
+
}
|
|
2309
3031
|
// Try popup first, fallback to redirect
|
|
2310
3032
|
let response;
|
|
2311
3033
|
try {
|
|
@@ -2324,10 +3046,11 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2324
3046
|
}
|
|
2325
3047
|
catch (error) {
|
|
2326
3048
|
this.logger.error('Microsoft sign in failed', error);
|
|
2327
|
-
|
|
3049
|
+
const err = error;
|
|
3050
|
+
if (err.errorCode === 'user_cancelled') {
|
|
2328
3051
|
throw new AuthError(AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
|
|
2329
3052
|
}
|
|
2330
|
-
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${
|
|
3053
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${err.message}`, this.provider);
|
|
2331
3054
|
}
|
|
2332
3055
|
}
|
|
2333
3056
|
async signOut(options) {
|
|
@@ -2373,15 +3096,16 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2373
3096
|
}
|
|
2374
3097
|
catch (error) {
|
|
2375
3098
|
this.logger.error('Token refresh failed', error);
|
|
2376
|
-
|
|
3099
|
+
const err = error;
|
|
3100
|
+
if (err.errorCode === 'interaction_required') {
|
|
2377
3101
|
// Need user interaction, trigger sign in
|
|
2378
3102
|
return await this.signIn();
|
|
2379
3103
|
}
|
|
2380
|
-
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${
|
|
3104
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${err.message}`, this.provider);
|
|
2381
3105
|
}
|
|
2382
3106
|
}
|
|
2383
3107
|
async isSupported() {
|
|
2384
|
-
return typeof window !== 'undefined' && !!
|
|
3108
|
+
return typeof window !== 'undefined' && !!this.getMsal();
|
|
2385
3109
|
}
|
|
2386
3110
|
async linkAccount() {
|
|
2387
3111
|
// Microsoft doesn't support account linking in the same way
|
|
@@ -2411,32 +3135,37 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2411
3135
|
scope: response.scopes.join(' '),
|
|
2412
3136
|
};
|
|
2413
3137
|
await this.saveCredential(credential);
|
|
2414
|
-
return this.createAuthResult(user, credential, ((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser)
|
|
3138
|
+
return this.createAuthResult(user, credential, Boolean((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser));
|
|
2415
3139
|
}
|
|
2416
3140
|
createUserFromMSALAccount(account) {
|
|
2417
3141
|
const idTokenClaims = account.idTokenClaims || {};
|
|
3142
|
+
const claim = (key) => {
|
|
3143
|
+
const value = idTokenClaims[key];
|
|
3144
|
+
return typeof value === 'string' ? value : undefined;
|
|
3145
|
+
};
|
|
3146
|
+
const iat = idTokenClaims.iat;
|
|
2418
3147
|
return {
|
|
2419
|
-
uid: account.localAccountId || account.homeAccountId,
|
|
2420
|
-
email:
|
|
3148
|
+
uid: account.localAccountId || account.homeAccountId || '',
|
|
3149
|
+
email: claim('email') || account.username || null,
|
|
2421
3150
|
emailVerified: !!idTokenClaims.email_verified,
|
|
2422
|
-
displayName: account.name ||
|
|
2423
|
-
photoURL:
|
|
2424
|
-
phoneNumber:
|
|
3151
|
+
displayName: account.name || claim('name') || null,
|
|
3152
|
+
photoURL: claim('picture') || null,
|
|
3153
|
+
phoneNumber: claim('phone_number') || null,
|
|
2425
3154
|
isAnonymous: false,
|
|
2426
|
-
tenantId: account.tenantId,
|
|
3155
|
+
tenantId: account.tenantId || null,
|
|
2427
3156
|
providerData: [
|
|
2428
3157
|
{
|
|
2429
3158
|
providerId: this.provider,
|
|
2430
|
-
uid: account.localAccountId,
|
|
2431
|
-
displayName: account.name,
|
|
2432
|
-
email: account.username,
|
|
3159
|
+
uid: account.localAccountId || '',
|
|
3160
|
+
displayName: account.name || null,
|
|
3161
|
+
email: account.username || null,
|
|
2433
3162
|
phoneNumber: null,
|
|
2434
|
-
photoURL:
|
|
3163
|
+
photoURL: claim('picture') || null,
|
|
2435
3164
|
},
|
|
2436
3165
|
],
|
|
2437
3166
|
metadata: {
|
|
2438
|
-
creationTime:
|
|
2439
|
-
? new Date(
|
|
3167
|
+
creationTime: typeof iat === 'number'
|
|
3168
|
+
? new Date(iat * 1000).toISOString()
|
|
2440
3169
|
: undefined,
|
|
2441
3170
|
lastSignInTime: new Date().toISOString(),
|
|
2442
3171
|
},
|
|
@@ -2534,7 +3263,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
|
|
|
2534
3263
|
checkLoginStatus() {
|
|
2535
3264
|
return new Promise((resolve) => {
|
|
2536
3265
|
window.FB.getLoginStatus(async (response) => {
|
|
2537
|
-
if (response.status === 'connected') {
|
|
3266
|
+
if (response.status === 'connected' && response.authResponse) {
|
|
2538
3267
|
await this.handleAuthResponse(response.authResponse);
|
|
2539
3268
|
}
|
|
2540
3269
|
resolve();
|
|
@@ -2589,7 +3318,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
|
|
|
2589
3318
|
// Facebook access tokens are short-lived and need to be refreshed via re-authentication
|
|
2590
3319
|
return new Promise((resolve, reject) => {
|
|
2591
3320
|
window.FB.getLoginStatus(async (response) => {
|
|
2592
|
-
if (response.status === 'connected') {
|
|
3321
|
+
if (response.status === 'connected' && response.authResponse) {
|
|
2593
3322
|
try {
|
|
2594
3323
|
const result = await this.handleAuthResponse(response.authResponse, true);
|
|
2595
3324
|
resolve(result);
|
|
@@ -2709,6 +3438,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2709
3438
|
this.scopes = [];
|
|
2710
3439
|
this.authWindow = null;
|
|
2711
3440
|
this.authPromise = null;
|
|
3441
|
+
/** Bound 'message' handler reference so it can be removed in dispose(). */
|
|
3442
|
+
this.boundAuthMessageHandler = null;
|
|
3443
|
+
/** Active popup-closed polling interval, tracked so it is cleared on every exit path. */
|
|
3444
|
+
this.popupCheckInterval = null;
|
|
3445
|
+
/** CSRF state from the most recent sign-in, forwarded to the proxy for re-verification. */
|
|
3446
|
+
this.lastState = null;
|
|
2712
3447
|
}
|
|
2713
3448
|
async initialize() {
|
|
2714
3449
|
const options = this.options;
|
|
@@ -2719,8 +3454,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2719
3454
|
this.redirectUri =
|
|
2720
3455
|
options.redirectUri || window.location.origin + '/auth/github/callback';
|
|
2721
3456
|
this.scopes = options.scopes || ['read:user', 'user:email'];
|
|
2722
|
-
|
|
2723
|
-
|
|
3457
|
+
this.tokenExchangeProxy =
|
|
3458
|
+
options.tokenExchangeProxy || options.tokenEndpoint;
|
|
3459
|
+
// Set up message listener for OAuth callback. Keep the bound reference so the exact
|
|
3460
|
+
// same function can be removed in dispose() (a fresh `.bind()` would not match).
|
|
3461
|
+
this.boundAuthMessageHandler = this.handleAuthMessage.bind(this);
|
|
3462
|
+
window.addEventListener('message', this.boundAuthMessageHandler);
|
|
2724
3463
|
// Check for stored session
|
|
2725
3464
|
await this.loadCurrentUser();
|
|
2726
3465
|
this.isInitialized = true;
|
|
@@ -2731,6 +3470,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2731
3470
|
return new Promise((resolve, reject) => {
|
|
2732
3471
|
this.authPromise = { resolve, reject };
|
|
2733
3472
|
const state = this.generateState();
|
|
3473
|
+
this.lastState = state;
|
|
2734
3474
|
const authUrl = this.buildAuthUrl(state);
|
|
2735
3475
|
// Open GitHub OAuth in a popup window
|
|
2736
3476
|
const width = 600;
|
|
@@ -2743,11 +3483,13 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2743
3483
|
reject(new AuthError(AuthErrorCode.POPUP_BLOCKED, 'Popup window was blocked. Please allow popups for this site.', this.provider));
|
|
2744
3484
|
return;
|
|
2745
3485
|
}
|
|
2746
|
-
// Check if popup is closed
|
|
2747
|
-
|
|
3486
|
+
// Check if popup is closed. Track the interval so the success path
|
|
3487
|
+
// (handleAuthMessage) and dispose() can also clear it — otherwise it leaks.
|
|
3488
|
+
this.clearPopupCheckInterval();
|
|
3489
|
+
this.popupCheckInterval = setInterval(() => {
|
|
2748
3490
|
var _a;
|
|
2749
3491
|
if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
|
|
2750
|
-
|
|
3492
|
+
this.clearPopupCheckInterval();
|
|
2751
3493
|
if (this.authPromise) {
|
|
2752
3494
|
this.authPromise = null;
|
|
2753
3495
|
reject(new AuthError(AuthErrorCode.USER_CANCELLED, 'User closed the authentication window', this.provider));
|
|
@@ -2756,6 +3498,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2756
3498
|
}, 1000);
|
|
2757
3499
|
});
|
|
2758
3500
|
}
|
|
3501
|
+
clearPopupCheckInterval() {
|
|
3502
|
+
if (this.popupCheckInterval !== null) {
|
|
3503
|
+
clearInterval(this.popupCheckInterval);
|
|
3504
|
+
this.popupCheckInterval = null;
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
2759
3507
|
async signOut(options) {
|
|
2760
3508
|
this.validateInitialized();
|
|
2761
3509
|
try {
|
|
@@ -2834,6 +3582,8 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2834
3582
|
if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) !== 'github-auth-callback') {
|
|
2835
3583
|
return;
|
|
2836
3584
|
}
|
|
3585
|
+
// The callback arrived — stop polling for a closed popup (success path cleanup).
|
|
3586
|
+
this.clearPopupCheckInterval();
|
|
2837
3587
|
if (this.authWindow) {
|
|
2838
3588
|
this.authWindow.close();
|
|
2839
3589
|
this.authWindow = null;
|
|
@@ -2876,9 +3626,44 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2876
3626
|
reject(AuthError.fromError(error, this.provider));
|
|
2877
3627
|
}
|
|
2878
3628
|
}
|
|
2879
|
-
async exchangeCodeForToken(
|
|
2880
|
-
//
|
|
2881
|
-
|
|
3629
|
+
async exchangeCodeForToken(code) {
|
|
3630
|
+
// GitHub does NOT permit browser-side code→token exchange (it needs the client secret
|
|
3631
|
+
// and blocks CORS), so the exchange must run on a developer-supplied backend proxy.
|
|
3632
|
+
if (!this.tokenExchangeProxy) {
|
|
3633
|
+
throw new AuthError(AuthErrorCode.MISSING_CONFIG, 'GitHub sign-in requires a backend token-exchange proxy. Set `tokenExchangeProxy` ' +
|
|
3634
|
+
'(or `tokenEndpoint`) in the GitHub provider config to a server endpoint that ' +
|
|
3635
|
+
'exchanges the authorization code for an access token. See the GitHub provider ' +
|
|
3636
|
+
'setup guide / docs/providers for an example.', this.provider);
|
|
3637
|
+
}
|
|
3638
|
+
let response;
|
|
3639
|
+
try {
|
|
3640
|
+
response = await fetch(this.tokenExchangeProxy, {
|
|
3641
|
+
method: 'POST',
|
|
3642
|
+
headers: {
|
|
3643
|
+
'Content-Type': 'application/json',
|
|
3644
|
+
Accept: 'application/json',
|
|
3645
|
+
},
|
|
3646
|
+
body: JSON.stringify({
|
|
3647
|
+
code,
|
|
3648
|
+
redirectUri: this.redirectUri,
|
|
3649
|
+
state: this.lastState,
|
|
3650
|
+
}),
|
|
3651
|
+
});
|
|
3652
|
+
}
|
|
3653
|
+
catch (error) {
|
|
3654
|
+
throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach the GitHub token-exchange proxy', this.provider, error);
|
|
3655
|
+
}
|
|
3656
|
+
const data = (await response
|
|
3657
|
+
.json()
|
|
3658
|
+
.catch(() => null));
|
|
3659
|
+
if (!response.ok || !data || !data.access_token) {
|
|
3660
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `GitHub token exchange failed${(data === null || data === void 0 ? void 0 : data.error_description)
|
|
3661
|
+
? `: ${data.error_description}`
|
|
3662
|
+
: (data === null || data === void 0 ? void 0 : data.error)
|
|
3663
|
+
? `: ${data.error}`
|
|
3664
|
+
: ''}`, this.provider);
|
|
3665
|
+
}
|
|
3666
|
+
return Object.assign(Object.assign({}, data), { access_token: data.access_token });
|
|
2882
3667
|
}
|
|
2883
3668
|
async fetchUserData(accessToken) {
|
|
2884
3669
|
const response = await fetch('https://api.github.com/user', {
|
|
@@ -2905,6 +3690,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2905
3690
|
return await response.json();
|
|
2906
3691
|
}
|
|
2907
3692
|
async createUserFromGitHubData(userData, accessToken) {
|
|
3693
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2908
3694
|
// Get primary email
|
|
2909
3695
|
const emails = await this.fetchUserEmails(accessToken);
|
|
2910
3696
|
const primaryEmail = emails.find((e) => e.primary) || emails[0];
|
|
@@ -2935,15 +3721,35 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2935
3721
|
},
|
|
2936
3722
|
customClaims: {
|
|
2937
3723
|
login: userData.login,
|
|
2938
|
-
company: userData.company,
|
|
2939
|
-
location: userData.location,
|
|
2940
|
-
bio: userData.bio,
|
|
2941
|
-
public_repos: userData.public_repos,
|
|
2942
|
-
followers: userData.followers,
|
|
2943
|
-
following: userData.following,
|
|
3724
|
+
company: (_a = userData.company) !== null && _a !== void 0 ? _a : null,
|
|
3725
|
+
location: (_b = userData.location) !== null && _b !== void 0 ? _b : null,
|
|
3726
|
+
bio: (_c = userData.bio) !== null && _c !== void 0 ? _c : null,
|
|
3727
|
+
public_repos: (_d = userData.public_repos) !== null && _d !== void 0 ? _d : null,
|
|
3728
|
+
followers: (_e = userData.followers) !== null && _e !== void 0 ? _e : null,
|
|
3729
|
+
following: (_f = userData.following) !== null && _f !== void 0 ? _f : null,
|
|
2944
3730
|
},
|
|
2945
3731
|
};
|
|
2946
3732
|
}
|
|
3733
|
+
dispose() {
|
|
3734
|
+
// Remove the global 'message' listener added in initialize() so it doesn't leak across
|
|
3735
|
+
// repeated init/dispose cycles, and stop any active popup-polling interval.
|
|
3736
|
+
if (this.boundAuthMessageHandler) {
|
|
3737
|
+
window.removeEventListener('message', this.boundAuthMessageHandler);
|
|
3738
|
+
this.boundAuthMessageHandler = null;
|
|
3739
|
+
}
|
|
3740
|
+
this.clearPopupCheckInterval();
|
|
3741
|
+
if (this.authWindow) {
|
|
3742
|
+
try {
|
|
3743
|
+
this.authWindow.close();
|
|
3744
|
+
}
|
|
3745
|
+
catch (_a) {
|
|
3746
|
+
// window already closed / cross-origin — safe to ignore
|
|
3747
|
+
}
|
|
3748
|
+
this.authWindow = null;
|
|
3749
|
+
}
|
|
3750
|
+
this.authPromise = null;
|
|
3751
|
+
super.dispose();
|
|
3752
|
+
}
|
|
2947
3753
|
}
|
|
2948
3754
|
|
|
2949
3755
|
var githubProvider = /*#__PURE__*/Object.freeze({
|
|
@@ -2956,6 +3762,11 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
2956
3762
|
super(...arguments);
|
|
2957
3763
|
this.unsubscribeAuth = null;
|
|
2958
3764
|
}
|
|
3765
|
+
/** Reads the host-page Firebase SDK, casting the `window` boundary exactly once. */
|
|
3766
|
+
getFirebase() {
|
|
3767
|
+
return window
|
|
3768
|
+
.firebase;
|
|
3769
|
+
}
|
|
2959
3770
|
async initialize() {
|
|
2960
3771
|
const options = this.options;
|
|
2961
3772
|
if (!options.apiKey || !options.authDomain || !options.projectId) {
|
|
@@ -2963,7 +3774,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
2963
3774
|
}
|
|
2964
3775
|
try {
|
|
2965
3776
|
// Check if Firebase is available
|
|
2966
|
-
const firebase =
|
|
3777
|
+
const firebase = this.getFirebase();
|
|
2967
3778
|
if (!firebase) {
|
|
2968
3779
|
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded. Please include the Firebase scripts in your HTML.', this.provider);
|
|
2969
3780
|
}
|
|
@@ -3011,73 +3822,88 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3011
3822
|
}
|
|
3012
3823
|
}
|
|
3013
3824
|
getPersistenceMode() {
|
|
3014
|
-
const firebase =
|
|
3825
|
+
const firebase = this.getFirebase();
|
|
3826
|
+
const persistence = firebase === null || firebase === void 0 ? void 0 : firebase.auth.Auth.Persistence;
|
|
3015
3827
|
switch (this.persistence) {
|
|
3016
3828
|
case 'session':
|
|
3017
|
-
return
|
|
3829
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.SESSION;
|
|
3018
3830
|
case 'none':
|
|
3019
|
-
return
|
|
3831
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.NONE;
|
|
3020
3832
|
default:
|
|
3021
|
-
return
|
|
3833
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.LOCAL;
|
|
3022
3834
|
}
|
|
3023
3835
|
}
|
|
3024
3836
|
async signIn(options) {
|
|
3837
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
|
3025
3838
|
this.validateInitialized();
|
|
3026
|
-
|
|
3839
|
+
// The manager spreads credentials to the top level AND nests them under `credentials`,
|
|
3840
|
+
// and spreads `options.*` (scopes, prompt, etc.) to the top level too. Derive the
|
|
3841
|
+
// Firebase sub-method from the STANDARD shape instead of an undocumented `options.method`.
|
|
3842
|
+
const raw = options || {};
|
|
3843
|
+
const nestedOptions = raw.options || {};
|
|
3844
|
+
const credentials = raw.credentials || {};
|
|
3845
|
+
// email/password may arrive nested under `credentials` or spread to the top level.
|
|
3846
|
+
const email = ((_a = credentials.email) !== null && _a !== void 0 ? _a : raw.email);
|
|
3847
|
+
const password = ((_b = credentials.password) !== null && _b !== void 0 ? _b : raw.password);
|
|
3848
|
+
const scopes = ((_c = nestedOptions.scopes) !== null && _c !== void 0 ? _c : raw.scopes);
|
|
3849
|
+
const firebaseOptions = this.options;
|
|
3850
|
+
const method = ((_e = (_d = nestedOptions.method) !== null && _d !== void 0 ? _d : raw.method) !== null && _e !== void 0 ? _e : (email && password
|
|
3851
|
+
? 'email'
|
|
3852
|
+
: firebaseOptions.defaultMethod || 'google'));
|
|
3853
|
+
const signInOptions = { method, email, password, scopes };
|
|
3854
|
+
const firebase = this.getFirebase();
|
|
3855
|
+
if (!firebase) {
|
|
3856
|
+
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
|
|
3857
|
+
}
|
|
3858
|
+
const applyScopes = (provider) => {
|
|
3859
|
+
if (signInOptions.scopes) {
|
|
3860
|
+
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3861
|
+
}
|
|
3862
|
+
};
|
|
3027
3863
|
try {
|
|
3028
3864
|
let firebaseUser;
|
|
3029
3865
|
let credential;
|
|
3030
3866
|
let additionalUserInfo;
|
|
3031
3867
|
// Determine sign-in method
|
|
3032
3868
|
if (signInOptions.method === 'google') {
|
|
3033
|
-
const provider = new
|
|
3034
|
-
|
|
3035
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3036
|
-
}
|
|
3869
|
+
const provider = new firebase.auth.GoogleAuthProvider();
|
|
3870
|
+
applyScopes(provider);
|
|
3037
3871
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3038
3872
|
firebaseUser = result.user;
|
|
3039
3873
|
credential = result.credential;
|
|
3040
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3874
|
+
additionalUserInfo = (_f = result.additionalUserInfo) !== null && _f !== void 0 ? _f : {};
|
|
3041
3875
|
}
|
|
3042
3876
|
else if (signInOptions.method === 'facebook') {
|
|
3043
|
-
const provider = new
|
|
3044
|
-
|
|
3045
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3046
|
-
}
|
|
3877
|
+
const provider = new firebase.auth.FacebookAuthProvider();
|
|
3878
|
+
applyScopes(provider);
|
|
3047
3879
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3048
3880
|
firebaseUser = result.user;
|
|
3049
3881
|
credential = result.credential;
|
|
3050
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3882
|
+
additionalUserInfo = (_g = result.additionalUserInfo) !== null && _g !== void 0 ? _g : {};
|
|
3051
3883
|
}
|
|
3052
3884
|
else if (signInOptions.method === 'github') {
|
|
3053
|
-
const provider = new
|
|
3054
|
-
|
|
3055
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3056
|
-
}
|
|
3885
|
+
const provider = new firebase.auth.GithubAuthProvider();
|
|
3886
|
+
applyScopes(provider);
|
|
3057
3887
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3058
3888
|
firebaseUser = result.user;
|
|
3059
3889
|
credential = result.credential;
|
|
3060
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3890
|
+
additionalUserInfo = (_h = result.additionalUserInfo) !== null && _h !== void 0 ? _h : {};
|
|
3061
3891
|
}
|
|
3062
3892
|
else if (signInOptions.method === 'microsoft') {
|
|
3063
|
-
const provider = new
|
|
3064
|
-
|
|
3065
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3066
|
-
}
|
|
3893
|
+
const provider = new firebase.auth.OAuthProvider('microsoft.com');
|
|
3894
|
+
applyScopes(provider);
|
|
3067
3895
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3068
3896
|
firebaseUser = result.user;
|
|
3069
3897
|
credential = result.credential;
|
|
3070
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3898
|
+
additionalUserInfo = (_j = result.additionalUserInfo) !== null && _j !== void 0 ? _j : {};
|
|
3071
3899
|
}
|
|
3072
3900
|
else if (signInOptions.method === 'apple') {
|
|
3073
|
-
const provider = new
|
|
3074
|
-
|
|
3075
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3076
|
-
}
|
|
3901
|
+
const provider = new firebase.auth.OAuthProvider('apple.com');
|
|
3902
|
+
applyScopes(provider);
|
|
3077
3903
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3078
3904
|
firebaseUser = result.user;
|
|
3079
3905
|
credential = result.credential;
|
|
3080
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3906
|
+
additionalUserInfo = (_k = result.additionalUserInfo) !== null && _k !== void 0 ? _k : {};
|
|
3081
3907
|
}
|
|
3082
3908
|
else if (signInOptions.method === 'email' &&
|
|
3083
3909
|
signInOptions.email &&
|
|
@@ -3109,11 +3935,12 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3109
3935
|
}
|
|
3110
3936
|
catch (error) {
|
|
3111
3937
|
this.logger.error('Firebase sign in failed', error);
|
|
3112
|
-
|
|
3113
|
-
|
|
3938
|
+
const err = error;
|
|
3939
|
+
if (err.code === 'auth/popup-closed-by-user' ||
|
|
3940
|
+
err.code === 'auth/cancelled-popup-request') {
|
|
3114
3941
|
throw new AuthError(AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
|
|
3115
3942
|
}
|
|
3116
|
-
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${
|
|
3943
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${err.message}`, this.provider);
|
|
3117
3944
|
}
|
|
3118
3945
|
}
|
|
3119
3946
|
async signOut(options) {
|
|
@@ -3157,24 +3984,33 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3157
3984
|
}
|
|
3158
3985
|
}
|
|
3159
3986
|
async isSupported() {
|
|
3160
|
-
return typeof window !== 'undefined' && !!
|
|
3987
|
+
return typeof window !== 'undefined' && !!this.getFirebase();
|
|
3161
3988
|
}
|
|
3162
3989
|
async linkAccount(options) {
|
|
3990
|
+
var _a, _b, _c, _d;
|
|
3163
3991
|
this.validateInitialized();
|
|
3164
3992
|
const currentUser = this.firebaseAuth.currentUser;
|
|
3165
3993
|
if (!currentUser) {
|
|
3166
3994
|
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active session to link account to', this.provider);
|
|
3167
3995
|
}
|
|
3996
|
+
const firebase = this.getFirebase();
|
|
3997
|
+
if (!firebase) {
|
|
3998
|
+
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
|
|
3999
|
+
}
|
|
4000
|
+
// `method`/`email`/`password` may arrive nested under credentials or in provider options.
|
|
4001
|
+
const raw = options;
|
|
4002
|
+
const creds = (_a = raw.credentials) !== null && _a !== void 0 ? _a : {};
|
|
4003
|
+
const method = ((_b = raw.method) !== null && _b !== void 0 ? _b : creds.method);
|
|
4004
|
+
const linkEmail = ((_c = creds.email) !== null && _c !== void 0 ? _c : raw.email);
|
|
4005
|
+
const linkPassword = ((_d = creds.password) !== null && _d !== void 0 ? _d : raw.password);
|
|
3168
4006
|
try {
|
|
3169
4007
|
let result;
|
|
3170
|
-
if (
|
|
3171
|
-
const provider = new
|
|
4008
|
+
if (method === 'google') {
|
|
4009
|
+
const provider = new firebase.auth.GoogleAuthProvider();
|
|
3172
4010
|
result = await currentUser.linkWithPopup(provider);
|
|
3173
4011
|
}
|
|
3174
|
-
else if (
|
|
3175
|
-
|
|
3176
|
-
options.password) {
|
|
3177
|
-
const credential = window.firebase.auth.EmailAuthProvider.credential(options.email, options.password);
|
|
4012
|
+
else if (method === 'email' && linkEmail && linkPassword) {
|
|
4013
|
+
const credential = firebase.auth.EmailAuthProvider.credential(linkEmail, linkPassword);
|
|
3178
4014
|
result = await currentUser.linkWithCredential(credential);
|
|
3179
4015
|
}
|
|
3180
4016
|
else {
|
|
@@ -3185,6 +4021,8 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3185
4021
|
return this.createAuthResult(user, authCredential, false, 'link');
|
|
3186
4022
|
}
|
|
3187
4023
|
catch (error) {
|
|
4024
|
+
if (error instanceof AuthError)
|
|
4025
|
+
throw error;
|
|
3188
4026
|
throw new AuthError(AuthErrorCode.INTERNAL_ERROR, `Failed to link account: ${error.message}`, this.provider);
|
|
3189
4027
|
}
|
|
3190
4028
|
}
|
|
@@ -3195,7 +4033,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3195
4033
|
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No active session', this.provider);
|
|
3196
4034
|
}
|
|
3197
4035
|
try {
|
|
3198
|
-
await currentUser.unlink(options.
|
|
4036
|
+
await currentUser.unlink(options.provider);
|
|
3199
4037
|
}
|
|
3200
4038
|
catch (error) {
|
|
3201
4039
|
throw new AuthError(AuthErrorCode.INTERNAL_ERROR, `Failed to unlink account: ${error.message}`, this.provider);
|
|
@@ -3259,26 +4097,137 @@ var firebaseProvider = /*#__PURE__*/Object.freeze({
|
|
|
3259
4097
|
FirebaseAuthProviderWeb: FirebaseAuthProviderWeb
|
|
3260
4098
|
});
|
|
3261
4099
|
|
|
3262
|
-
class
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
4100
|
+
class PendingVerificationStore {
|
|
4101
|
+
/**
|
|
4102
|
+
* @param namespace Provider namespace (e.g. `'sms'`, `'email-code'`, `'magic-link'`). Keys are
|
|
4103
|
+
* stored under `cap_auth_pending_<namespace>` so providers never collide.
|
|
4104
|
+
*/
|
|
4105
|
+
constructor(namespace) {
|
|
4106
|
+
/** In-memory mirror so the store works in SSR / private-mode where localStorage is unavailable. */
|
|
4107
|
+
this.memory = new Map();
|
|
4108
|
+
this.storageKey = `cap_auth_pending_${namespace}`;
|
|
4109
|
+
}
|
|
4110
|
+
getLocalStorage() {
|
|
4111
|
+
try {
|
|
4112
|
+
return typeof localStorage !== 'undefined' ? localStorage : null;
|
|
4113
|
+
}
|
|
4114
|
+
catch (_a) {
|
|
4115
|
+
// Access to localStorage can throw (e.g. sandboxed iframe) — fall back to memory only.
|
|
4116
|
+
return null;
|
|
4117
|
+
}
|
|
4118
|
+
}
|
|
4119
|
+
readAll() {
|
|
4120
|
+
const ls = this.getLocalStorage();
|
|
4121
|
+
if (!ls) {
|
|
4122
|
+
return Object.fromEntries(this.memory);
|
|
4123
|
+
}
|
|
4124
|
+
try {
|
|
4125
|
+
const raw = ls.getItem(this.storageKey);
|
|
4126
|
+
if (!raw)
|
|
4127
|
+
return {};
|
|
4128
|
+
const parsed = JSON.parse(raw);
|
|
4129
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
4130
|
+
}
|
|
4131
|
+
catch (error) {
|
|
4132
|
+
defaultLogger.warn(`PendingVerificationStore: failed to read ${this.storageKey}`, error);
|
|
4133
|
+
return {};
|
|
4134
|
+
}
|
|
4135
|
+
}
|
|
4136
|
+
writeAll(all) {
|
|
4137
|
+
const ls = this.getLocalStorage();
|
|
4138
|
+
if (!ls) {
|
|
4139
|
+
this.memory.clear();
|
|
4140
|
+
for (const [k, v] of Object.entries(all))
|
|
4141
|
+
this.memory.set(k, v);
|
|
4142
|
+
return;
|
|
4143
|
+
}
|
|
4144
|
+
try {
|
|
4145
|
+
ls.setItem(this.storageKey, JSON.stringify(all));
|
|
4146
|
+
}
|
|
4147
|
+
catch (error) {
|
|
4148
|
+
defaultLogger.warn(`PendingVerificationStore: failed to write ${this.storageKey}`, error);
|
|
4149
|
+
}
|
|
4150
|
+
}
|
|
4151
|
+
/**
|
|
4152
|
+
* Stores (or replaces) the pending record for `key` (phone / email / magic-link token). Other
|
|
4153
|
+
* expired entries in the namespace are pruned here to bound storage growth.
|
|
4154
|
+
*/
|
|
4155
|
+
set(key, record) {
|
|
4156
|
+
const all = this.readAll();
|
|
4157
|
+
this.pruneExpired(all, key);
|
|
4158
|
+
all[key] = record;
|
|
4159
|
+
this.writeAll(all);
|
|
4160
|
+
}
|
|
4161
|
+
/**
|
|
4162
|
+
* Returns the pending record for `key`, or null if absent. Does NOT filter by expiry — the
|
|
4163
|
+
* caller owns the expiry decision so it can throw a precise error and clean up itself.
|
|
4164
|
+
*/
|
|
4165
|
+
get(key) {
|
|
4166
|
+
var _a;
|
|
4167
|
+
const all = this.readAll();
|
|
4168
|
+
return (_a = all[key]) !== null && _a !== void 0 ? _a : null;
|
|
4169
|
+
}
|
|
4170
|
+
/** Removes the pending record for `key` (e.g. after a successful or expired verification). */
|
|
4171
|
+
delete(key) {
|
|
4172
|
+
const all = this.readAll();
|
|
4173
|
+
if (key in all) {
|
|
4174
|
+
delete all[key];
|
|
4175
|
+
this.writeAll(all);
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
4178
|
+
/** Clears every pending record in this namespace. */
|
|
4179
|
+
clear() {
|
|
4180
|
+
const ls = this.getLocalStorage();
|
|
4181
|
+
this.memory.clear();
|
|
4182
|
+
if (ls) {
|
|
4183
|
+
try {
|
|
4184
|
+
ls.removeItem(this.storageKey);
|
|
4185
|
+
}
|
|
4186
|
+
catch (error) {
|
|
4187
|
+
defaultLogger.warn(`PendingVerificationStore: failed to clear ${this.storageKey}`, error);
|
|
4188
|
+
}
|
|
4189
|
+
}
|
|
4190
|
+
}
|
|
4191
|
+
pruneExpired(all, exceptKey) {
|
|
4192
|
+
const now = Date.now();
|
|
4193
|
+
for (const [k, v] of Object.entries(all)) {
|
|
4194
|
+
if (k !== exceptKey && now > v.expires) {
|
|
4195
|
+
delete all[k];
|
|
4196
|
+
}
|
|
4197
|
+
}
|
|
4198
|
+
return all;
|
|
4199
|
+
}
|
|
4200
|
+
}
|
|
4201
|
+
|
|
4202
|
+
class MagicLinkProvider extends BaseAuthProvider {
|
|
4203
|
+
get name() {
|
|
4204
|
+
return 'magic-link';
|
|
4205
|
+
}
|
|
4206
|
+
constructor(input) {
|
|
4207
|
+
super(resolveProviderConfig(AuthProvider.EMAIL_MAGIC_LINK, input));
|
|
4208
|
+
// Persisted (SSR-guarded localStorage) so a magic link clicked from an email — which opens a
|
|
4209
|
+
// FRESH page load with empty in-memory state — can still find its pending entry to verify
|
|
4210
|
+
// against. Keyed by the link token (already present in the callback URL); we store only the
|
|
4211
|
+
// email + expiry, never any additional secret (see PendingVerificationStore + F-11).
|
|
4212
|
+
this.pendingVerification = new PendingVerificationStore('magic-link');
|
|
4213
|
+
// Magic link uses its config as-is (no defaults to merge).
|
|
4214
|
+
this.config = this.options;
|
|
3268
4215
|
// Check for magic link callback on initialization
|
|
3269
4216
|
this.checkForMagicLinkCallback();
|
|
3270
4217
|
}
|
|
3271
4218
|
async signIn(options) {
|
|
3272
4219
|
if (!(options === null || options === void 0 ? void 0 : options.email)) {
|
|
3273
|
-
throw new AuthError(
|
|
4220
|
+
throw new AuthError(AuthErrorCode.EMAIL_REQUIRED, 'Email is required for magic link authentication');
|
|
3274
4221
|
}
|
|
3275
4222
|
try {
|
|
3276
4223
|
// Send magic link to email
|
|
3277
4224
|
const token = this.generateToken();
|
|
3278
4225
|
const magicLink = this.generateMagicLink(token);
|
|
3279
|
-
// Store pending verification
|
|
4226
|
+
// Store pending verification (persisted; email + expiry only, keyed by the link token).
|
|
3280
4227
|
this.pendingVerification.set(token, {
|
|
3281
|
-
|
|
4228
|
+
identifier: options.email,
|
|
4229
|
+
sessionId: token,
|
|
4230
|
+
attempts: 0,
|
|
3282
4231
|
expires: Date.now() + 15 * 60 * 1000, // 15 minutes
|
|
3283
4232
|
});
|
|
3284
4233
|
// Send email via backend API
|
|
@@ -3295,7 +4244,7 @@ class MagicLinkProvider {
|
|
|
3295
4244
|
}),
|
|
3296
4245
|
});
|
|
3297
4246
|
if (!response.ok) {
|
|
3298
|
-
throw new AuthError(
|
|
4247
|
+
throw new AuthError(AuthErrorCode.SEND_LINK_FAILED, 'Failed to send magic link');
|
|
3299
4248
|
}
|
|
3300
4249
|
// Return partial auth result for pending state
|
|
3301
4250
|
const tempUser = {
|
|
@@ -3329,18 +4278,22 @@ class MagicLinkProvider {
|
|
|
3329
4278
|
};
|
|
3330
4279
|
}
|
|
3331
4280
|
catch (error) {
|
|
3332
|
-
|
|
4281
|
+
if (error instanceof AuthError)
|
|
4282
|
+
throw error;
|
|
4283
|
+
throw new AuthError(AuthErrorCode.SEND_LINK_FAILED, error.message || 'Failed to send magic link');
|
|
3333
4284
|
}
|
|
3334
4285
|
}
|
|
3335
4286
|
async verifyMagicLink(token) {
|
|
3336
4287
|
const pending = this.pendingVerification.get(token);
|
|
3337
4288
|
if (!pending) {
|
|
3338
|
-
throw new AuthError(
|
|
4289
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Invalid or expired magic link');
|
|
3339
4290
|
}
|
|
3340
4291
|
if (Date.now() > pending.expires) {
|
|
3341
4292
|
this.pendingVerification.delete(token);
|
|
3342
|
-
throw new AuthError(
|
|
4293
|
+
throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Magic link has expired');
|
|
3343
4294
|
}
|
|
4295
|
+
// The persisted record stores the email under `identifier`.
|
|
4296
|
+
const email = pending.identifier;
|
|
3344
4297
|
try {
|
|
3345
4298
|
// Verify token with backend if configured
|
|
3346
4299
|
if (this.config.verifyUrl) {
|
|
@@ -3351,27 +4304,27 @@ class MagicLinkProvider {
|
|
|
3351
4304
|
},
|
|
3352
4305
|
body: JSON.stringify({
|
|
3353
4306
|
token,
|
|
3354
|
-
email:
|
|
4307
|
+
email: email,
|
|
3355
4308
|
clientId: this.config.clientId,
|
|
3356
4309
|
}),
|
|
3357
4310
|
});
|
|
3358
4311
|
if (!response.ok) {
|
|
3359
|
-
throw new AuthError(
|
|
4312
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, 'Failed to verify magic link');
|
|
3360
4313
|
}
|
|
3361
4314
|
const data = await response.json();
|
|
3362
4315
|
// Create user from verified data
|
|
3363
4316
|
const user = {
|
|
3364
|
-
uid: data.uid || this.generateUid(
|
|
3365
|
-
email:
|
|
3366
|
-
displayName: data.displayName ||
|
|
4317
|
+
uid: data.uid || this.generateUid(email),
|
|
4318
|
+
email: email,
|
|
4319
|
+
displayName: data.displayName || email.split('@')[0],
|
|
3367
4320
|
photoURL: data.photoURL || null,
|
|
3368
4321
|
emailVerified: true,
|
|
3369
4322
|
providerData: [
|
|
3370
4323
|
{
|
|
3371
4324
|
providerId: this.name,
|
|
3372
|
-
uid: data.uid ||
|
|
3373
|
-
displayName: data.displayName ||
|
|
3374
|
-
email:
|
|
4325
|
+
uid: data.uid || email,
|
|
4326
|
+
displayName: data.displayName || email.split('@')[0],
|
|
4327
|
+
email: email,
|
|
3375
4328
|
phoneNumber: null,
|
|
3376
4329
|
photoURL: data.photoURL || null,
|
|
3377
4330
|
},
|
|
@@ -3400,17 +4353,17 @@ class MagicLinkProvider {
|
|
|
3400
4353
|
else {
|
|
3401
4354
|
// Simple verification without backend
|
|
3402
4355
|
const user = {
|
|
3403
|
-
uid: this.generateUid(
|
|
3404
|
-
email:
|
|
3405
|
-
displayName:
|
|
4356
|
+
uid: this.generateUid(email),
|
|
4357
|
+
email: email,
|
|
4358
|
+
displayName: email.split('@')[0],
|
|
3406
4359
|
photoURL: null,
|
|
3407
4360
|
emailVerified: true,
|
|
3408
4361
|
providerData: [
|
|
3409
4362
|
{
|
|
3410
4363
|
providerId: this.name,
|
|
3411
|
-
uid:
|
|
3412
|
-
displayName:
|
|
3413
|
-
email:
|
|
4364
|
+
uid: email,
|
|
4365
|
+
displayName: email.split('@')[0],
|
|
4366
|
+
email: email,
|
|
3414
4367
|
phoneNumber: null,
|
|
3415
4368
|
photoURL: null,
|
|
3416
4369
|
},
|
|
@@ -3437,7 +4390,9 @@ class MagicLinkProvider {
|
|
|
3437
4390
|
}
|
|
3438
4391
|
}
|
|
3439
4392
|
catch (error) {
|
|
3440
|
-
|
|
4393
|
+
if (error instanceof AuthError)
|
|
4394
|
+
throw error;
|
|
4395
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify magic link');
|
|
3441
4396
|
}
|
|
3442
4397
|
}
|
|
3443
4398
|
async signOut() {
|
|
@@ -3449,7 +4404,7 @@ class MagicLinkProvider {
|
|
|
3449
4404
|
return null;
|
|
3450
4405
|
}
|
|
3451
4406
|
async refreshToken() {
|
|
3452
|
-
throw new AuthError(
|
|
4407
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Token refresh is not supported for magic link authentication');
|
|
3453
4408
|
}
|
|
3454
4409
|
generateToken() {
|
|
3455
4410
|
const array = new Uint8Array(32);
|
|
@@ -3506,14 +4461,9 @@ class MagicLinkProvider {
|
|
|
3506
4461
|
// Magic link auth is supported if we have the required config
|
|
3507
4462
|
return !!this.config.sendLinkUrl;
|
|
3508
4463
|
}
|
|
3509
|
-
|
|
3510
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for magic link authentication');
|
|
3511
|
-
}
|
|
3512
|
-
async unlinkAccount(_options) {
|
|
3513
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for magic link authentication');
|
|
3514
|
-
}
|
|
4464
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
3515
4465
|
async revokeAccess(_token) {
|
|
3516
|
-
// Magic link doesn't have persistent access to revoke
|
|
4466
|
+
// Magic link doesn't have persistent access to revoke; clear any pending verification.
|
|
3517
4467
|
this.pendingVerification.clear();
|
|
3518
4468
|
}
|
|
3519
4469
|
}
|
|
@@ -3523,17 +4473,22 @@ var magicLinkProvider = /*#__PURE__*/Object.freeze({
|
|
|
3523
4473
|
MagicLinkProvider: MagicLinkProvider
|
|
3524
4474
|
});
|
|
3525
4475
|
|
|
3526
|
-
class SMSProvider {
|
|
3527
|
-
|
|
3528
|
-
|
|
3529
|
-
|
|
4476
|
+
class SMSProvider extends BaseAuthProvider {
|
|
4477
|
+
get name() {
|
|
4478
|
+
return 'sms';
|
|
4479
|
+
}
|
|
4480
|
+
constructor(input) {
|
|
4481
|
+
super(resolveProviderConfig(AuthProvider.SMS, input));
|
|
4482
|
+
// Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
|
|
4483
|
+
// page change between sending and verifying the code. Only non-secret metadata is stored —
|
|
4484
|
+
// never the SMS code itself (see PendingVerificationStore + F-11).
|
|
4485
|
+
this.pendingVerifications = new PendingVerificationStore('sms');
|
|
3530
4486
|
this.MAX_ATTEMPTS = 3;
|
|
3531
|
-
|
|
3532
|
-
this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, config);
|
|
4487
|
+
this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, this.options);
|
|
3533
4488
|
}
|
|
3534
4489
|
async signIn(options) {
|
|
3535
4490
|
if (!(options === null || options === void 0 ? void 0 : options.phoneNumber)) {
|
|
3536
|
-
throw new AuthError(
|
|
4491
|
+
throw new AuthError(AuthErrorCode.PHONE_REQUIRED, 'Phone number is required for SMS authentication');
|
|
3537
4492
|
}
|
|
3538
4493
|
// If code is provided, verify it
|
|
3539
4494
|
if (options.code) {
|
|
@@ -3552,7 +4507,7 @@ class SMSProvider {
|
|
|
3552
4507
|
const timeSinceLastResend = Date.now() - existing.lastResent;
|
|
3553
4508
|
if (timeSinceLastResend < this.config.resendDelay) {
|
|
3554
4509
|
const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
|
|
3555
|
-
throw new AuthError(
|
|
4510
|
+
throw new AuthError(AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
|
|
3556
4511
|
}
|
|
3557
4512
|
}
|
|
3558
4513
|
// Send SMS code via backend
|
|
@@ -3569,12 +4524,12 @@ class SMSProvider {
|
|
|
3569
4524
|
});
|
|
3570
4525
|
if (!response.ok) {
|
|
3571
4526
|
const error = await response.json().catch(() => ({}));
|
|
3572
|
-
throw new AuthError(
|
|
4527
|
+
throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
|
|
3573
4528
|
}
|
|
3574
4529
|
const data = await response.json();
|
|
3575
|
-
// Store pending verification
|
|
4530
|
+
// Store pending verification (persisted; metadata only, never the code).
|
|
3576
4531
|
this.pendingVerifications.set(formattedPhone, {
|
|
3577
|
-
|
|
4532
|
+
identifier: formattedPhone,
|
|
3578
4533
|
sessionId: data.sessionId,
|
|
3579
4534
|
expires: Date.now() + 10 * 60 * 1000, // 10 minutes
|
|
3580
4535
|
attempts: 0,
|
|
@@ -3617,26 +4572,27 @@ class SMSProvider {
|
|
|
3617
4572
|
catch (error) {
|
|
3618
4573
|
if (error instanceof AuthError)
|
|
3619
4574
|
throw error;
|
|
3620
|
-
throw new AuthError(
|
|
4575
|
+
throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
|
|
3621
4576
|
}
|
|
3622
4577
|
}
|
|
3623
4578
|
async verifyCode(phoneNumber, code) {
|
|
3624
4579
|
const formattedPhone = this.formatPhoneNumber(phoneNumber);
|
|
3625
4580
|
const pending = this.pendingVerifications.get(formattedPhone);
|
|
3626
4581
|
if (!pending) {
|
|
3627
|
-
throw new AuthError(
|
|
4582
|
+
throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending SMS verification found');
|
|
3628
4583
|
}
|
|
3629
4584
|
if (Date.now() > pending.expires) {
|
|
3630
4585
|
this.pendingVerifications.delete(formattedPhone);
|
|
3631
|
-
throw new AuthError(
|
|
4586
|
+
throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'SMS code has expired');
|
|
3632
4587
|
}
|
|
3633
4588
|
if (pending.attempts >= this.MAX_ATTEMPTS) {
|
|
3634
4589
|
this.pendingVerifications.delete(formattedPhone);
|
|
3635
|
-
throw new AuthError(
|
|
4590
|
+
throw new AuthError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts');
|
|
3636
4591
|
}
|
|
3637
4592
|
try {
|
|
3638
|
-
// Increment attempts
|
|
4593
|
+
// Increment attempts and persist the bump (so the count survives a reload mid-flow).
|
|
3639
4594
|
pending.attempts++;
|
|
4595
|
+
this.pendingVerifications.set(formattedPhone, pending);
|
|
3640
4596
|
// Verify code with backend
|
|
3641
4597
|
const response = await fetch(this.config.verifyCodeUrl, {
|
|
3642
4598
|
method: 'POST',
|
|
@@ -3653,9 +4609,9 @@ class SMSProvider {
|
|
|
3653
4609
|
if (!response.ok) {
|
|
3654
4610
|
const error = await response.json().catch(() => ({}));
|
|
3655
4611
|
if (response.status === 401) {
|
|
3656
|
-
throw new AuthError(
|
|
4612
|
+
throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid SMS code');
|
|
3657
4613
|
}
|
|
3658
|
-
throw new AuthError(
|
|
4614
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
|
|
3659
4615
|
}
|
|
3660
4616
|
const data = await response.json();
|
|
3661
4617
|
// Create user from verified data
|
|
@@ -3701,7 +4657,7 @@ class SMSProvider {
|
|
|
3701
4657
|
catch (error) {
|
|
3702
4658
|
if (error instanceof AuthError)
|
|
3703
4659
|
throw error;
|
|
3704
|
-
throw new AuthError(
|
|
4660
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
|
|
3705
4661
|
}
|
|
3706
4662
|
}
|
|
3707
4663
|
async signOut() {
|
|
@@ -3713,8 +4669,9 @@ class SMSProvider {
|
|
|
3713
4669
|
return null;
|
|
3714
4670
|
}
|
|
3715
4671
|
async refreshToken(_options) {
|
|
3716
|
-
//
|
|
3717
|
-
|
|
4672
|
+
// SMS code authentication is single-use and has no refresh flow; the user must request
|
|
4673
|
+
// a new verification code rather than refresh a token.
|
|
4674
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication does not support token refresh; request a new code instead.');
|
|
3718
4675
|
}
|
|
3719
4676
|
formatPhoneNumber(phoneNumber) {
|
|
3720
4677
|
// Remove all non-numeric characters
|
|
@@ -3765,14 +4722,9 @@ class SMSProvider {
|
|
|
3765
4722
|
// SMS auth is supported if we have the required config
|
|
3766
4723
|
return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
|
|
3767
4724
|
}
|
|
3768
|
-
|
|
3769
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for SMS authentication');
|
|
3770
|
-
}
|
|
3771
|
-
async unlinkAccount(_options) {
|
|
3772
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for SMS authentication');
|
|
3773
|
-
}
|
|
4725
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
3774
4726
|
async revokeAccess(_token) {
|
|
3775
|
-
// SMS auth doesn't have persistent access to revoke
|
|
4727
|
+
// SMS auth doesn't have persistent access to revoke; clear any pending verification.
|
|
3776
4728
|
this.pendingVerifications.clear();
|
|
3777
4729
|
}
|
|
3778
4730
|
}
|
|
@@ -3782,24 +4734,27 @@ var smsProvider = /*#__PURE__*/Object.freeze({
|
|
|
3782
4734
|
SMSProvider: SMSProvider
|
|
3783
4735
|
});
|
|
3784
4736
|
|
|
3785
|
-
class EmailPasswordProvider {
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
4737
|
+
class EmailPasswordProvider extends BaseAuthProvider {
|
|
4738
|
+
get name() {
|
|
4739
|
+
return 'email-password';
|
|
4740
|
+
}
|
|
4741
|
+
constructor(input) {
|
|
4742
|
+
super(resolveProviderConfig(AuthProvider.EMAIL_PASSWORD, input));
|
|
4743
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
4744
|
+
// so email/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
3789
4745
|
this.authToken = null;
|
|
3790
4746
|
this.refreshTokenValue = null;
|
|
3791
|
-
// Initialize with config
|
|
3792
4747
|
this.config = Object.assign({ allowSignUp: true, passwordRequirements: {
|
|
3793
4748
|
minLength: 8,
|
|
3794
4749
|
requireUppercase: true,
|
|
3795
4750
|
requireLowercase: true,
|
|
3796
4751
|
requireNumbers: true,
|
|
3797
4752
|
requireSpecialChars: false,
|
|
3798
|
-
} },
|
|
4753
|
+
} }, this.options);
|
|
3799
4754
|
}
|
|
3800
4755
|
async signIn(options) {
|
|
3801
4756
|
if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
3802
|
-
throw new AuthError(
|
|
4757
|
+
throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
|
|
3803
4758
|
}
|
|
3804
4759
|
try {
|
|
3805
4760
|
const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
|
|
@@ -3816,9 +4771,9 @@ class EmailPasswordProvider {
|
|
|
3816
4771
|
if (!response.ok) {
|
|
3817
4772
|
const error = await response.json().catch(() => ({}));
|
|
3818
4773
|
if (response.status === 401) {
|
|
3819
|
-
throw new AuthError(
|
|
4774
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid email or password');
|
|
3820
4775
|
}
|
|
3821
|
-
throw new AuthError(
|
|
4776
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
|
|
3822
4777
|
}
|
|
3823
4778
|
const data = await response.json();
|
|
3824
4779
|
// Create user object
|
|
@@ -3865,24 +4820,24 @@ class EmailPasswordProvider {
|
|
|
3865
4820
|
catch (error) {
|
|
3866
4821
|
if (error instanceof AuthError)
|
|
3867
4822
|
throw error;
|
|
3868
|
-
throw new AuthError(
|
|
4823
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with email and password');
|
|
3869
4824
|
}
|
|
3870
4825
|
}
|
|
3871
4826
|
async signUp(options) {
|
|
3872
4827
|
if (!this.config.allowSignUp) {
|
|
3873
|
-
throw new AuthError(
|
|
4828
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
|
|
3874
4829
|
}
|
|
3875
4830
|
if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
3876
|
-
throw new AuthError(
|
|
4831
|
+
throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
|
|
3877
4832
|
}
|
|
3878
4833
|
// Validate email
|
|
3879
4834
|
if (!this.isValidEmail(options.email)) {
|
|
3880
|
-
throw new AuthError(
|
|
4835
|
+
throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
3881
4836
|
}
|
|
3882
4837
|
// Validate password
|
|
3883
4838
|
const passwordError = this.validatePassword(options.password);
|
|
3884
4839
|
if (passwordError) {
|
|
3885
|
-
throw new AuthError(
|
|
4840
|
+
throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
3886
4841
|
}
|
|
3887
4842
|
try {
|
|
3888
4843
|
const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
|
|
@@ -3901,9 +4856,9 @@ class EmailPasswordProvider {
|
|
|
3901
4856
|
if (!response.ok) {
|
|
3902
4857
|
const error = await response.json().catch(() => ({}));
|
|
3903
4858
|
if (response.status === 409) {
|
|
3904
|
-
throw new AuthError(
|
|
4859
|
+
throw new AuthError(AuthErrorCode.EMAIL_ALREADY_IN_USE, 'Email already in use');
|
|
3905
4860
|
}
|
|
3906
|
-
throw new AuthError(
|
|
4861
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
3907
4862
|
}
|
|
3908
4863
|
const data = await response.json();
|
|
3909
4864
|
// Create user object
|
|
@@ -3950,7 +4905,7 @@ class EmailPasswordProvider {
|
|
|
3950
4905
|
catch (error) {
|
|
3951
4906
|
if (error instanceof AuthError)
|
|
3952
4907
|
throw error;
|
|
3953
|
-
throw new AuthError(
|
|
4908
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
3954
4909
|
}
|
|
3955
4910
|
}
|
|
3956
4911
|
async signOut() {
|
|
@@ -3980,7 +4935,7 @@ class EmailPasswordProvider {
|
|
|
3980
4935
|
}
|
|
3981
4936
|
async refreshToken(_options) {
|
|
3982
4937
|
if (!this.refreshTokenValue) {
|
|
3983
|
-
throw new AuthError(
|
|
4938
|
+
throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
|
|
3984
4939
|
}
|
|
3985
4940
|
try {
|
|
3986
4941
|
const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
|
|
@@ -3994,7 +4949,7 @@ class EmailPasswordProvider {
|
|
|
3994
4949
|
}),
|
|
3995
4950
|
});
|
|
3996
4951
|
if (!response.ok) {
|
|
3997
|
-
throw new AuthError(
|
|
4952
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
|
|
3998
4953
|
}
|
|
3999
4954
|
const data = await response.json();
|
|
4000
4955
|
// Update tokens
|
|
@@ -4016,17 +4971,17 @@ class EmailPasswordProvider {
|
|
|
4016
4971
|
catch (error) {
|
|
4017
4972
|
if (error instanceof AuthError)
|
|
4018
4973
|
throw error;
|
|
4019
|
-
throw new AuthError(
|
|
4974
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
|
|
4020
4975
|
}
|
|
4021
4976
|
}
|
|
4022
4977
|
async updatePassword(currentPassword, newPassword) {
|
|
4023
4978
|
if (!this.currentUser || !this.authToken) {
|
|
4024
|
-
throw new AuthError(
|
|
4979
|
+
throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
4025
4980
|
}
|
|
4026
4981
|
// Validate new password
|
|
4027
4982
|
const passwordError = this.validatePassword(newPassword);
|
|
4028
4983
|
if (passwordError) {
|
|
4029
|
-
throw new AuthError(
|
|
4984
|
+
throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
4030
4985
|
}
|
|
4031
4986
|
try {
|
|
4032
4987
|
const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
|
|
@@ -4044,20 +4999,20 @@ class EmailPasswordProvider {
|
|
|
4044
4999
|
if (!response.ok) {
|
|
4045
5000
|
const error = await response.json().catch(() => ({}));
|
|
4046
5001
|
if (response.status === 401) {
|
|
4047
|
-
throw new AuthError(
|
|
5002
|
+
throw new AuthError(AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
|
|
4048
5003
|
}
|
|
4049
|
-
throw new AuthError(
|
|
5004
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4050
5005
|
}
|
|
4051
5006
|
}
|
|
4052
5007
|
catch (error) {
|
|
4053
5008
|
if (error instanceof AuthError)
|
|
4054
5009
|
throw error;
|
|
4055
|
-
throw new AuthError(
|
|
5010
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4056
5011
|
}
|
|
4057
5012
|
}
|
|
4058
5013
|
async sendPasswordResetEmail(email) {
|
|
4059
5014
|
if (!this.isValidEmail(email)) {
|
|
4060
|
-
throw new AuthError(
|
|
5015
|
+
throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
4061
5016
|
}
|
|
4062
5017
|
try {
|
|
4063
5018
|
const response = await fetch(`${this.config.apiUrl}/auth/reset-password`, {
|
|
@@ -4072,21 +5027,21 @@ class EmailPasswordProvider {
|
|
|
4072
5027
|
});
|
|
4073
5028
|
if (!response.ok) {
|
|
4074
5029
|
const error = await response.json().catch(() => ({}));
|
|
4075
|
-
throw new AuthError(
|
|
5030
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send reset email');
|
|
4076
5031
|
}
|
|
4077
5032
|
}
|
|
4078
5033
|
catch (error) {
|
|
4079
5034
|
if (error instanceof AuthError)
|
|
4080
5035
|
throw error;
|
|
4081
|
-
throw new AuthError(
|
|
5036
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset email');
|
|
4082
5037
|
}
|
|
4083
5038
|
}
|
|
4084
5039
|
async sendEmailVerification() {
|
|
4085
5040
|
if (!this.currentUser || !this.authToken) {
|
|
4086
|
-
throw new AuthError(
|
|
5041
|
+
throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
4087
5042
|
}
|
|
4088
5043
|
if (this.currentUser.emailVerified) {
|
|
4089
|
-
throw new AuthError(
|
|
5044
|
+
throw new AuthError(AuthErrorCode.EMAIL_ALREADY_VERIFIED, 'Email already verified');
|
|
4090
5045
|
}
|
|
4091
5046
|
try {
|
|
4092
5047
|
const response = await fetch(`${this.config.apiUrl}/auth/verify-email`, {
|
|
@@ -4101,13 +5056,13 @@ class EmailPasswordProvider {
|
|
|
4101
5056
|
});
|
|
4102
5057
|
if (!response.ok) {
|
|
4103
5058
|
const error = await response.json().catch(() => ({}));
|
|
4104
|
-
throw new AuthError(
|
|
5059
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
|
|
4105
5060
|
}
|
|
4106
5061
|
}
|
|
4107
5062
|
catch (error) {
|
|
4108
5063
|
if (error instanceof AuthError)
|
|
4109
5064
|
throw error;
|
|
4110
|
-
throw new AuthError(
|
|
5065
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
|
|
4111
5066
|
}
|
|
4112
5067
|
}
|
|
4113
5068
|
isValidEmail(email) {
|
|
@@ -4141,12 +5096,7 @@ class EmailPasswordProvider {
|
|
|
4141
5096
|
// Email/Password auth is supported if we have the required config
|
|
4142
5097
|
return !!this.config.apiUrl;
|
|
4143
5098
|
}
|
|
4144
|
-
|
|
4145
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for email/password authentication');
|
|
4146
|
-
}
|
|
4147
|
-
async unlinkAccount(_options) {
|
|
4148
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for email/password authentication');
|
|
4149
|
-
}
|
|
5099
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
4150
5100
|
async revokeAccess(_token) {
|
|
4151
5101
|
// For email/password auth, revoking access means signing out
|
|
4152
5102
|
await this.signOut();
|
|
@@ -4158,10 +5108,15 @@ var emailPasswordProvider = /*#__PURE__*/Object.freeze({
|
|
|
4158
5108
|
EmailPasswordProvider: EmailPasswordProvider
|
|
4159
5109
|
});
|
|
4160
5110
|
|
|
4161
|
-
class BiometricProvider {
|
|
4162
|
-
|
|
4163
|
-
|
|
5111
|
+
class BiometricProvider extends BaseAuthProvider {
|
|
5112
|
+
get name() {
|
|
5113
|
+
return 'biometric';
|
|
5114
|
+
}
|
|
5115
|
+
constructor(input = {}) {
|
|
5116
|
+
super(resolveProviderConfig(AuthProvider.BIOMETRIC, input));
|
|
4164
5117
|
this.biometricAuth = null;
|
|
5118
|
+
this.cryptoKeyPromise = null;
|
|
5119
|
+
const config = this.options;
|
|
4165
5120
|
this.config = Object.assign({ reason: 'Authenticate to access your account', title: 'Authentication Required', subtitle: 'Access your account securely', fallbackTitle: 'Use Passcode', requireRecentAuth: true, recentAuthTimeout: 5 * 60 * 1000 }, config);
|
|
4166
5121
|
this.storageKey =
|
|
4167
5122
|
config.storageKey || 'capacitor-auth-biometric-credentials';
|
|
@@ -4175,31 +5130,31 @@ class BiometricProvider {
|
|
|
4175
5130
|
this.biometricAuth = BiometricAuth;
|
|
4176
5131
|
}
|
|
4177
5132
|
catch (_a) {
|
|
4178
|
-
|
|
5133
|
+
defaultLogger.warn('Biometric authentication plugin not available');
|
|
4179
5134
|
}
|
|
4180
5135
|
}
|
|
4181
5136
|
async signIn(_options) {
|
|
4182
5137
|
var _a, _b, _c;
|
|
4183
5138
|
if (!this.biometricAuth) {
|
|
4184
|
-
throw new AuthError(
|
|
5139
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
|
|
4185
5140
|
}
|
|
4186
5141
|
try {
|
|
4187
5142
|
// Check if biometry is available
|
|
4188
5143
|
const checkResult = await this.biometricAuth.checkBiometry();
|
|
4189
5144
|
if (!checkResult.isAvailable) {
|
|
4190
|
-
throw new AuthError(
|
|
5145
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, checkResult.reason ||
|
|
4191
5146
|
'Biometric authentication is not available on this device');
|
|
4192
5147
|
}
|
|
4193
5148
|
// Check if we have stored credentials
|
|
4194
5149
|
const storedCredentials = await this.getStoredCredentials();
|
|
4195
5150
|
if (!storedCredentials) {
|
|
4196
|
-
throw new AuthError(
|
|
5151
|
+
throw new AuthError(AuthErrorCode.NO_STORED_CREDENTIALS, 'No stored credentials found. Please sign in with another method first.');
|
|
4197
5152
|
}
|
|
4198
5153
|
// Check if recent auth is required
|
|
4199
5154
|
if (this.config.requireRecentAuth) {
|
|
4200
5155
|
const timeSinceLastAuth = Date.now() - storedCredentials.lastAuthTime;
|
|
4201
5156
|
if (timeSinceLastAuth > this.config.recentAuthTimeout) {
|
|
4202
|
-
throw new AuthError(
|
|
5157
|
+
throw new AuthError(AuthErrorCode.REQUIRES_RECENT_LOGIN, 'Authentication expired. Please sign in with another method.');
|
|
4203
5158
|
}
|
|
4204
5159
|
}
|
|
4205
5160
|
// Perform biometric authentication
|
|
@@ -4235,17 +5190,17 @@ class BiometricProvider {
|
|
|
4235
5190
|
throw error;
|
|
4236
5191
|
// Handle biometric errors
|
|
4237
5192
|
if (error.code === 'userCancel' || ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('cancel'))) {
|
|
4238
|
-
throw new AuthError(
|
|
5193
|
+
throw new AuthError(AuthErrorCode.USER_CANCELLED, 'Authentication cancelled by user');
|
|
4239
5194
|
}
|
|
4240
5195
|
else if (error.code === 'biometryLockout' ||
|
|
4241
5196
|
((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('lockout'))) {
|
|
4242
|
-
throw new AuthError(
|
|
5197
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_LOCKOUT, 'Too many failed attempts. Biometry is locked.');
|
|
4243
5198
|
}
|
|
4244
5199
|
else if (error.code === 'biometryNotEnrolled' ||
|
|
4245
5200
|
((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('enrolled'))) {
|
|
4246
|
-
throw new AuthError(
|
|
5201
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_ENROLLED, 'No biometric credentials are enrolled');
|
|
4247
5202
|
}
|
|
4248
|
-
throw new AuthError(
|
|
5203
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_AUTHENTICATION_FAILED, error.message || 'Biometric authentication failed');
|
|
4249
5204
|
}
|
|
4250
5205
|
}
|
|
4251
5206
|
async signOut() {
|
|
@@ -4309,6 +5264,8 @@ class BiometricProvider {
|
|
|
4309
5264
|
return true;
|
|
4310
5265
|
}
|
|
4311
5266
|
async getStoredCredentials() {
|
|
5267
|
+
if (typeof localStorage === 'undefined')
|
|
5268
|
+
return null;
|
|
4312
5269
|
try {
|
|
4313
5270
|
const stored = localStorage.getItem(this.storageKey);
|
|
4314
5271
|
if (!stored)
|
|
@@ -4321,25 +5278,118 @@ class BiometricProvider {
|
|
|
4321
5278
|
}
|
|
4322
5279
|
}
|
|
4323
5280
|
async storeCredentials(credentials) {
|
|
5281
|
+
if (typeof localStorage === 'undefined') {
|
|
5282
|
+
throw new AuthError(AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric credential storage is unavailable in this environment');
|
|
5283
|
+
}
|
|
4324
5284
|
try {
|
|
4325
5285
|
const encrypted = await this.encrypt(JSON.stringify(credentials));
|
|
4326
5286
|
localStorage.setItem(this.storageKey, encrypted);
|
|
4327
5287
|
}
|
|
4328
|
-
catch (
|
|
4329
|
-
throw new AuthError(
|
|
5288
|
+
catch (error) {
|
|
5289
|
+
throw new AuthError(AuthErrorCode.STORAGE_ERROR, 'Failed to store credentials', undefined, { cause: String(error) });
|
|
4330
5290
|
}
|
|
4331
5291
|
}
|
|
4332
5292
|
async clearStoredCredentials() {
|
|
4333
|
-
localStorage
|
|
5293
|
+
if (typeof localStorage !== 'undefined') {
|
|
5294
|
+
localStorage.removeItem(this.storageKey);
|
|
5295
|
+
}
|
|
5296
|
+
}
|
|
5297
|
+
/**
|
|
5298
|
+
* Persistent, non-extractable AES-GCM key kept in IndexedDB so it cannot be read back out by
|
|
5299
|
+
* script — stored biometric credentials are therefore not recoverable by simply reading
|
|
5300
|
+
* localStorage (unlike the previous base64 encoding).
|
|
5301
|
+
*/
|
|
5302
|
+
getEncryptionKey() {
|
|
5303
|
+
if (!this.cryptoKeyPromise) {
|
|
5304
|
+
this.cryptoKeyPromise = (async () => {
|
|
5305
|
+
const existing = await this.loadKeyFromIndexedDb();
|
|
5306
|
+
if (existing)
|
|
5307
|
+
return existing;
|
|
5308
|
+
const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
5309
|
+
await this.saveKeyToIndexedDb(key);
|
|
5310
|
+
return key;
|
|
5311
|
+
})();
|
|
5312
|
+
}
|
|
5313
|
+
return this.cryptoKeyPromise;
|
|
5314
|
+
}
|
|
5315
|
+
openKeyDb() {
|
|
5316
|
+
return new Promise((resolve, reject) => {
|
|
5317
|
+
const req = indexedDB.open('capacitor-auth-keys', 1);
|
|
5318
|
+
req.onupgradeneeded = () => req.result.createObjectStore('keys');
|
|
5319
|
+
req.onsuccess = () => resolve(req.result);
|
|
5320
|
+
req.onerror = () => reject(req.error);
|
|
5321
|
+
});
|
|
5322
|
+
}
|
|
5323
|
+
async loadKeyFromIndexedDb() {
|
|
5324
|
+
if (typeof indexedDB === 'undefined')
|
|
5325
|
+
return null;
|
|
5326
|
+
try {
|
|
5327
|
+
const db = await this.openKeyDb();
|
|
5328
|
+
return await new Promise((resolve) => {
|
|
5329
|
+
const tx = db.transaction('keys', 'readonly');
|
|
5330
|
+
const req = tx.objectStore('keys').get(this.storageKey);
|
|
5331
|
+
req.onsuccess = () => { var _a; return resolve((_a = req.result) !== null && _a !== void 0 ? _a : null); };
|
|
5332
|
+
req.onerror = () => resolve(null);
|
|
5333
|
+
});
|
|
5334
|
+
}
|
|
5335
|
+
catch (_a) {
|
|
5336
|
+
return null;
|
|
5337
|
+
}
|
|
5338
|
+
}
|
|
5339
|
+
async saveKeyToIndexedDb(key) {
|
|
5340
|
+
if (typeof indexedDB === 'undefined')
|
|
5341
|
+
return;
|
|
5342
|
+
try {
|
|
5343
|
+
const db = await this.openKeyDb();
|
|
5344
|
+
await new Promise((resolve) => {
|
|
5345
|
+
const tx = db.transaction('keys', 'readwrite');
|
|
5346
|
+
tx.objectStore('keys').put(key, this.storageKey);
|
|
5347
|
+
tx.oncomplete = () => resolve();
|
|
5348
|
+
tx.onerror = () => resolve();
|
|
5349
|
+
});
|
|
5350
|
+
}
|
|
5351
|
+
catch (_a) {
|
|
5352
|
+
// Best-effort: a fresh key is generated next time if persistence fails.
|
|
5353
|
+
}
|
|
4334
5354
|
}
|
|
4335
|
-
|
|
5355
|
+
/**
|
|
5356
|
+
* Encrypts with AES-GCM (Web Crypto). Falls back to base64 ONLY when Web Crypto / IndexedDB
|
|
5357
|
+
* are unavailable (insecure context); the `b64:`/`aes:` prefix tells decrypt() the format.
|
|
5358
|
+
*/
|
|
4336
5359
|
async encrypt(data) {
|
|
4337
|
-
|
|
4338
|
-
|
|
5360
|
+
if (typeof crypto === 'undefined' ||
|
|
5361
|
+
!crypto.subtle ||
|
|
5362
|
+
typeof indexedDB === 'undefined') {
|
|
5363
|
+
return `b64:${btoa(data)}`;
|
|
5364
|
+
}
|
|
5365
|
+
const key = await this.getEncryptionKey();
|
|
5366
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
5367
|
+
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(data));
|
|
5368
|
+
const packed = new Uint8Array(iv.length + ciphertext.byteLength);
|
|
5369
|
+
packed.set(iv, 0);
|
|
5370
|
+
packed.set(new Uint8Array(ciphertext), iv.length);
|
|
5371
|
+
let binary = '';
|
|
5372
|
+
for (let i = 0; i < packed.length; i++) {
|
|
5373
|
+
binary += String.fromCharCode(packed[i]);
|
|
5374
|
+
}
|
|
5375
|
+
return `aes:${btoa(binary)}`;
|
|
4339
5376
|
}
|
|
4340
5377
|
async decrypt(data) {
|
|
4341
|
-
|
|
4342
|
-
|
|
5378
|
+
if (data.startsWith('aes:')) {
|
|
5379
|
+
const key = await this.getEncryptionKey();
|
|
5380
|
+
const binary = atob(data.slice(4));
|
|
5381
|
+
const bytes = new Uint8Array(binary.length);
|
|
5382
|
+
for (let i = 0; i < binary.length; i++) {
|
|
5383
|
+
bytes[i] = binary.charCodeAt(i);
|
|
5384
|
+
}
|
|
5385
|
+
const iv = bytes.slice(0, 12);
|
|
5386
|
+
const ciphertext = bytes.slice(12);
|
|
5387
|
+
const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
|
|
5388
|
+
return new TextDecoder().decode(plaintext);
|
|
5389
|
+
}
|
|
5390
|
+
// Legacy (older versions) or insecure-context fallback: base64-encoded payload.
|
|
5391
|
+
const payload = data.startsWith('b64:') ? data.slice(4) : data;
|
|
5392
|
+
return atob(payload);
|
|
4343
5393
|
}
|
|
4344
5394
|
async initialize() {
|
|
4345
5395
|
// Biometric provider is initialized in constructor
|
|
@@ -4350,9 +5400,7 @@ class BiometricProvider {
|
|
|
4350
5400
|
const result = await this.isAvailable();
|
|
4351
5401
|
return result.available;
|
|
4352
5402
|
}
|
|
4353
|
-
|
|
4354
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for biometric authentication');
|
|
4355
|
-
}
|
|
5403
|
+
// linkAccount inherits BaseAuthProvider's OPERATION_NOT_ALLOWED default (F-44).
|
|
4356
5404
|
async unlinkAccount(_options) {
|
|
4357
5405
|
// Unlinking biometric auth means clearing stored credentials
|
|
4358
5406
|
await this.clearStoredCredentials();
|
|
@@ -4388,9 +5436,9 @@ class SlackProvider extends OAuthProvider {
|
|
|
4388
5436
|
async signIn(options) {
|
|
4389
5437
|
return this.performOAuthFlow(options);
|
|
4390
5438
|
}
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
5439
|
+
// Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
|
|
5440
|
+
// Note: Slack's OAuth 2.0 for public web apps typically doesn't issue refresh tokens.
|
|
5441
|
+
// If no refresh token is available, the base class will throw "No refresh token available".
|
|
4394
5442
|
getOAuthConfig() {
|
|
4395
5443
|
return {
|
|
4396
5444
|
clientId: this.clientId,
|
|
@@ -4401,15 +5449,39 @@ class SlackProvider extends OAuthProvider {
|
|
|
4401
5449
|
additionalParams: this.teamId ? { team: this.teamId } : {},
|
|
4402
5450
|
};
|
|
4403
5451
|
}
|
|
4404
|
-
async parseUserFromTokenResponse(
|
|
4405
|
-
|
|
4406
|
-
|
|
5452
|
+
async parseUserFromTokenResponse(response) {
|
|
5453
|
+
var _a;
|
|
5454
|
+
const accessToken = response.access_token;
|
|
5455
|
+
if (!accessToken) {
|
|
5456
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Slack token response did not include an access token; cannot fetch the user profile.', this.provider);
|
|
5457
|
+
}
|
|
5458
|
+
// Fetch the real profile via Slack's OpenID Connect userInfo endpoint.
|
|
5459
|
+
// https://api.slack.com/methods/openid.connect.userInfo
|
|
5460
|
+
let res;
|
|
5461
|
+
try {
|
|
5462
|
+
res = await fetch('https://slack.com/api/openid.connect.userInfo', {
|
|
5463
|
+
method: 'GET',
|
|
5464
|
+
headers: {
|
|
5465
|
+
Authorization: `Bearer ${accessToken}`,
|
|
5466
|
+
Accept: 'application/json',
|
|
5467
|
+
},
|
|
5468
|
+
});
|
|
5469
|
+
}
|
|
5470
|
+
catch (error) {
|
|
5471
|
+
throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach Slack userInfo endpoint', this.provider, error);
|
|
5472
|
+
}
|
|
5473
|
+
// Slack returns HTTP 200 with `{ ok: false, error }` on API-level failures.
|
|
5474
|
+
const data = (await res.json().catch(() => null));
|
|
5475
|
+
if (!res.ok || !data || data.ok === false || !data.sub) {
|
|
5476
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, `Failed to fetch Slack user profile${(data === null || data === void 0 ? void 0 : data.error) ? `: ${data.error}` : ''}`, this.provider);
|
|
5477
|
+
}
|
|
4407
5478
|
return {
|
|
4408
|
-
id:
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
|
|
5479
|
+
id: data.sub,
|
|
5480
|
+
sub: data.sub,
|
|
5481
|
+
email: data.email,
|
|
5482
|
+
email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
|
|
5483
|
+
name: data.name,
|
|
5484
|
+
picture: data.picture,
|
|
4413
5485
|
isNewUser: false,
|
|
4414
5486
|
};
|
|
4415
5487
|
}
|
|
@@ -4455,10 +5527,10 @@ class SlackProvider extends OAuthProvider {
|
|
|
4455
5527
|
return true;
|
|
4456
5528
|
}
|
|
4457
5529
|
async linkAccount(_options) {
|
|
4458
|
-
throw new AuthError(
|
|
5530
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for Slack provider');
|
|
4459
5531
|
}
|
|
4460
5532
|
async unlinkAccount(_options) {
|
|
4461
|
-
throw new AuthError(
|
|
5533
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for Slack provider');
|
|
4462
5534
|
}
|
|
4463
5535
|
async revokeAccess(token) {
|
|
4464
5536
|
await super.revokeAccess(token);
|
|
@@ -4497,9 +5569,10 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4497
5569
|
await this.clearStoredData();
|
|
4498
5570
|
await this.setCurrentUser(null);
|
|
4499
5571
|
}
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
5572
|
+
// Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
|
|
5573
|
+
// Note: LinkedIn's OAuth 2.0 issues long-lived access tokens (60 days) and typically
|
|
5574
|
+
// doesn't provide refresh tokens for web apps. If no refresh token is available,
|
|
5575
|
+
// the base class will throw "No refresh token available".
|
|
4503
5576
|
getOAuthConfig() {
|
|
4504
5577
|
return {
|
|
4505
5578
|
clientId: this.clientId,
|
|
@@ -4509,15 +5582,40 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4509
5582
|
scopes: this.scopes,
|
|
4510
5583
|
};
|
|
4511
5584
|
}
|
|
4512
|
-
async parseUserFromTokenResponse(
|
|
4513
|
-
|
|
4514
|
-
|
|
5585
|
+
async parseUserFromTokenResponse(response) {
|
|
5586
|
+
var _a;
|
|
5587
|
+
const accessToken = response.access_token;
|
|
5588
|
+
if (!accessToken) {
|
|
5589
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'LinkedIn token response did not include an access token; cannot fetch the user profile.', this.provider);
|
|
5590
|
+
}
|
|
5591
|
+
// Fetch the real profile via LinkedIn's OpenID Connect userinfo endpoint.
|
|
5592
|
+
// https://learn.microsoft.com/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2
|
|
5593
|
+
let res;
|
|
5594
|
+
try {
|
|
5595
|
+
res = await fetch('https://api.linkedin.com/v2/userinfo', {
|
|
5596
|
+
method: 'GET',
|
|
5597
|
+
headers: {
|
|
5598
|
+
Authorization: `Bearer ${accessToken}`,
|
|
5599
|
+
Accept: 'application/json',
|
|
5600
|
+
},
|
|
5601
|
+
});
|
|
5602
|
+
}
|
|
5603
|
+
catch (error) {
|
|
5604
|
+
throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to reach LinkedIn userinfo endpoint', this.provider, error);
|
|
5605
|
+
}
|
|
5606
|
+
const data = (await res
|
|
5607
|
+
.json()
|
|
5608
|
+
.catch(() => null));
|
|
5609
|
+
if (!res.ok || !data || !data.sub) {
|
|
5610
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Failed to fetch LinkedIn user profile', this.provider);
|
|
5611
|
+
}
|
|
4515
5612
|
return {
|
|
4516
|
-
id:
|
|
4517
|
-
|
|
4518
|
-
|
|
4519
|
-
|
|
4520
|
-
|
|
5613
|
+
id: data.sub,
|
|
5614
|
+
sub: data.sub,
|
|
5615
|
+
email: data.email,
|
|
5616
|
+
email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
|
|
5617
|
+
name: data.name,
|
|
5618
|
+
picture: data.picture,
|
|
4521
5619
|
isNewUser: false,
|
|
4522
5620
|
};
|
|
4523
5621
|
}
|
|
@@ -4564,10 +5662,10 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4564
5662
|
return true;
|
|
4565
5663
|
}
|
|
4566
5664
|
async linkAccount(_options) {
|
|
4567
|
-
throw new AuthError(
|
|
5665
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for LinkedIn provider');
|
|
4568
5666
|
}
|
|
4569
5667
|
async unlinkAccount(_options) {
|
|
4570
|
-
throw new AuthError(
|
|
5668
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for LinkedIn provider');
|
|
4571
5669
|
}
|
|
4572
5670
|
async revokeAccess(token) {
|
|
4573
5671
|
await super.revokeAccess(token);
|
|
@@ -4579,17 +5677,22 @@ var linkedinProvider = /*#__PURE__*/Object.freeze({
|
|
|
4579
5677
|
LinkedInProvider: LinkedInProvider
|
|
4580
5678
|
});
|
|
4581
5679
|
|
|
4582
|
-
class UsernamePasswordProvider {
|
|
4583
|
-
|
|
4584
|
-
|
|
4585
|
-
|
|
5680
|
+
class UsernamePasswordProvider extends BaseAuthProvider {
|
|
5681
|
+
get name() {
|
|
5682
|
+
return 'username-password';
|
|
5683
|
+
}
|
|
5684
|
+
constructor(input) {
|
|
5685
|
+
super(resolveProviderConfig(AuthProvider.USERNAME_PASSWORD, input));
|
|
5686
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
5687
|
+
// so username/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
4586
5688
|
this.authToken = null;
|
|
4587
5689
|
this.refreshTokenValue = null;
|
|
5690
|
+
const config = this.options;
|
|
4588
5691
|
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);
|
|
4589
5692
|
}
|
|
4590
5693
|
async signIn(options) {
|
|
4591
5694
|
if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
4592
|
-
throw new AuthError(
|
|
5695
|
+
throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
|
|
4593
5696
|
}
|
|
4594
5697
|
try {
|
|
4595
5698
|
const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
|
|
@@ -4606,9 +5709,9 @@ class UsernamePasswordProvider {
|
|
|
4606
5709
|
if (!response.ok) {
|
|
4607
5710
|
const error = await response.json().catch(() => ({}));
|
|
4608
5711
|
if (response.status === 401) {
|
|
4609
|
-
throw new AuthError(
|
|
5712
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid username or password');
|
|
4610
5713
|
}
|
|
4611
|
-
throw new AuthError(
|
|
5714
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
|
|
4612
5715
|
}
|
|
4613
5716
|
const data = await response.json();
|
|
4614
5717
|
// Create user object
|
|
@@ -4656,29 +5759,29 @@ class UsernamePasswordProvider {
|
|
|
4656
5759
|
catch (error) {
|
|
4657
5760
|
if (error instanceof AuthError)
|
|
4658
5761
|
throw error;
|
|
4659
|
-
throw new AuthError(
|
|
5762
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with username and password');
|
|
4660
5763
|
}
|
|
4661
5764
|
}
|
|
4662
5765
|
async signUp(options) {
|
|
4663
5766
|
if (!this.config.allowSignUp) {
|
|
4664
|
-
throw new AuthError(
|
|
5767
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
|
|
4665
5768
|
}
|
|
4666
5769
|
if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
4667
|
-
throw new AuthError(
|
|
5770
|
+
throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
|
|
4668
5771
|
}
|
|
4669
5772
|
// Validate username
|
|
4670
5773
|
const usernameError = this.validateUsername(options.username);
|
|
4671
5774
|
if (usernameError) {
|
|
4672
|
-
throw new AuthError(
|
|
5775
|
+
throw new AuthError(AuthErrorCode.INVALID_USERNAME, usernameError);
|
|
4673
5776
|
}
|
|
4674
5777
|
// Validate password
|
|
4675
5778
|
const passwordError = this.validatePassword(options.password);
|
|
4676
5779
|
if (passwordError) {
|
|
4677
|
-
throw new AuthError(
|
|
5780
|
+
throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
4678
5781
|
}
|
|
4679
5782
|
// Validate email if provided
|
|
4680
5783
|
if (options.email && !this.isValidEmail(options.email)) {
|
|
4681
|
-
throw new AuthError(
|
|
5784
|
+
throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
4682
5785
|
}
|
|
4683
5786
|
try {
|
|
4684
5787
|
const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
|
|
@@ -4698,9 +5801,9 @@ class UsernamePasswordProvider {
|
|
|
4698
5801
|
if (!response.ok) {
|
|
4699
5802
|
const error = await response.json().catch(() => ({}));
|
|
4700
5803
|
if (response.status === 409) {
|
|
4701
|
-
throw new AuthError(
|
|
5804
|
+
throw new AuthError(AuthErrorCode.USERNAME_ALREADY_EXISTS, 'Username already taken');
|
|
4702
5805
|
}
|
|
4703
|
-
throw new AuthError(
|
|
5806
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
4704
5807
|
}
|
|
4705
5808
|
const data = await response.json();
|
|
4706
5809
|
// Create user object
|
|
@@ -4748,7 +5851,7 @@ class UsernamePasswordProvider {
|
|
|
4748
5851
|
catch (error) {
|
|
4749
5852
|
if (error instanceof AuthError)
|
|
4750
5853
|
throw error;
|
|
4751
|
-
throw new AuthError(
|
|
5854
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
4752
5855
|
}
|
|
4753
5856
|
}
|
|
4754
5857
|
async signOut() {
|
|
@@ -4778,7 +5881,7 @@ class UsernamePasswordProvider {
|
|
|
4778
5881
|
}
|
|
4779
5882
|
async refreshToken(_options) {
|
|
4780
5883
|
if (!this.refreshTokenValue) {
|
|
4781
|
-
throw new AuthError(
|
|
5884
|
+
throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
|
|
4782
5885
|
}
|
|
4783
5886
|
try {
|
|
4784
5887
|
const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
|
|
@@ -4792,7 +5895,7 @@ class UsernamePasswordProvider {
|
|
|
4792
5895
|
}),
|
|
4793
5896
|
});
|
|
4794
5897
|
if (!response.ok) {
|
|
4795
|
-
throw new AuthError(
|
|
5898
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
|
|
4796
5899
|
}
|
|
4797
5900
|
const data = await response.json();
|
|
4798
5901
|
// Update tokens
|
|
@@ -4814,17 +5917,17 @@ class UsernamePasswordProvider {
|
|
|
4814
5917
|
catch (error) {
|
|
4815
5918
|
if (error instanceof AuthError)
|
|
4816
5919
|
throw error;
|
|
4817
|
-
throw new AuthError(
|
|
5920
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
|
|
4818
5921
|
}
|
|
4819
5922
|
}
|
|
4820
5923
|
async updatePassword(currentPassword, newPassword) {
|
|
4821
5924
|
if (!this.currentUser || !this.authToken) {
|
|
4822
|
-
throw new AuthError(
|
|
5925
|
+
throw new AuthError(AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
4823
5926
|
}
|
|
4824
5927
|
// Validate new password
|
|
4825
5928
|
const passwordError = this.validatePassword(newPassword);
|
|
4826
5929
|
if (passwordError) {
|
|
4827
|
-
throw new AuthError(
|
|
5930
|
+
throw new AuthError(AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
4828
5931
|
}
|
|
4829
5932
|
try {
|
|
4830
5933
|
const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
|
|
@@ -4842,15 +5945,15 @@ class UsernamePasswordProvider {
|
|
|
4842
5945
|
if (!response.ok) {
|
|
4843
5946
|
const error = await response.json().catch(() => ({}));
|
|
4844
5947
|
if (response.status === 401) {
|
|
4845
|
-
throw new AuthError(
|
|
5948
|
+
throw new AuthError(AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
|
|
4846
5949
|
}
|
|
4847
|
-
throw new AuthError(
|
|
5950
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4848
5951
|
}
|
|
4849
5952
|
}
|
|
4850
5953
|
catch (error) {
|
|
4851
5954
|
if (error instanceof AuthError)
|
|
4852
5955
|
throw error;
|
|
4853
|
-
throw new AuthError(
|
|
5956
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4854
5957
|
}
|
|
4855
5958
|
}
|
|
4856
5959
|
async checkUsernameAvailability(username) {
|
|
@@ -4929,12 +6032,7 @@ class UsernamePasswordProvider {
|
|
|
4929
6032
|
// Username/Password auth is supported if we have the required config
|
|
4930
6033
|
return !!this.config.apiUrl;
|
|
4931
6034
|
}
|
|
4932
|
-
|
|
4933
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for username/password authentication');
|
|
4934
|
-
}
|
|
4935
|
-
async unlinkAccount(_options) {
|
|
4936
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for username/password authentication');
|
|
4937
|
-
}
|
|
6035
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
4938
6036
|
async revokeAccess(_token) {
|
|
4939
6037
|
// For username/password auth, revoking access means signing out
|
|
4940
6038
|
await this.signOut();
|
|
@@ -4946,6 +6044,638 @@ var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
|
|
|
4946
6044
|
UsernamePasswordProvider: UsernamePasswordProvider
|
|
4947
6045
|
});
|
|
4948
6046
|
|
|
6047
|
+
class EmailCodeProvider extends BaseAuthProvider {
|
|
6048
|
+
get name() {
|
|
6049
|
+
return 'email-code';
|
|
6050
|
+
}
|
|
6051
|
+
constructor(input) {
|
|
6052
|
+
super(resolveProviderConfig(AuthProvider.EMAIL_CODE, input));
|
|
6053
|
+
// Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
|
|
6054
|
+
// page change between sending and verifying the code. Only non-secret metadata is stored —
|
|
6055
|
+
// never the verification code itself (see PendingVerificationStore + F-11).
|
|
6056
|
+
this.pendingVerifications = new PendingVerificationStore('email-code');
|
|
6057
|
+
this.MAX_ATTEMPTS = 3;
|
|
6058
|
+
this.config = Object.assign({ codeLength: 6, resendDelay: 60000, codeExpiration: 10 * 60 * 1000 }, this.options);
|
|
6059
|
+
}
|
|
6060
|
+
async signIn(options) {
|
|
6061
|
+
if (!(options === null || options === void 0 ? void 0 : options.email)) {
|
|
6062
|
+
throw new AuthError(AuthErrorCode.EMAIL_REQUIRED, 'Email is required for email code authentication');
|
|
6063
|
+
}
|
|
6064
|
+
// Validate email format
|
|
6065
|
+
if (!this.isValidEmail(options.email)) {
|
|
6066
|
+
throw new AuthError(AuthErrorCode.INVALID_EMAIL, 'Please enter a valid email address');
|
|
6067
|
+
}
|
|
6068
|
+
// If code is provided, verify it
|
|
6069
|
+
if (options.code) {
|
|
6070
|
+
return this.verifyCode(options.email, options.code);
|
|
6071
|
+
}
|
|
6072
|
+
// Otherwise, send code
|
|
6073
|
+
return this.sendCode(options.email);
|
|
6074
|
+
}
|
|
6075
|
+
async sendCode(email) {
|
|
6076
|
+
try {
|
|
6077
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6078
|
+
// Check if we can resend
|
|
6079
|
+
const existing = this.pendingVerifications.get(normalizedEmail);
|
|
6080
|
+
if (existing && existing.lastResent) {
|
|
6081
|
+
const timeSinceLastResend = Date.now() - existing.lastResent;
|
|
6082
|
+
if (timeSinceLastResend < this.config.resendDelay) {
|
|
6083
|
+
const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
|
|
6084
|
+
throw new AuthError(AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
|
|
6085
|
+
}
|
|
6086
|
+
}
|
|
6087
|
+
// Send email code via backend
|
|
6088
|
+
const response = await fetch(this.config.sendCodeUrl, {
|
|
6089
|
+
method: 'POST',
|
|
6090
|
+
headers: {
|
|
6091
|
+
'Content-Type': 'application/json',
|
|
6092
|
+
},
|
|
6093
|
+
body: JSON.stringify({
|
|
6094
|
+
email: normalizedEmail,
|
|
6095
|
+
clientId: this.config.clientId,
|
|
6096
|
+
codeLength: this.config.codeLength,
|
|
6097
|
+
}),
|
|
6098
|
+
});
|
|
6099
|
+
if (!response.ok) {
|
|
6100
|
+
const error = await response.json().catch(() => ({}));
|
|
6101
|
+
throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6102
|
+
}
|
|
6103
|
+
const data = await response.json();
|
|
6104
|
+
// Store pending verification (persisted; metadata only, never the code).
|
|
6105
|
+
this.pendingVerifications.set(normalizedEmail, {
|
|
6106
|
+
identifier: normalizedEmail,
|
|
6107
|
+
sessionId: data.sessionId,
|
|
6108
|
+
expires: Date.now() + this.config.codeExpiration,
|
|
6109
|
+
attempts: 0,
|
|
6110
|
+
lastResent: Date.now(),
|
|
6111
|
+
});
|
|
6112
|
+
// Return partial auth result for pending state
|
|
6113
|
+
const tempUser = {
|
|
6114
|
+
uid: `email-code-pending:${data.sessionId}`,
|
|
6115
|
+
email: normalizedEmail,
|
|
6116
|
+
displayName: normalizedEmail.split('@')[0],
|
|
6117
|
+
photoURL: null,
|
|
6118
|
+
phoneNumber: null,
|
|
6119
|
+
emailVerified: false,
|
|
6120
|
+
providerData: [],
|
|
6121
|
+
metadata: {
|
|
6122
|
+
creationTime: new Date().toISOString(),
|
|
6123
|
+
lastSignInTime: new Date().toISOString(),
|
|
6124
|
+
},
|
|
6125
|
+
};
|
|
6126
|
+
return {
|
|
6127
|
+
user: tempUser,
|
|
6128
|
+
credential: {
|
|
6129
|
+
providerId: this.name,
|
|
6130
|
+
signInMethod: 'email-code',
|
|
6131
|
+
accessToken: data.sessionId,
|
|
6132
|
+
},
|
|
6133
|
+
additionalUserInfo: {
|
|
6134
|
+
isNewUser: false,
|
|
6135
|
+
providerId: this.name,
|
|
6136
|
+
profile: {
|
|
6137
|
+
email: normalizedEmail,
|
|
6138
|
+
sessionId: data.sessionId,
|
|
6139
|
+
message: `Verification code sent to ${this.maskEmail(normalizedEmail)}`,
|
|
6140
|
+
pending: true,
|
|
6141
|
+
},
|
|
6142
|
+
},
|
|
6143
|
+
};
|
|
6144
|
+
}
|
|
6145
|
+
catch (error) {
|
|
6146
|
+
if (error instanceof AuthError)
|
|
6147
|
+
throw error;
|
|
6148
|
+
throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6149
|
+
}
|
|
6150
|
+
}
|
|
6151
|
+
async verifyCode(email, code) {
|
|
6152
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6153
|
+
const pending = this.pendingVerifications.get(normalizedEmail);
|
|
6154
|
+
if (!pending) {
|
|
6155
|
+
throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending email verification found. Please request a new code.');
|
|
6156
|
+
}
|
|
6157
|
+
if (Date.now() > pending.expires) {
|
|
6158
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6159
|
+
throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
|
|
6160
|
+
}
|
|
6161
|
+
if (pending.attempts >= this.MAX_ATTEMPTS) {
|
|
6162
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6163
|
+
throw new AuthError(AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts. Please request a new code.');
|
|
6164
|
+
}
|
|
6165
|
+
try {
|
|
6166
|
+
// Increment attempts and persist the bump (so the count survives a reload mid-flow).
|
|
6167
|
+
pending.attempts++;
|
|
6168
|
+
this.pendingVerifications.set(normalizedEmail, pending);
|
|
6169
|
+
// Verify code with backend
|
|
6170
|
+
const response = await fetch(this.config.verifyCodeUrl, {
|
|
6171
|
+
method: 'POST',
|
|
6172
|
+
headers: {
|
|
6173
|
+
'Content-Type': 'application/json',
|
|
6174
|
+
},
|
|
6175
|
+
body: JSON.stringify({
|
|
6176
|
+
email: normalizedEmail,
|
|
6177
|
+
code,
|
|
6178
|
+
sessionId: pending.sessionId,
|
|
6179
|
+
clientId: this.config.clientId,
|
|
6180
|
+
}),
|
|
6181
|
+
});
|
|
6182
|
+
if (!response.ok) {
|
|
6183
|
+
const error = await response.json().catch(() => ({}));
|
|
6184
|
+
if (response.status === 401) {
|
|
6185
|
+
throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid verification code');
|
|
6186
|
+
}
|
|
6187
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
|
|
6188
|
+
}
|
|
6189
|
+
const data = await response.json();
|
|
6190
|
+
// Create user from verified data
|
|
6191
|
+
const user = {
|
|
6192
|
+
uid: data.uid || this.generateUid(normalizedEmail),
|
|
6193
|
+
email: normalizedEmail,
|
|
6194
|
+
displayName: data.displayName || normalizedEmail.split('@')[0],
|
|
6195
|
+
photoURL: data.photoURL || null,
|
|
6196
|
+
phoneNumber: data.phoneNumber || null,
|
|
6197
|
+
emailVerified: true,
|
|
6198
|
+
providerData: [
|
|
6199
|
+
{
|
|
6200
|
+
providerId: this.name,
|
|
6201
|
+
uid: data.uid || normalizedEmail,
|
|
6202
|
+
displayName: data.displayName || normalizedEmail.split('@')[0],
|
|
6203
|
+
email: normalizedEmail,
|
|
6204
|
+
phoneNumber: null,
|
|
6205
|
+
photoURL: data.photoURL || null,
|
|
6206
|
+
},
|
|
6207
|
+
],
|
|
6208
|
+
metadata: {
|
|
6209
|
+
creationTime: data.createdAt || new Date().toISOString(),
|
|
6210
|
+
lastSignInTime: new Date().toISOString(),
|
|
6211
|
+
},
|
|
6212
|
+
};
|
|
6213
|
+
// Clean up pending verification
|
|
6214
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6215
|
+
return {
|
|
6216
|
+
user,
|
|
6217
|
+
credential: {
|
|
6218
|
+
providerId: this.name,
|
|
6219
|
+
signInMethod: 'email-code',
|
|
6220
|
+
accessToken: data.accessToken,
|
|
6221
|
+
refreshToken: data.refreshToken,
|
|
6222
|
+
expiresAt: data.expiresAt,
|
|
6223
|
+
},
|
|
6224
|
+
additionalUserInfo: {
|
|
6225
|
+
isNewUser: data.isNewUser || false,
|
|
6226
|
+
providerId: this.name,
|
|
6227
|
+
},
|
|
6228
|
+
};
|
|
6229
|
+
}
|
|
6230
|
+
catch (error) {
|
|
6231
|
+
if (error instanceof AuthError)
|
|
6232
|
+
throw error;
|
|
6233
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
|
|
6234
|
+
}
|
|
6235
|
+
}
|
|
6236
|
+
async signOut() {
|
|
6237
|
+
this.pendingVerifications.clear();
|
|
6238
|
+
}
|
|
6239
|
+
async getCurrentUser() {
|
|
6240
|
+
return null;
|
|
6241
|
+
}
|
|
6242
|
+
async refreshToken(_options) {
|
|
6243
|
+
// Email code authentication is single-use and has no refresh flow; the user must request
|
|
6244
|
+
// a new verification code rather than refresh a token.
|
|
6245
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication does not support token refresh; request a new code instead.');
|
|
6246
|
+
}
|
|
6247
|
+
async initialize() {
|
|
6248
|
+
// Email code provider doesn't require initialization
|
|
6249
|
+
}
|
|
6250
|
+
async isSupported() {
|
|
6251
|
+
return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
|
|
6252
|
+
}
|
|
6253
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
6254
|
+
async revokeAccess(_token) {
|
|
6255
|
+
this.pendingVerifications.clear();
|
|
6256
|
+
}
|
|
6257
|
+
// Public method to resend code
|
|
6258
|
+
async resendCode(email) {
|
|
6259
|
+
return this.sendCode(email);
|
|
6260
|
+
}
|
|
6261
|
+
// Public method to check if can resend
|
|
6262
|
+
canResendCode(email) {
|
|
6263
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6264
|
+
const pending = this.pendingVerifications.get(normalizedEmail);
|
|
6265
|
+
if (!pending || !pending.lastResent) {
|
|
6266
|
+
return { canResend: true };
|
|
6267
|
+
}
|
|
6268
|
+
const timeSinceLastResend = Date.now() - pending.lastResent;
|
|
6269
|
+
if (timeSinceLastResend < this.config.resendDelay) {
|
|
6270
|
+
return {
|
|
6271
|
+
canResend: false,
|
|
6272
|
+
waitTime: Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000),
|
|
6273
|
+
};
|
|
6274
|
+
}
|
|
6275
|
+
return { canResend: true };
|
|
6276
|
+
}
|
|
6277
|
+
isValidEmail(email) {
|
|
6278
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
6279
|
+
return emailRegex.test(email);
|
|
6280
|
+
}
|
|
6281
|
+
maskEmail(email) {
|
|
6282
|
+
const [local, domain] = email.split('@');
|
|
6283
|
+
if (local.length <= 2) {
|
|
6284
|
+
return `${local[0]}***@${domain}`;
|
|
6285
|
+
}
|
|
6286
|
+
return `${local[0]}***${local[local.length - 1]}@${domain}`;
|
|
6287
|
+
}
|
|
6288
|
+
generateUid(email) {
|
|
6289
|
+
return `email-code:${email.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
|
|
6290
|
+
}
|
|
6291
|
+
}
|
|
6292
|
+
|
|
6293
|
+
var emailCodeProvider = /*#__PURE__*/Object.freeze({
|
|
6294
|
+
__proto__: null,
|
|
6295
|
+
EmailCodeProvider: EmailCodeProvider
|
|
6296
|
+
});
|
|
6297
|
+
|
|
6298
|
+
class PhonePasswordProvider extends BaseAuthProvider {
|
|
6299
|
+
get name() {
|
|
6300
|
+
return 'phone-password';
|
|
6301
|
+
}
|
|
6302
|
+
constructor(input) {
|
|
6303
|
+
super(resolveProviderConfig(AuthProvider.PHONE_PASSWORD, input));
|
|
6304
|
+
this.pendingVerifications = new Map();
|
|
6305
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
6306
|
+
// so phone/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
6307
|
+
this.storedAccessToken = null;
|
|
6308
|
+
this.storedRefreshToken = null;
|
|
6309
|
+
this.config = Object.assign({ countryCode: '+1', requirePhoneVerification: false, passwordStrength: {
|
|
6310
|
+
minLength: 8,
|
|
6311
|
+
requireUppercase: true,
|
|
6312
|
+
requireLowercase: true,
|
|
6313
|
+
requireNumbers: true,
|
|
6314
|
+
requireSpecialChars: false,
|
|
6315
|
+
} }, this.options);
|
|
6316
|
+
}
|
|
6317
|
+
async signIn(options) {
|
|
6318
|
+
const credentials = options === null || options === void 0 ? void 0 : options.credentials;
|
|
6319
|
+
if (!(credentials === null || credentials === void 0 ? void 0 : credentials.phoneNumber) || !(credentials === null || credentials === void 0 ? void 0 : credentials.password)) {
|
|
6320
|
+
throw new AuthError(AuthErrorCode.CREDENTIALS_REQUIRED, 'Phone number and password are required');
|
|
6321
|
+
}
|
|
6322
|
+
const formattedPhone = this.formatPhoneNumber(credentials.phoneNumber);
|
|
6323
|
+
// Handle sign up flow
|
|
6324
|
+
if (options === null || options === void 0 ? void 0 : options.isSignUp) {
|
|
6325
|
+
return this.signUp(formattedPhone, credentials.password);
|
|
6326
|
+
}
|
|
6327
|
+
// Handle phone verification if code is provided
|
|
6328
|
+
if (credentials.code && this.config.requirePhoneVerification) {
|
|
6329
|
+
return this.verifyPhone(formattedPhone, credentials.code, credentials.password);
|
|
6330
|
+
}
|
|
6331
|
+
// Standard sign in
|
|
6332
|
+
return this.performSignIn(formattedPhone, credentials.password);
|
|
6333
|
+
}
|
|
6334
|
+
async performSignIn(phoneNumber, password) {
|
|
6335
|
+
try {
|
|
6336
|
+
const response = await fetch(this.config.signInUrl, {
|
|
6337
|
+
method: 'POST',
|
|
6338
|
+
headers: {
|
|
6339
|
+
'Content-Type': 'application/json',
|
|
6340
|
+
},
|
|
6341
|
+
body: JSON.stringify({
|
|
6342
|
+
phoneNumber,
|
|
6343
|
+
password,
|
|
6344
|
+
clientId: this.config.clientId,
|
|
6345
|
+
}),
|
|
6346
|
+
});
|
|
6347
|
+
if (!response.ok) {
|
|
6348
|
+
const error = await response.json().catch(() => ({}));
|
|
6349
|
+
if (response.status === 401) {
|
|
6350
|
+
throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'Invalid phone number or password');
|
|
6351
|
+
}
|
|
6352
|
+
if (response.status === 403) {
|
|
6353
|
+
throw new AuthError(AuthErrorCode.PHONE_NOT_VERIFIED, 'Please verify your phone number first');
|
|
6354
|
+
}
|
|
6355
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
|
|
6356
|
+
}
|
|
6357
|
+
const data = await response.json();
|
|
6358
|
+
return this.buildAuthResult(data, phoneNumber);
|
|
6359
|
+
}
|
|
6360
|
+
catch (error) {
|
|
6361
|
+
if (error instanceof AuthError)
|
|
6362
|
+
throw error;
|
|
6363
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
|
|
6364
|
+
}
|
|
6365
|
+
}
|
|
6366
|
+
async signUp(phoneNumber, password) {
|
|
6367
|
+
// Validate password strength
|
|
6368
|
+
this.validatePassword(password);
|
|
6369
|
+
try {
|
|
6370
|
+
const response = await fetch(this.config.signUpUrl, {
|
|
6371
|
+
method: 'POST',
|
|
6372
|
+
headers: {
|
|
6373
|
+
'Content-Type': 'application/json',
|
|
6374
|
+
},
|
|
6375
|
+
body: JSON.stringify({
|
|
6376
|
+
phoneNumber,
|
|
6377
|
+
password,
|
|
6378
|
+
clientId: this.config.clientId,
|
|
6379
|
+
}),
|
|
6380
|
+
});
|
|
6381
|
+
if (!response.ok) {
|
|
6382
|
+
const error = await response.json().catch(() => ({}));
|
|
6383
|
+
if (response.status === 409) {
|
|
6384
|
+
throw new AuthError(AuthErrorCode.PHONE_NUMBER_ALREADY_EXISTS, 'An account with this phone number already exists');
|
|
6385
|
+
}
|
|
6386
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
|
|
6387
|
+
}
|
|
6388
|
+
const data = await response.json();
|
|
6389
|
+
// If phone verification is required, send verification code
|
|
6390
|
+
if (this.config.requirePhoneVerification && this.config.sendVerificationUrl) {
|
|
6391
|
+
await this.sendVerificationCode(phoneNumber);
|
|
6392
|
+
return {
|
|
6393
|
+
user: {
|
|
6394
|
+
uid: `phone-pending:${data.sessionId || phoneNumber}`,
|
|
6395
|
+
email: null,
|
|
6396
|
+
displayName: this.maskPhoneNumber(phoneNumber),
|
|
6397
|
+
photoURL: null,
|
|
6398
|
+
phoneNumber,
|
|
6399
|
+
emailVerified: false,
|
|
6400
|
+
providerData: [],
|
|
6401
|
+
metadata: {
|
|
6402
|
+
creationTime: new Date().toISOString(),
|
|
6403
|
+
lastSignInTime: new Date().toISOString(),
|
|
6404
|
+
},
|
|
6405
|
+
},
|
|
6406
|
+
credential: {
|
|
6407
|
+
providerId: this.name,
|
|
6408
|
+
signInMethod: 'phone-password',
|
|
6409
|
+
accessToken: data.sessionId,
|
|
6410
|
+
},
|
|
6411
|
+
additionalUserInfo: {
|
|
6412
|
+
isNewUser: true,
|
|
6413
|
+
providerId: this.name,
|
|
6414
|
+
profile: {
|
|
6415
|
+
phoneNumber,
|
|
6416
|
+
message: 'Phone verification required. Check your SMS.',
|
|
6417
|
+
pending: true,
|
|
6418
|
+
},
|
|
6419
|
+
},
|
|
6420
|
+
};
|
|
6421
|
+
}
|
|
6422
|
+
return this.buildAuthResult(data, phoneNumber, true);
|
|
6423
|
+
}
|
|
6424
|
+
catch (error) {
|
|
6425
|
+
if (error instanceof AuthError)
|
|
6426
|
+
throw error;
|
|
6427
|
+
throw new AuthError(AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
|
|
6428
|
+
}
|
|
6429
|
+
}
|
|
6430
|
+
async sendVerificationCode(phoneNumber) {
|
|
6431
|
+
if (!this.config.sendVerificationUrl) {
|
|
6432
|
+
throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
|
|
6433
|
+
}
|
|
6434
|
+
const response = await fetch(this.config.sendVerificationUrl, {
|
|
6435
|
+
method: 'POST',
|
|
6436
|
+
headers: {
|
|
6437
|
+
'Content-Type': 'application/json',
|
|
6438
|
+
},
|
|
6439
|
+
body: JSON.stringify({
|
|
6440
|
+
phoneNumber,
|
|
6441
|
+
clientId: this.config.clientId,
|
|
6442
|
+
}),
|
|
6443
|
+
});
|
|
6444
|
+
if (!response.ok) {
|
|
6445
|
+
const error = await response.json().catch(() => ({}));
|
|
6446
|
+
throw new AuthError(AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6447
|
+
}
|
|
6448
|
+
const data = await response.json();
|
|
6449
|
+
this.pendingVerifications.set(phoneNumber, {
|
|
6450
|
+
phoneNumber,
|
|
6451
|
+
sessionId: data.sessionId,
|
|
6452
|
+
expires: Date.now() + 10 * 60 * 1000, // 10 minutes
|
|
6453
|
+
});
|
|
6454
|
+
}
|
|
6455
|
+
async verifyPhone(phoneNumber, code, password) {
|
|
6456
|
+
if (!this.config.verifyPhoneUrl) {
|
|
6457
|
+
throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
|
|
6458
|
+
}
|
|
6459
|
+
const pending = this.pendingVerifications.get(phoneNumber);
|
|
6460
|
+
if (!pending) {
|
|
6461
|
+
throw new AuthError(AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending phone verification found');
|
|
6462
|
+
}
|
|
6463
|
+
if (Date.now() > pending.expires) {
|
|
6464
|
+
this.pendingVerifications.delete(phoneNumber);
|
|
6465
|
+
throw new AuthError(AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
|
|
6466
|
+
}
|
|
6467
|
+
try {
|
|
6468
|
+
const response = await fetch(this.config.verifyPhoneUrl, {
|
|
6469
|
+
method: 'POST',
|
|
6470
|
+
headers: {
|
|
6471
|
+
'Content-Type': 'application/json',
|
|
6472
|
+
},
|
|
6473
|
+
body: JSON.stringify({
|
|
6474
|
+
phoneNumber,
|
|
6475
|
+
code,
|
|
6476
|
+
password,
|
|
6477
|
+
sessionId: pending.sessionId,
|
|
6478
|
+
clientId: this.config.clientId,
|
|
6479
|
+
}),
|
|
6480
|
+
});
|
|
6481
|
+
if (!response.ok) {
|
|
6482
|
+
const error = await response.json().catch(() => ({}));
|
|
6483
|
+
if (response.status === 401) {
|
|
6484
|
+
throw new AuthError(AuthErrorCode.INVALID_CODE, 'Invalid verification code');
|
|
6485
|
+
}
|
|
6486
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
|
|
6487
|
+
}
|
|
6488
|
+
const data = await response.json();
|
|
6489
|
+
this.pendingVerifications.delete(phoneNumber);
|
|
6490
|
+
return this.buildAuthResult(data, phoneNumber);
|
|
6491
|
+
}
|
|
6492
|
+
catch (error) {
|
|
6493
|
+
if (error instanceof AuthError)
|
|
6494
|
+
throw error;
|
|
6495
|
+
throw new AuthError(AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
|
|
6496
|
+
}
|
|
6497
|
+
}
|
|
6498
|
+
async signOut() {
|
|
6499
|
+
this.currentUser = null;
|
|
6500
|
+
this.storedAccessToken = null;
|
|
6501
|
+
this.storedRefreshToken = null;
|
|
6502
|
+
this.pendingVerifications.clear();
|
|
6503
|
+
}
|
|
6504
|
+
async getCurrentUser() {
|
|
6505
|
+
return this.currentUser;
|
|
6506
|
+
}
|
|
6507
|
+
async refreshToken(_options) {
|
|
6508
|
+
if (!this.storedRefreshToken || !this.config.refreshTokenUrl) {
|
|
6509
|
+
throw new AuthError(AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available or refresh URL not configured');
|
|
6510
|
+
}
|
|
6511
|
+
try {
|
|
6512
|
+
const response = await fetch(this.config.refreshTokenUrl, {
|
|
6513
|
+
method: 'POST',
|
|
6514
|
+
headers: {
|
|
6515
|
+
'Content-Type': 'application/json',
|
|
6516
|
+
},
|
|
6517
|
+
body: JSON.stringify({
|
|
6518
|
+
refreshToken: this.storedRefreshToken,
|
|
6519
|
+
clientId: this.config.clientId,
|
|
6520
|
+
}),
|
|
6521
|
+
});
|
|
6522
|
+
if (!response.ok) {
|
|
6523
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, 'Token refresh failed');
|
|
6524
|
+
}
|
|
6525
|
+
const data = await response.json();
|
|
6526
|
+
this.storedAccessToken = data.accessToken;
|
|
6527
|
+
if (data.refreshToken) {
|
|
6528
|
+
this.storedRefreshToken = data.refreshToken;
|
|
6529
|
+
}
|
|
6530
|
+
if (!this.currentUser) {
|
|
6531
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No current user');
|
|
6532
|
+
}
|
|
6533
|
+
return {
|
|
6534
|
+
user: this.currentUser,
|
|
6535
|
+
credential: {
|
|
6536
|
+
providerId: this.name,
|
|
6537
|
+
signInMethod: 'phone-password',
|
|
6538
|
+
accessToken: data.accessToken,
|
|
6539
|
+
refreshToken: data.refreshToken || this.storedRefreshToken,
|
|
6540
|
+
expiresAt: data.expiresAt,
|
|
6541
|
+
},
|
|
6542
|
+
additionalUserInfo: {
|
|
6543
|
+
isNewUser: false,
|
|
6544
|
+
providerId: this.name,
|
|
6545
|
+
},
|
|
6546
|
+
};
|
|
6547
|
+
}
|
|
6548
|
+
catch (error) {
|
|
6549
|
+
if (error instanceof AuthError)
|
|
6550
|
+
throw error;
|
|
6551
|
+
throw new AuthError(AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Token refresh failed');
|
|
6552
|
+
}
|
|
6553
|
+
}
|
|
6554
|
+
async initialize() {
|
|
6555
|
+
// Phone password provider doesn't require initialization
|
|
6556
|
+
}
|
|
6557
|
+
async isSupported() {
|
|
6558
|
+
return !!(this.config.signInUrl && this.config.signUpUrl);
|
|
6559
|
+
}
|
|
6560
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
6561
|
+
async revokeAccess(_token) {
|
|
6562
|
+
await this.signOut();
|
|
6563
|
+
}
|
|
6564
|
+
getAccessToken() {
|
|
6565
|
+
return this.storedAccessToken;
|
|
6566
|
+
}
|
|
6567
|
+
async sendPasswordReset(phoneNumber) {
|
|
6568
|
+
if (!this.config.resetPasswordUrl) {
|
|
6569
|
+
throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Password reset URL not configured');
|
|
6570
|
+
}
|
|
6571
|
+
const formattedPhone = this.formatPhoneNumber(phoneNumber);
|
|
6572
|
+
const response = await fetch(this.config.resetPasswordUrl, {
|
|
6573
|
+
method: 'POST',
|
|
6574
|
+
headers: {
|
|
6575
|
+
'Content-Type': 'application/json',
|
|
6576
|
+
},
|
|
6577
|
+
body: JSON.stringify({
|
|
6578
|
+
phoneNumber: formattedPhone,
|
|
6579
|
+
clientId: this.config.clientId,
|
|
6580
|
+
}),
|
|
6581
|
+
});
|
|
6582
|
+
if (!response.ok) {
|
|
6583
|
+
const error = await response.json().catch(() => ({}));
|
|
6584
|
+
throw new AuthError(AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset');
|
|
6585
|
+
}
|
|
6586
|
+
}
|
|
6587
|
+
// Renamed from createAuthResult to avoid colliding with BaseAuthProvider.createAuthResult,
|
|
6588
|
+
// which has a different signature (this builds a phone-specific result from a backend payload).
|
|
6589
|
+
buildAuthResult(data, phoneNumber, isNewUser = false) {
|
|
6590
|
+
const user = {
|
|
6591
|
+
uid: data.uid || this.generateUid(phoneNumber),
|
|
6592
|
+
email: data.email || null,
|
|
6593
|
+
displayName: data.displayName || phoneNumber,
|
|
6594
|
+
photoURL: data.photoURL || null,
|
|
6595
|
+
phoneNumber,
|
|
6596
|
+
emailVerified: false,
|
|
6597
|
+
providerData: [
|
|
6598
|
+
{
|
|
6599
|
+
providerId: this.name,
|
|
6600
|
+
uid: data.uid || phoneNumber,
|
|
6601
|
+
displayName: data.displayName || phoneNumber,
|
|
6602
|
+
email: data.email || null,
|
|
6603
|
+
phoneNumber,
|
|
6604
|
+
photoURL: data.photoURL || null,
|
|
6605
|
+
},
|
|
6606
|
+
],
|
|
6607
|
+
metadata: {
|
|
6608
|
+
creationTime: data.createdAt || new Date().toISOString(),
|
|
6609
|
+
lastSignInTime: new Date().toISOString(),
|
|
6610
|
+
},
|
|
6611
|
+
};
|
|
6612
|
+
this.currentUser = user;
|
|
6613
|
+
this.storedAccessToken = data.accessToken;
|
|
6614
|
+
this.storedRefreshToken = data.refreshToken;
|
|
6615
|
+
return {
|
|
6616
|
+
user,
|
|
6617
|
+
credential: {
|
|
6618
|
+
providerId: this.name,
|
|
6619
|
+
signInMethod: 'phone-password',
|
|
6620
|
+
accessToken: data.accessToken,
|
|
6621
|
+
refreshToken: data.refreshToken,
|
|
6622
|
+
expiresAt: data.expiresAt,
|
|
6623
|
+
},
|
|
6624
|
+
additionalUserInfo: {
|
|
6625
|
+
isNewUser: data.isNewUser || isNewUser,
|
|
6626
|
+
providerId: this.name,
|
|
6627
|
+
},
|
|
6628
|
+
};
|
|
6629
|
+
}
|
|
6630
|
+
validatePassword(password) {
|
|
6631
|
+
const { passwordStrength } = this.config;
|
|
6632
|
+
if (!passwordStrength)
|
|
6633
|
+
return;
|
|
6634
|
+
const errors = [];
|
|
6635
|
+
if (passwordStrength.minLength && password.length < passwordStrength.minLength) {
|
|
6636
|
+
errors.push(`at least ${passwordStrength.minLength} characters`);
|
|
6637
|
+
}
|
|
6638
|
+
if (passwordStrength.requireUppercase && !/[A-Z]/.test(password)) {
|
|
6639
|
+
errors.push('an uppercase letter');
|
|
6640
|
+
}
|
|
6641
|
+
if (passwordStrength.requireLowercase && !/[a-z]/.test(password)) {
|
|
6642
|
+
errors.push('a lowercase letter');
|
|
6643
|
+
}
|
|
6644
|
+
if (passwordStrength.requireNumbers && !/\d/.test(password)) {
|
|
6645
|
+
errors.push('a number');
|
|
6646
|
+
}
|
|
6647
|
+
if (passwordStrength.requireSpecialChars && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
|
|
6648
|
+
errors.push('a special character');
|
|
6649
|
+
}
|
|
6650
|
+
if (errors.length > 0) {
|
|
6651
|
+
throw new AuthError(AuthErrorCode.WEAK_PASSWORD, `Password must contain ${errors.join(', ')}`);
|
|
6652
|
+
}
|
|
6653
|
+
}
|
|
6654
|
+
formatPhoneNumber(phoneNumber) {
|
|
6655
|
+
let cleaned = phoneNumber.replace(/\D/g, '');
|
|
6656
|
+
if (!phoneNumber.startsWith('+')) {
|
|
6657
|
+
if (cleaned.length === 10) {
|
|
6658
|
+
cleaned = '1' + cleaned;
|
|
6659
|
+
}
|
|
6660
|
+
cleaned = this.config.countryCode.replace('+', '') + cleaned;
|
|
6661
|
+
}
|
|
6662
|
+
return '+' + cleaned;
|
|
6663
|
+
}
|
|
6664
|
+
maskPhoneNumber(phoneNumber) {
|
|
6665
|
+
const digits = phoneNumber.replace(/\D/g, '');
|
|
6666
|
+
const lastFour = digits.slice(-4);
|
|
6667
|
+
return `***-***-${lastFour}`;
|
|
6668
|
+
}
|
|
6669
|
+
generateUid(phoneNumber) {
|
|
6670
|
+
return `phone-password:${phoneNumber.replace(/\D/g, '')}`;
|
|
6671
|
+
}
|
|
6672
|
+
}
|
|
6673
|
+
|
|
6674
|
+
var phonePasswordProvider = /*#__PURE__*/Object.freeze({
|
|
6675
|
+
__proto__: null,
|
|
6676
|
+
PhonePasswordProvider: PhonePasswordProvider
|
|
6677
|
+
});
|
|
6678
|
+
|
|
4949
6679
|
exports.PlatformDetector = PlatformDetector;
|
|
4950
6680
|
exports.ProviderRegistry = ProviderRegistry;
|
|
4951
6681
|
exports.auth = auth;
|