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/plugin.cjs.js
CHANGED
|
@@ -2,43 +2,66 @@
|
|
|
2
2
|
|
|
3
3
|
var core = require('@capacitor/core');
|
|
4
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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
5
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
6
|
+
/**
|
|
7
|
+
* Reads a default log level from the build/runtime environment WITHOUT assuming a particular
|
|
8
|
+
* bundler or host. Checked defensively (each access wrapped) so it is safe in:
|
|
9
|
+
* - Vite / bundlers that define `import.meta.env`
|
|
10
|
+
* - Node / SSR where `globalThis.process.env` exists
|
|
11
|
+
* - Plain browsers where neither is present (falls back to 'warn')
|
|
12
|
+
*
|
|
13
|
+
* Intentional omissions for a PUBLISHED LIBRARY (see F-42):
|
|
14
|
+
* - We do NOT patch the host application's global `console.*`. A library silencing the host's
|
|
15
|
+
* console would be hostile and surprising.
|
|
16
|
+
* - We do NOT read the host's `localStorage` for a log-level switch. The host owns its storage;
|
|
17
|
+
* the consumer configures logging explicitly via `auth.configure({ logLevel })` or
|
|
18
|
+
* `logger.setLevel()`.
|
|
19
|
+
*/
|
|
20
|
+
function readEnvLogLevel() {
|
|
21
|
+
var _a;
|
|
22
|
+
const candidates = [];
|
|
23
|
+
try {
|
|
24
|
+
// import.meta.env may not exist (CJS) — guard the whole access.
|
|
25
|
+
const metaEnv = (_a = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs.js', document.baseURI).href)) })) === null || _a === void 0 ? void 0 : _a.env;
|
|
26
|
+
if (metaEnv) {
|
|
27
|
+
candidates.push(metaEnv.VITE_LOG_LEVEL, metaEnv.LOG_LEVEL);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch (_b) {
|
|
31
|
+
// import.meta unsupported in this environment — ignore.
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const proc = globalThis.process;
|
|
35
|
+
if (proc === null || proc === void 0 ? void 0 : proc.env) {
|
|
36
|
+
candidates.push(proc.env.VITE_LOG_LEVEL, proc.env.LOG_LEVEL);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
catch (_c) {
|
|
40
|
+
// process not available — ignore.
|
|
41
|
+
}
|
|
42
|
+
for (const value of candidates) {
|
|
43
|
+
if (value === 'debug' ||
|
|
44
|
+
value === 'info' ||
|
|
45
|
+
value === 'warn' ||
|
|
46
|
+
value === 'error' ||
|
|
47
|
+
value === 'silent') {
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
31
52
|
}
|
|
32
|
-
|
|
33
53
|
class Logger {
|
|
34
54
|
constructor(config) {
|
|
55
|
+
var _a, _b;
|
|
35
56
|
this.logLevels = {
|
|
36
57
|
debug: 0,
|
|
37
58
|
info: 1,
|
|
38
59
|
warn: 2,
|
|
39
60
|
error: 3,
|
|
61
|
+
silent: 4,
|
|
40
62
|
};
|
|
41
|
-
|
|
63
|
+
// An explicit logLevel from the caller wins; otherwise fall back to the env default, then 'warn'.
|
|
64
|
+
this.config = Object.assign(Object.assign({}, config), { logLevel: (_b = (_a = config.logLevel) !== null && _a !== void 0 ? _a : readEnvLogLevel()) !== null && _b !== void 0 ? _b : 'warn' });
|
|
42
65
|
}
|
|
43
66
|
shouldLog(level) {
|
|
44
67
|
if (!this.config.enableLogging)
|
|
@@ -70,13 +93,110 @@ class Logger {
|
|
|
70
93
|
console.error(this.formatMessage('error', message), error);
|
|
71
94
|
}
|
|
72
95
|
}
|
|
96
|
+
/** Verbose tracing — gated at `debug` level like {@link debug}. */
|
|
97
|
+
trace(message, ...args) {
|
|
98
|
+
if (this.shouldLog('debug')) {
|
|
99
|
+
console.trace(this.formatMessage('trace', message), ...args);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Tabular output — gated at `debug` level. Falls back to `debug` when `console.table` is absent. */
|
|
103
|
+
table(data, columns) {
|
|
104
|
+
if (this.shouldLog('debug')) {
|
|
105
|
+
if (typeof console.table === 'function') {
|
|
106
|
+
console.table(data, columns);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
console.debug(this.formatMessage('table', ''), data);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Opens a console group — gated at `debug` level. No-ops if `console.group` is absent. */
|
|
114
|
+
group(label) {
|
|
115
|
+
if (this.shouldLog('debug') && typeof console.group === 'function') {
|
|
116
|
+
console.group(label ? this.formatMessage('group', label) : undefined);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Closes a console group opened by {@link group}. */
|
|
120
|
+
groupEnd() {
|
|
121
|
+
if (this.shouldLog('debug') && typeof console.groupEnd === 'function') {
|
|
122
|
+
console.groupEnd();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Starts a timer — gated at `debug` level. No-ops if `console.time` is absent. */
|
|
126
|
+
time(label) {
|
|
127
|
+
if (this.shouldLog('debug') && typeof console.time === 'function') {
|
|
128
|
+
console.time(label);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Stops a timer started by {@link time} and logs the elapsed duration. */
|
|
132
|
+
timeEnd(label) {
|
|
133
|
+
if (this.shouldLog('debug') && typeof console.timeEnd === 'function') {
|
|
134
|
+
console.timeEnd(label);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
73
137
|
setLogLevel(level) {
|
|
74
138
|
this.config.logLevel = level;
|
|
75
139
|
}
|
|
140
|
+
/** Alias for {@link setLogLevel} matching the workspace logger convention. */
|
|
141
|
+
setLevel(level) {
|
|
142
|
+
this.config.logLevel = level;
|
|
143
|
+
}
|
|
144
|
+
getLevel() {
|
|
145
|
+
return this.config.logLevel;
|
|
146
|
+
}
|
|
76
147
|
setEnabled(enabled) {
|
|
77
148
|
this.config.enableLogging = enabled;
|
|
78
149
|
}
|
|
79
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Shared default logger instance used by package internals that don't receive a logger via
|
|
153
|
+
* dependency injection (e.g. {@link EventEmitter}, {@link WebStorage} defaults, the biometric
|
|
154
|
+
* provider). Enabled by default at `warn` level so only warnings + errors surface unless the
|
|
155
|
+
* consumer raises the level. Consumers can adjust it programmatically:
|
|
156
|
+
*
|
|
157
|
+
* ```ts
|
|
158
|
+
* import { defaultLogger } from 'capacitor-auth-manager';
|
|
159
|
+
* defaultLogger.setLevel('debug');
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
const defaultLogger = new Logger({
|
|
163
|
+
enableLogging: true,
|
|
164
|
+
logLevel: 'warn',
|
|
165
|
+
prefix: 'CapacitorAuthManager',
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
class EventEmitter {
|
|
169
|
+
/**
|
|
170
|
+
* @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
|
|
171
|
+
* so emitter errors honour the package log level instead of writing to `console` directly.
|
|
172
|
+
*/
|
|
173
|
+
constructor(logger = defaultLogger) {
|
|
174
|
+
this.listeners = new Set();
|
|
175
|
+
this.logger = logger;
|
|
176
|
+
}
|
|
177
|
+
emit(data) {
|
|
178
|
+
this.listeners.forEach((listener) => {
|
|
179
|
+
try {
|
|
180
|
+
listener(data);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
this.logger.error('Error in event listener:', error);
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
subscribe(listener) {
|
|
188
|
+
this.listeners.add(listener);
|
|
189
|
+
return () => {
|
|
190
|
+
this.listeners.delete(listener);
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
clear() {
|
|
194
|
+
this.listeners.clear();
|
|
195
|
+
}
|
|
196
|
+
get listenerCount() {
|
|
197
|
+
return this.listeners.size;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
80
200
|
|
|
81
201
|
exports.AuthProvider = void 0;
|
|
82
202
|
(function (AuthProvider) {
|
|
@@ -190,11 +310,46 @@ exports.AuthErrorCode = void 0;
|
|
|
190
310
|
AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
|
|
191
311
|
AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
|
|
192
312
|
AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
|
|
313
|
+
// --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
|
|
314
|
+
// magic-link / biometric / email-password / username-password / phone-password) throw enum
|
|
315
|
+
// codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
|
|
316
|
+
AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
|
|
317
|
+
AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
|
|
318
|
+
AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
|
|
319
|
+
AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
|
|
320
|
+
AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
|
|
321
|
+
AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
|
|
322
|
+
AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
|
|
323
|
+
AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
|
|
324
|
+
AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
|
|
325
|
+
AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
|
|
326
|
+
AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
|
|
327
|
+
AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
|
|
328
|
+
AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
|
|
329
|
+
AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
|
|
330
|
+
AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
|
|
331
|
+
AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
|
|
332
|
+
AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
|
|
333
|
+
AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
|
|
334
|
+
AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
|
|
335
|
+
AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
|
|
336
|
+
AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
|
|
337
|
+
AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
|
|
338
|
+
AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
|
|
339
|
+
AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
|
|
340
|
+
AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
|
|
193
341
|
})(exports.AuthErrorCode || (exports.AuthErrorCode = {}));
|
|
194
342
|
|
|
195
343
|
class WebStorage {
|
|
196
|
-
|
|
344
|
+
/**
|
|
345
|
+
* @param persistence Where to persist values (local / session / in-memory).
|
|
346
|
+
* @param prefix Key prefix to namespace this package's storage.
|
|
347
|
+
* @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
|
|
348
|
+
* so storage failures honour the package log level instead of writing to `console` directly.
|
|
349
|
+
*/
|
|
350
|
+
constructor(persistence = exports.AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
|
|
197
351
|
this.prefix = prefix;
|
|
352
|
+
this.logger = logger;
|
|
198
353
|
switch (persistence) {
|
|
199
354
|
case exports.AuthPersistence.SESSION:
|
|
200
355
|
this.storage = window.sessionStorage;
|
|
@@ -224,7 +379,7 @@ class WebStorage {
|
|
|
224
379
|
return null;
|
|
225
380
|
}
|
|
226
381
|
catch (error) {
|
|
227
|
-
|
|
382
|
+
this.logger.error('Storage get error:', error);
|
|
228
383
|
return null;
|
|
229
384
|
}
|
|
230
385
|
}
|
|
@@ -234,7 +389,7 @@ class WebStorage {
|
|
|
234
389
|
this.storage.setItem(this.prefix + key, stringValue);
|
|
235
390
|
}
|
|
236
391
|
catch (error) {
|
|
237
|
-
|
|
392
|
+
this.logger.error('Storage set error:', error);
|
|
238
393
|
throw error;
|
|
239
394
|
}
|
|
240
395
|
}
|
|
@@ -243,7 +398,7 @@ class WebStorage {
|
|
|
243
398
|
this.storage.removeItem(this.prefix + key);
|
|
244
399
|
}
|
|
245
400
|
catch (error) {
|
|
246
|
-
|
|
401
|
+
this.logger.error('Storage remove error:', error);
|
|
247
402
|
}
|
|
248
403
|
}
|
|
249
404
|
async clear() {
|
|
@@ -258,9 +413,60 @@ class WebStorage {
|
|
|
258
413
|
keys.forEach((key) => this.storage.removeItem(key));
|
|
259
414
|
}
|
|
260
415
|
catch (error) {
|
|
261
|
-
|
|
416
|
+
this.logger.error('Storage clear error:', error);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* StorageInterface backed by `@capacitor/preferences` (native KV — iOS UserDefaults /
|
|
422
|
+
* Android SharedPreferences). On a device this keeps tokens out of the webview's localStorage,
|
|
423
|
+
* which is the right default for Capacitor apps. Lazily imports the optional
|
|
424
|
+
* `@capacitor/preferences` package on first use; opt in by passing an instance as `storage`
|
|
425
|
+
* to `auth.configure({ storage: new CapacitorPreferencesStorage() })`.
|
|
426
|
+
*
|
|
427
|
+
* NOTE: Preferences is not hardware-encrypted. For secrecy at rest, inject a Keychain/Keystore
|
|
428
|
+
* (e.g. a secure-storage plugin) implementation of StorageInterface instead.
|
|
429
|
+
*/
|
|
430
|
+
class CapacitorPreferencesStorage {
|
|
431
|
+
constructor(prefix = 'cap_auth_') {
|
|
432
|
+
this.prefsPromise = null;
|
|
433
|
+
this.prefix = prefix;
|
|
434
|
+
}
|
|
435
|
+
getPrefs() {
|
|
436
|
+
if (!this.prefsPromise) {
|
|
437
|
+
this.prefsPromise = import('@capacitor/preferences').then((m) => m.Preferences);
|
|
438
|
+
}
|
|
439
|
+
return this.prefsPromise;
|
|
440
|
+
}
|
|
441
|
+
async get(key) {
|
|
442
|
+
const prefs = await this.getPrefs();
|
|
443
|
+
const { value } = await prefs.get({ key: this.prefix + key });
|
|
444
|
+
if (value === null || value === undefined) {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
try {
|
|
448
|
+
return JSON.parse(value);
|
|
449
|
+
}
|
|
450
|
+
catch (_a) {
|
|
451
|
+
return value;
|
|
262
452
|
}
|
|
263
453
|
}
|
|
454
|
+
async set(key, value) {
|
|
455
|
+
const prefs = await this.getPrefs();
|
|
456
|
+
const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
|
|
457
|
+
await prefs.set({ key: this.prefix + key, value: stringValue });
|
|
458
|
+
}
|
|
459
|
+
async remove(key) {
|
|
460
|
+
const prefs = await this.getPrefs();
|
|
461
|
+
await prefs.remove({ key: this.prefix + key });
|
|
462
|
+
}
|
|
463
|
+
async clear() {
|
|
464
|
+
const prefs = await this.getPrefs();
|
|
465
|
+
const { keys } = await prefs.keys();
|
|
466
|
+
await Promise.all(keys
|
|
467
|
+
.filter((k) => k.startsWith(this.prefix))
|
|
468
|
+
.map((k) => prefs.remove({ key: k })));
|
|
469
|
+
}
|
|
264
470
|
}
|
|
265
471
|
class InMemoryStorage {
|
|
266
472
|
constructor() {
|
|
@@ -293,11 +499,36 @@ class AuthError extends Error {
|
|
|
293
499
|
this.name = 'AuthError';
|
|
294
500
|
this.code = code;
|
|
295
501
|
this.provider = provider;
|
|
296
|
-
this.details = details;
|
|
297
|
-
// Maintains proper stack trace for where our error was thrown (only available on V8
|
|
298
|
-
|
|
299
|
-
|
|
502
|
+
this.details = AuthError.sanitizeDetails(details);
|
|
503
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8 engines:
|
|
504
|
+
// Node.js and Chromium). Typed locally so the package does not depend on @types/node globals.
|
|
505
|
+
const ErrorCtor = Error;
|
|
506
|
+
if (ErrorCtor.captureStackTrace) {
|
|
507
|
+
ErrorCtor.captureStackTrace(this, AuthError);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Produces a safe, shallow `details` object: redacts sensitive keys and keeps only JSON-safe
|
|
512
|
+
* primitives. Prevents tokens/PII embedded in a raw error or token-endpoint response body from
|
|
513
|
+
* being captured into AuthError.details (and thus logged or serialized via toJSON()).
|
|
514
|
+
*/
|
|
515
|
+
static sanitizeDetails(input) {
|
|
516
|
+
if (input === null || typeof input !== 'object') {
|
|
517
|
+
return undefined;
|
|
518
|
+
}
|
|
519
|
+
const out = {};
|
|
520
|
+
for (const [key, value] of Object.entries(input)) {
|
|
521
|
+
if (AuthError.SENSITIVE_KEY.test(key)) {
|
|
522
|
+
out[key] = '[redacted]';
|
|
523
|
+
}
|
|
524
|
+
else if (value === null ||
|
|
525
|
+
typeof value === 'string' ||
|
|
526
|
+
typeof value === 'number' ||
|
|
527
|
+
typeof value === 'boolean') {
|
|
528
|
+
out[key] = value;
|
|
529
|
+
}
|
|
300
530
|
}
|
|
531
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
301
532
|
}
|
|
302
533
|
static fromError(error, provider) {
|
|
303
534
|
if (error instanceof AuthError) {
|
|
@@ -305,7 +536,7 @@ class AuthError extends Error {
|
|
|
305
536
|
}
|
|
306
537
|
let code = exports.AuthErrorCode.INTERNAL_ERROR;
|
|
307
538
|
let message = 'An unknown error occurred';
|
|
308
|
-
|
|
539
|
+
const details = error;
|
|
309
540
|
if (error instanceof Error) {
|
|
310
541
|
message = error.message;
|
|
311
542
|
// Try to map common error patterns to specific error codes
|
|
@@ -340,6 +571,7 @@ class AuthError extends Error {
|
|
|
340
571
|
};
|
|
341
572
|
}
|
|
342
573
|
}
|
|
574
|
+
AuthError.SENSITIVE_KEY = /(token|secret|password|authorization|code_verifier|client_secret|credential|api[-_]?key|cookie)/i;
|
|
343
575
|
function isAuthError(error) {
|
|
344
576
|
return (error instanceof AuthError ||
|
|
345
577
|
(typeof error === 'object' &&
|
|
@@ -348,9 +580,18 @@ function isAuthError(error) {
|
|
|
348
580
|
error.code !== undefined));
|
|
349
581
|
}
|
|
350
582
|
|
|
583
|
+
function getPlatformWindow() {
|
|
584
|
+
return typeof window !== 'undefined'
|
|
585
|
+
? window
|
|
586
|
+
: undefined;
|
|
587
|
+
}
|
|
351
588
|
class PlatformDetector {
|
|
352
589
|
static getPlatform() {
|
|
353
|
-
|
|
590
|
+
// A cached NON-web result is final (native/electron never reverts to web). But a cached
|
|
591
|
+
// 'web' result is NOT treated as final: Capacitor can inject `window.Capacitor` after this
|
|
592
|
+
// module first runs (the native bridge initializes asynchronously), so re-evaluate while
|
|
593
|
+
// the last verdict was 'web' to pick up a late native environment. See F-26.
|
|
594
|
+
if (this.platformInfo && this.platformInfo.platform !== 'web') {
|
|
354
595
|
return this.platformInfo;
|
|
355
596
|
}
|
|
356
597
|
const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
|
|
@@ -368,11 +609,21 @@ class PlatformDetector {
|
|
|
368
609
|
};
|
|
369
610
|
return this.platformInfo;
|
|
370
611
|
}
|
|
612
|
+
/**
|
|
613
|
+
* Forces a fresh platform detection on the next {@link getPlatform} call, discarding any cached
|
|
614
|
+
* result. Useful if the runtime environment changes after startup (e.g. a Capacitor bridge that
|
|
615
|
+
* initializes late). Most callers can rely on the automatic re-check while the cached value is
|
|
616
|
+
* still 'web'.
|
|
617
|
+
*/
|
|
618
|
+
static reset() {
|
|
619
|
+
this.platformInfo = null;
|
|
620
|
+
}
|
|
371
621
|
static detectPlatform(userAgent) {
|
|
372
622
|
var _a, _b;
|
|
623
|
+
const win = getPlatformWindow();
|
|
373
624
|
// Check if running in Capacitor
|
|
374
|
-
if (
|
|
375
|
-
const capacitor =
|
|
625
|
+
if (win === null || win === void 0 ? void 0 : win.Capacitor) {
|
|
626
|
+
const capacitor = win.Capacitor;
|
|
376
627
|
if (capacitor.getPlatform) {
|
|
377
628
|
const platform = capacitor.getPlatform();
|
|
378
629
|
if (platform === 'ios' || platform === 'android') {
|
|
@@ -381,8 +632,7 @@ class PlatformDetector {
|
|
|
381
632
|
}
|
|
382
633
|
}
|
|
383
634
|
// Check if running in Electron
|
|
384
|
-
if (
|
|
385
|
-
((_b = (_a = window.process) === null || _a === void 0 ? void 0 : _a.versions) === null || _b === void 0 ? void 0 : _b.electron)) {
|
|
635
|
+
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) {
|
|
386
636
|
return 'electron';
|
|
387
637
|
}
|
|
388
638
|
// Check for React Native
|
|
@@ -411,124 +661,34 @@ class PlatformDetector {
|
|
|
411
661
|
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
|
|
412
662
|
}
|
|
413
663
|
static isCapacitorAvailable() {
|
|
414
|
-
|
|
664
|
+
var _a;
|
|
665
|
+
return !!((_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor);
|
|
415
666
|
}
|
|
416
667
|
static async checkCapacitorPlugin(pluginName) {
|
|
417
|
-
|
|
668
|
+
var _a;
|
|
669
|
+
const capacitor = (_a = getPlatformWindow()) === null || _a === void 0 ? void 0 : _a.Capacitor;
|
|
670
|
+
if (!capacitor) {
|
|
418
671
|
return false;
|
|
419
672
|
}
|
|
420
673
|
try {
|
|
421
|
-
|
|
422
|
-
return !!(Capacitor.Plugins && Capacitor.Plugins[pluginName]);
|
|
674
|
+
return !!(capacitor.Plugins && capacitor.Plugins[pluginName]);
|
|
423
675
|
}
|
|
424
|
-
catch (
|
|
676
|
+
catch (_b) {
|
|
425
677
|
return false;
|
|
426
678
|
}
|
|
427
679
|
}
|
|
428
680
|
}
|
|
429
681
|
PlatformDetector.platformInfo = null;
|
|
430
682
|
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
return this.manifests.get(name);
|
|
441
|
-
}
|
|
442
|
-
static async getProvider(name, config) {
|
|
443
|
-
var _b, _c;
|
|
444
|
-
// Check if already loaded
|
|
445
|
-
const existing = this.providers.get(name);
|
|
446
|
-
if (existing) {
|
|
447
|
-
return existing;
|
|
448
|
-
}
|
|
449
|
-
// Check if loader exists
|
|
450
|
-
const loader = this.loaders.get(name);
|
|
451
|
-
if (!loader) {
|
|
452
|
-
const manifest = this.manifests.get(name);
|
|
453
|
-
if (manifest) {
|
|
454
|
-
throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
|
|
455
|
-
}
|
|
456
|
-
throw new Error(`Unknown provider: ${name}`);
|
|
457
|
-
}
|
|
458
|
-
// Check platform support
|
|
459
|
-
const manifest = this.manifests.get(name);
|
|
460
|
-
if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
|
|
461
|
-
const platform = PlatformDetector.getPlatform();
|
|
462
|
-
if (!manifest.platforms.includes(platform.platform)) {
|
|
463
|
-
throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
try {
|
|
467
|
-
// Load the provider
|
|
468
|
-
const module = await loader();
|
|
469
|
-
const ProviderClass = module.default;
|
|
470
|
-
// Create instance
|
|
471
|
-
const provider = new ProviderClass(config);
|
|
472
|
-
// Initialize if needed
|
|
473
|
-
if (provider.initialize) {
|
|
474
|
-
await provider.initialize(config);
|
|
475
|
-
}
|
|
476
|
-
// Cache the provider
|
|
477
|
-
this.providers.set(name, provider);
|
|
478
|
-
return provider;
|
|
479
|
-
}
|
|
480
|
-
catch (error) {
|
|
481
|
-
// Check if it's a missing dependency error
|
|
482
|
-
if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot find module')) ||
|
|
483
|
-
((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Failed to resolve module'))) {
|
|
484
|
-
const manifest = this.manifests.get(name);
|
|
485
|
-
if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
|
|
486
|
-
throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
|
|
487
|
-
`Install the required package:\n` +
|
|
488
|
-
`npm install ${manifest.packageName}\n\n` +
|
|
489
|
-
`Then try again.`);
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
throw error;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
static clearProvider(name) {
|
|
496
|
-
const provider = this.providers.get(name);
|
|
497
|
-
if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
|
|
498
|
-
provider.dispose();
|
|
499
|
-
}
|
|
500
|
-
this.providers.delete(name);
|
|
501
|
-
}
|
|
502
|
-
static clearAll() {
|
|
503
|
-
for (const [, provider] of this.providers) {
|
|
504
|
-
if (provider.dispose) {
|
|
505
|
-
provider.dispose();
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
this.providers.clear();
|
|
509
|
-
}
|
|
510
|
-
static getAvailableProviders() {
|
|
511
|
-
return Array.from(this.manifests.keys());
|
|
512
|
-
}
|
|
513
|
-
static getSupportedProviders() {
|
|
514
|
-
const platform = PlatformDetector.getPlatform();
|
|
515
|
-
const supported = [];
|
|
516
|
-
for (const [name, manifest] of this.manifests) {
|
|
517
|
-
if (!manifest.platforms ||
|
|
518
|
-
manifest.platforms.includes(platform.platform)) {
|
|
519
|
-
supported.push(name);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
return Promise.resolve(supported);
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
_a = ProviderRegistry;
|
|
526
|
-
ProviderRegistry.providers = new Map();
|
|
527
|
-
ProviderRegistry.loaders = new Map();
|
|
528
|
-
ProviderRegistry.manifests = new Map();
|
|
529
|
-
(() => {
|
|
530
|
-
// Register built-in provider manifests
|
|
531
|
-
_a.registerManifest({
|
|
683
|
+
/**
|
|
684
|
+
* Built-in provider manifests (display metadata + human-readable setup instructions).
|
|
685
|
+
*
|
|
686
|
+
* Extracted from `provider-registry.ts` as a pure data module (zero logic) so the registry stays
|
|
687
|
+
* under the project's file-size guideline. `ProviderRegistry` imports this array and registers each
|
|
688
|
+
* entry in its static initializer — behaviour is unchanged (see F-40).
|
|
689
|
+
*/
|
|
690
|
+
const BUILT_IN_PROVIDER_MANIFESTS = [
|
|
691
|
+
{
|
|
532
692
|
name: 'google',
|
|
533
693
|
displayName: 'Google',
|
|
534
694
|
packageName: '@google/gsi',
|
|
@@ -560,8 +720,8 @@ To use Google authentication, you need to:
|
|
|
560
720
|
scopes: { type: 'array', items: 'string' },
|
|
561
721
|
hostedDomain: { type: 'string' },
|
|
562
722
|
},
|
|
563
|
-
}
|
|
564
|
-
|
|
723
|
+
},
|
|
724
|
+
{
|
|
565
725
|
name: 'apple',
|
|
566
726
|
displayName: 'Apple',
|
|
567
727
|
setupInstructions: `
|
|
@@ -589,8 +749,8 @@ To use Apple authentication:
|
|
|
589
749
|
redirectUri: { type: 'string', required: true },
|
|
590
750
|
scopes: { type: 'array', items: 'string' },
|
|
591
751
|
},
|
|
592
|
-
}
|
|
593
|
-
|
|
752
|
+
},
|
|
753
|
+
{
|
|
594
754
|
name: 'firebase',
|
|
595
755
|
displayName: 'Firebase Auth',
|
|
596
756
|
packageName: 'firebase',
|
|
@@ -624,8 +784,8 @@ To use Firebase authentication:
|
|
|
624
784
|
authDomain: { type: 'string', required: true },
|
|
625
785
|
projectId: { type: 'string', required: true },
|
|
626
786
|
},
|
|
627
|
-
}
|
|
628
|
-
|
|
787
|
+
},
|
|
788
|
+
{
|
|
629
789
|
name: 'microsoft',
|
|
630
790
|
displayName: 'Microsoft',
|
|
631
791
|
packageName: '@azure/msal-browser',
|
|
@@ -659,8 +819,8 @@ To use Microsoft authentication:
|
|
|
659
819
|
redirectUri: { type: 'string' },
|
|
660
820
|
scopes: { type: 'array', items: 'string' },
|
|
661
821
|
},
|
|
662
|
-
}
|
|
663
|
-
|
|
822
|
+
},
|
|
823
|
+
{
|
|
664
824
|
name: 'facebook',
|
|
665
825
|
displayName: 'Facebook',
|
|
666
826
|
setupInstructions: `
|
|
@@ -673,7 +833,7 @@ To use Facebook authentication:
|
|
|
673
833
|
- Configure OAuth redirect URIs
|
|
674
834
|
|
|
675
835
|
2. Add Facebook SDK to your HTML:
|
|
676
|
-
<script async defer crossorigin="anonymous"
|
|
836
|
+
<script async defer crossorigin="anonymous"
|
|
677
837
|
src="https://connect.facebook.net/en_US/sdk.js"></script>
|
|
678
838
|
|
|
679
839
|
3. Configure the provider:
|
|
@@ -692,8 +852,8 @@ To use Facebook authentication:
|
|
|
692
852
|
version: { type: 'string' },
|
|
693
853
|
scopes: { type: 'array', items: 'string' },
|
|
694
854
|
},
|
|
695
|
-
}
|
|
696
|
-
|
|
855
|
+
},
|
|
856
|
+
{
|
|
697
857
|
name: 'github',
|
|
698
858
|
displayName: 'GitHub',
|
|
699
859
|
setupInstructions: `
|
|
@@ -722,9 +882,8 @@ Note: You'll need a backend service to exchange the authorization code for an ac
|
|
|
722
882
|
redirectUri: { type: 'string' },
|
|
723
883
|
scopes: { type: 'array', items: 'string' },
|
|
724
884
|
},
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
_a.registerManifest({
|
|
885
|
+
},
|
|
886
|
+
{
|
|
728
887
|
name: 'magic-link',
|
|
729
888
|
displayName: 'Email Magic Link',
|
|
730
889
|
setupInstructions: `
|
|
@@ -751,8 +910,8 @@ To use Email Magic Link authentication:
|
|
|
751
910
|
verifyUrl: { type: 'string' },
|
|
752
911
|
redirectUrl: { type: 'string' },
|
|
753
912
|
},
|
|
754
|
-
}
|
|
755
|
-
|
|
913
|
+
},
|
|
914
|
+
{
|
|
756
915
|
name: 'sms',
|
|
757
916
|
displayName: 'SMS Authentication',
|
|
758
917
|
setupInstructions: `
|
|
@@ -781,8 +940,8 @@ To use SMS authentication:
|
|
|
781
940
|
countryCode: { type: 'string' },
|
|
782
941
|
codeLength: { type: 'number' },
|
|
783
942
|
},
|
|
784
|
-
}
|
|
785
|
-
|
|
943
|
+
},
|
|
944
|
+
{
|
|
786
945
|
name: 'email-password',
|
|
787
946
|
displayName: 'Email & Password',
|
|
788
947
|
setupInstructions: `
|
|
@@ -809,8 +968,8 @@ To use Email/Password authentication:
|
|
|
809
968
|
apiUrl: { type: 'string', required: true },
|
|
810
969
|
passwordRequirements: { type: 'object' },
|
|
811
970
|
},
|
|
812
|
-
}
|
|
813
|
-
|
|
971
|
+
},
|
|
972
|
+
{
|
|
814
973
|
name: 'biometric',
|
|
815
974
|
displayName: 'Biometric Authentication',
|
|
816
975
|
packageName: 'capacitor-biometric-authentication',
|
|
@@ -839,8 +998,8 @@ Note: Users must first authenticate with another method before enabling biometri
|
|
|
839
998
|
title: { type: 'string' },
|
|
840
999
|
subtitle: { type: 'string' },
|
|
841
1000
|
},
|
|
842
|
-
}
|
|
843
|
-
|
|
1001
|
+
},
|
|
1002
|
+
{
|
|
844
1003
|
name: 'slack',
|
|
845
1004
|
displayName: 'Slack',
|
|
846
1005
|
setupInstructions: `
|
|
@@ -883,8 +1042,8 @@ Note: Slack OAuth requires a backend service to exchange the authorization code
|
|
|
883
1042
|
scopes: { type: 'array', items: 'string' },
|
|
884
1043
|
teamId: { type: 'string' },
|
|
885
1044
|
},
|
|
886
|
-
}
|
|
887
|
-
|
|
1045
|
+
},
|
|
1046
|
+
{
|
|
888
1047
|
name: 'linkedin',
|
|
889
1048
|
displayName: 'LinkedIn',
|
|
890
1049
|
setupInstructions: `
|
|
@@ -928,8 +1087,8 @@ The redirect URI must be HTTPS in production (LinkedIn requirement).
|
|
|
928
1087
|
redirectUri: { type: 'string', required: true },
|
|
929
1088
|
scopes: { type: 'array', items: 'string' },
|
|
930
1089
|
},
|
|
931
|
-
}
|
|
932
|
-
|
|
1090
|
+
},
|
|
1091
|
+
{
|
|
933
1092
|
name: 'username-password',
|
|
934
1093
|
displayName: 'Username & Password',
|
|
935
1094
|
setupInstructions: `
|
|
@@ -989,80 +1148,256 @@ Note: This provider requires a backend service to handle authentication.
|
|
|
989
1148
|
passwordRequirements: { type: 'object' },
|
|
990
1149
|
allowSignUp: { type: 'boolean' },
|
|
991
1150
|
},
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
_a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
|
|
995
|
-
default: m.GoogleAuthProviderWeb,
|
|
996
|
-
})));
|
|
997
|
-
_a.registerLoader('apple', () => Promise.resolve().then(function () { return appleProvider; }).then((m) => ({
|
|
998
|
-
default: m.AppleAuthProviderWeb,
|
|
999
|
-
})));
|
|
1000
|
-
_a.registerLoader('microsoft', () => Promise.resolve().then(function () { return microsoftProvider; }).then((m) => ({
|
|
1001
|
-
default: m.MicrosoftAuthProviderWeb,
|
|
1002
|
-
})));
|
|
1003
|
-
_a.registerLoader('facebook', () => Promise.resolve().then(function () { return facebookProvider; }).then((m) => ({
|
|
1004
|
-
default: m.FacebookAuthProviderWeb,
|
|
1005
|
-
})));
|
|
1006
|
-
_a.registerLoader('github', () => Promise.resolve().then(function () { return githubProvider; }).then((m) => ({
|
|
1007
|
-
default: m.GitHubAuthProviderWeb,
|
|
1008
|
-
})));
|
|
1009
|
-
_a.registerLoader('firebase', () => Promise.resolve().then(function () { return firebaseProvider; }).then((m) => ({
|
|
1010
|
-
default: m.FirebaseAuthProviderWeb,
|
|
1011
|
-
})));
|
|
1012
|
-
_a.registerLoader('magic-link', () => Promise.resolve().then(function () { return magicLinkProvider; }).then((m) => ({
|
|
1013
|
-
default: m.MagicLinkProvider,
|
|
1014
|
-
})));
|
|
1015
|
-
_a.registerLoader('sms', () => Promise.resolve().then(function () { return smsProvider; }).then((m) => ({
|
|
1016
|
-
default: m.SMSProvider,
|
|
1017
|
-
})));
|
|
1018
|
-
_a.registerLoader('email-password', () => Promise.resolve().then(function () { return emailPasswordProvider; }).then((m) => ({
|
|
1019
|
-
default: m.EmailPasswordProvider,
|
|
1020
|
-
})));
|
|
1021
|
-
_a.registerLoader('biometric', () => Promise.resolve().then(function () { return biometricProvider; }).then((m) => ({
|
|
1022
|
-
default: m.BiometricProvider,
|
|
1023
|
-
})));
|
|
1024
|
-
_a.registerLoader('slack', () => Promise.resolve().then(function () { return slackProvider; }).then((m) => ({
|
|
1025
|
-
default: m.SlackProvider,
|
|
1026
|
-
})));
|
|
1027
|
-
_a.registerLoader('linkedin', () => Promise.resolve().then(function () { return linkedinProvider; }).then((m) => ({
|
|
1028
|
-
default: m.LinkedInProvider,
|
|
1029
|
-
})));
|
|
1030
|
-
_a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
|
|
1031
|
-
default: m.UsernamePasswordProvider,
|
|
1032
|
-
})));
|
|
1033
|
-
})();
|
|
1151
|
+
},
|
|
1152
|
+
];
|
|
1034
1153
|
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
isLoading: false,
|
|
1040
|
-
isAuthenticated: false,
|
|
1041
|
-
provider: null,
|
|
1042
|
-
};
|
|
1043
|
-
this.stateEmitter = new EventEmitter();
|
|
1044
|
-
this.config = {};
|
|
1045
|
-
this.isInitialized = false;
|
|
1046
|
-
this.tokenRefreshTimers = new Map();
|
|
1047
|
-
this.storage = new WebStorage('local');
|
|
1048
|
-
this.logger = new Logger({
|
|
1049
|
-
enableLogging: false,
|
|
1050
|
-
logLevel: 'info',
|
|
1051
|
-
prefix: 'AuthManager',
|
|
1052
|
-
});
|
|
1053
|
-
// Auto-initialize on first use
|
|
1054
|
-
if (typeof window !== 'undefined') {
|
|
1055
|
-
this.initialize().catch((err) => {
|
|
1056
|
-
this.logger.error('Auto-initialization failed:', err);
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1154
|
+
var _a;
|
|
1155
|
+
class ProviderRegistry {
|
|
1156
|
+
static registerManifest(manifest) {
|
|
1157
|
+
this.manifests.set(manifest.name, manifest);
|
|
1059
1158
|
}
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1159
|
+
static registerLoader(name, loader) {
|
|
1160
|
+
this.loaders.set(name, loader);
|
|
1161
|
+
}
|
|
1162
|
+
static getManifest(name) {
|
|
1163
|
+
return this.manifests.get(name);
|
|
1164
|
+
}
|
|
1165
|
+
static canonicalName(name) {
|
|
1166
|
+
var _b;
|
|
1167
|
+
return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
|
|
1168
|
+
}
|
|
1169
|
+
static async getProvider(name, options, deps) {
|
|
1170
|
+
var _b, _c, _d, _e;
|
|
1171
|
+
const key = this.canonicalName(name);
|
|
1172
|
+
// Check if already loaded
|
|
1173
|
+
const existing = this.providers.get(key);
|
|
1174
|
+
if (existing) {
|
|
1175
|
+
return existing;
|
|
1176
|
+
}
|
|
1177
|
+
// Check if loader exists
|
|
1178
|
+
const loader = this.loaders.get(key);
|
|
1179
|
+
if (!loader) {
|
|
1180
|
+
const manifest = this.manifests.get(key);
|
|
1181
|
+
if (manifest) {
|
|
1182
|
+
throw new Error(`Provider '${name}' is not loaded.\n\n${manifest.setupInstructions || `Please configure the ${manifest.displayName} provider.`}`);
|
|
1183
|
+
}
|
|
1184
|
+
throw new Error(`Unknown provider: ${name}`);
|
|
1185
|
+
}
|
|
1186
|
+
// Check platform support
|
|
1187
|
+
const manifest = this.manifests.get(key);
|
|
1188
|
+
if (manifest === null || manifest === void 0 ? void 0 : manifest.platforms) {
|
|
1189
|
+
const platform = PlatformDetector.getPlatform();
|
|
1190
|
+
if (!manifest.platforms.includes(platform.platform)) {
|
|
1191
|
+
throw new Error(`Provider '${name}' is not supported on ${platform.platform}`);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
try {
|
|
1195
|
+
// Load the provider class
|
|
1196
|
+
const module = await loader();
|
|
1197
|
+
const ProviderClass = module.default;
|
|
1198
|
+
// Build the constructor argument. BaseAuthProvider subclasses need a full
|
|
1199
|
+
// BaseProviderConfig ({ provider, options, storage, logger, persistence });
|
|
1200
|
+
// standalone providers take their options object directly.
|
|
1201
|
+
const storage = (_b = deps === null || deps === void 0 ? void 0 : deps.storage) !== null && _b !== void 0 ? _b : new WebStorage(exports.AuthPersistence.LOCAL);
|
|
1202
|
+
const logger = (_c = deps === null || deps === void 0 ? void 0 : deps.logger) !== null && _c !== void 0 ? _c : new Logger({
|
|
1203
|
+
enableLogging: false,
|
|
1204
|
+
logLevel: 'warn',
|
|
1205
|
+
prefix: 'AuthManager',
|
|
1206
|
+
});
|
|
1207
|
+
const constructorArg = this.STANDALONE_PROVIDERS.has(key)
|
|
1208
|
+
? (options !== null && options !== void 0 ? options : {})
|
|
1209
|
+
: {
|
|
1210
|
+
provider: key,
|
|
1211
|
+
options: (options !== null && options !== void 0 ? options : {}),
|
|
1212
|
+
storage,
|
|
1213
|
+
logger,
|
|
1214
|
+
persistence: deps === null || deps === void 0 ? void 0 : deps.persistence,
|
|
1215
|
+
};
|
|
1216
|
+
// Create instance
|
|
1217
|
+
const provider = new ProviderClass(constructorArg);
|
|
1218
|
+
// Initialize if supported (BaseAuthProvider.initialize takes no arguments)
|
|
1219
|
+
if (provider.initialize) {
|
|
1220
|
+
await provider.initialize();
|
|
1221
|
+
}
|
|
1222
|
+
// Cache the provider under its canonical key
|
|
1223
|
+
this.providers.set(key, provider);
|
|
1224
|
+
return provider;
|
|
1225
|
+
}
|
|
1226
|
+
catch (error) {
|
|
1227
|
+
// Check if it's a missing dependency error
|
|
1228
|
+
if (((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot find module')) ||
|
|
1229
|
+
((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to resolve module'))) {
|
|
1230
|
+
const manifest = this.manifests.get(this.canonicalName(name));
|
|
1231
|
+
if (manifest === null || manifest === void 0 ? void 0 : manifest.packageName) {
|
|
1232
|
+
throw new Error(`Missing dependency for ${manifest.displayName} provider.\n\n` +
|
|
1233
|
+
`Install the required package:\n` +
|
|
1234
|
+
`npm install ${manifest.packageName}\n\n` +
|
|
1235
|
+
`Then try again.`);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
throw error;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
static clearProvider(name) {
|
|
1242
|
+
const key = this.canonicalName(name);
|
|
1243
|
+
const provider = this.providers.get(key);
|
|
1244
|
+
if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
|
|
1245
|
+
provider.dispose();
|
|
1246
|
+
}
|
|
1247
|
+
this.providers.delete(key);
|
|
1248
|
+
}
|
|
1249
|
+
static clearAll() {
|
|
1250
|
+
for (const [, provider] of this.providers) {
|
|
1251
|
+
if (provider.dispose) {
|
|
1252
|
+
provider.dispose();
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
this.providers.clear();
|
|
1256
|
+
}
|
|
1257
|
+
static getAvailableProviders() {
|
|
1258
|
+
return Array.from(this.manifests.keys());
|
|
1259
|
+
}
|
|
1260
|
+
static getSupportedProviders() {
|
|
1261
|
+
const platform = PlatformDetector.getPlatform();
|
|
1262
|
+
const supported = [];
|
|
1263
|
+
for (const [name, manifest] of this.manifests) {
|
|
1264
|
+
if (!manifest.platforms ||
|
|
1265
|
+
manifest.platforms.includes(platform.platform)) {
|
|
1266
|
+
supported.push(name);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
return Promise.resolve(supported);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
_a = ProviderRegistry;
|
|
1273
|
+
ProviderRegistry.providers = new Map();
|
|
1274
|
+
ProviderRegistry.loaders = new Map();
|
|
1275
|
+
ProviderRegistry.manifests = new Map();
|
|
1276
|
+
/** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
|
|
1277
|
+
ProviderRegistry.STANDALONE_PROVIDERS = new Set([
|
|
1278
|
+
'magic-link',
|
|
1279
|
+
'sms',
|
|
1280
|
+
'email-password',
|
|
1281
|
+
'username-password',
|
|
1282
|
+
'biometric',
|
|
1283
|
+
'phone-password',
|
|
1284
|
+
'email-code',
|
|
1285
|
+
]);
|
|
1286
|
+
/** Maps AuthProvider enum values (some underscored) to the registered hyphenated loader keys. */
|
|
1287
|
+
ProviderRegistry.NAME_ALIASES = {
|
|
1288
|
+
email_magic_link: 'magic-link',
|
|
1289
|
+
username_password: 'username-password',
|
|
1290
|
+
phone_password: 'phone-password',
|
|
1291
|
+
email_code: 'email-code',
|
|
1292
|
+
};
|
|
1293
|
+
(() => {
|
|
1294
|
+
// Register built-in provider manifests (data lives in provider-manifests.ts — F-40).
|
|
1295
|
+
for (const manifest of BUILT_IN_PROVIDER_MANIFESTS) {
|
|
1296
|
+
_a.registerManifest(manifest);
|
|
1297
|
+
}
|
|
1298
|
+
// Register provider loaders
|
|
1299
|
+
_a.registerLoader('google', () => Promise.resolve().then(function () { return googleProvider; }).then((m) => ({
|
|
1300
|
+
default: m.GoogleAuthProviderWeb,
|
|
1301
|
+
})));
|
|
1302
|
+
_a.registerLoader('apple', () => Promise.resolve().then(function () { return appleProvider; }).then((m) => ({
|
|
1303
|
+
default: m.AppleAuthProviderWeb,
|
|
1304
|
+
})));
|
|
1305
|
+
_a.registerLoader('microsoft', () => Promise.resolve().then(function () { return microsoftProvider; }).then((m) => ({
|
|
1306
|
+
default: m.MicrosoftAuthProviderWeb,
|
|
1307
|
+
})));
|
|
1308
|
+
_a.registerLoader('facebook', () => Promise.resolve().then(function () { return facebookProvider; }).then((m) => ({
|
|
1309
|
+
default: m.FacebookAuthProviderWeb,
|
|
1310
|
+
})));
|
|
1311
|
+
_a.registerLoader('github', () => Promise.resolve().then(function () { return githubProvider; }).then((m) => ({
|
|
1312
|
+
default: m.GitHubAuthProviderWeb,
|
|
1313
|
+
})));
|
|
1314
|
+
_a.registerLoader('firebase', () => Promise.resolve().then(function () { return firebaseProvider; }).then((m) => ({
|
|
1315
|
+
default: m.FirebaseAuthProviderWeb,
|
|
1316
|
+
})));
|
|
1317
|
+
_a.registerLoader('magic-link', () => Promise.resolve().then(function () { return magicLinkProvider; }).then((m) => ({
|
|
1318
|
+
default: m.MagicLinkProvider,
|
|
1319
|
+
})));
|
|
1320
|
+
_a.registerLoader('sms', () => Promise.resolve().then(function () { return smsProvider; }).then((m) => ({
|
|
1321
|
+
default: m.SMSProvider,
|
|
1322
|
+
})));
|
|
1323
|
+
_a.registerLoader('email-password', () => Promise.resolve().then(function () { return emailPasswordProvider; }).then((m) => ({
|
|
1324
|
+
default: m.EmailPasswordProvider,
|
|
1325
|
+
})));
|
|
1326
|
+
_a.registerLoader('biometric', () => Promise.resolve().then(function () { return biometricProvider; }).then((m) => ({
|
|
1327
|
+
default: m.BiometricProvider,
|
|
1328
|
+
})));
|
|
1329
|
+
_a.registerLoader('slack', () => Promise.resolve().then(function () { return slackProvider; }).then((m) => ({
|
|
1330
|
+
default: m.SlackProvider,
|
|
1331
|
+
})));
|
|
1332
|
+
_a.registerLoader('linkedin', () => Promise.resolve().then(function () { return linkedinProvider; }).then((m) => ({
|
|
1333
|
+
default: m.LinkedInProvider,
|
|
1334
|
+
})));
|
|
1335
|
+
_a.registerLoader('username-password', () => Promise.resolve().then(function () { return usernamePasswordProvider; }).then((m) => ({
|
|
1336
|
+
default: m.UsernamePasswordProvider,
|
|
1337
|
+
})));
|
|
1338
|
+
_a.registerLoader('email-code', () => Promise.resolve().then(function () { return emailCodeProvider; }).then((m) => ({
|
|
1339
|
+
default: m.EmailCodeProvider,
|
|
1340
|
+
})));
|
|
1341
|
+
_a.registerLoader('phone-password', () => Promise.resolve().then(function () { return phonePasswordProvider; }).then((m) => ({
|
|
1342
|
+
default: m.PhonePasswordProvider,
|
|
1343
|
+
})));
|
|
1344
|
+
})();
|
|
1345
|
+
|
|
1346
|
+
/**
|
|
1347
|
+
* Maps the config's persistence literal to the {@link AuthPersistence} enum WebStorage expects.
|
|
1348
|
+
* Critically, `'memory'` maps to {@link AuthPersistence.NONE} (`'none'`) — previously the literal
|
|
1349
|
+
* was cast via `as any` and fell through WebStorage's switch to localStorage, silently breaking
|
|
1350
|
+
* in-memory persistence.
|
|
1351
|
+
*/
|
|
1352
|
+
function toAuthPersistence(persistence) {
|
|
1353
|
+
switch (persistence) {
|
|
1354
|
+
case 'session':
|
|
1355
|
+
return exports.AuthPersistence.SESSION;
|
|
1356
|
+
case 'memory':
|
|
1357
|
+
return exports.AuthPersistence.NONE;
|
|
1358
|
+
case 'local':
|
|
1359
|
+
default:
|
|
1360
|
+
return exports.AuthPersistence.LOCAL;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
class AuthManagerCore {
|
|
1364
|
+
constructor() {
|
|
1365
|
+
this.state = {
|
|
1366
|
+
user: null,
|
|
1367
|
+
isLoading: false,
|
|
1368
|
+
isAuthenticated: false,
|
|
1369
|
+
provider: null,
|
|
1370
|
+
};
|
|
1371
|
+
this.stateEmitter = new EventEmitter();
|
|
1372
|
+
this.config = {};
|
|
1373
|
+
this.isInitialized = false;
|
|
1374
|
+
this.tokenRefreshTimers = new Map();
|
|
1375
|
+
this.initPromise = null;
|
|
1376
|
+
this.logger = new Logger({
|
|
1377
|
+
enableLogging: false,
|
|
1378
|
+
logLevel: 'info',
|
|
1379
|
+
prefix: 'AuthManager',
|
|
1380
|
+
});
|
|
1381
|
+
this.storage = new WebStorage(exports.AuthPersistence.LOCAL, undefined, this.logger);
|
|
1382
|
+
this.currentPersistence = 'local';
|
|
1383
|
+
// Auto-initialize on first use
|
|
1384
|
+
if (typeof window !== 'undefined') {
|
|
1385
|
+
this.initialize().catch((err) => {
|
|
1386
|
+
this.logger.error('Auto-initialization failed:', err);
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
async initialize(config) {
|
|
1391
|
+
if (this.isInitialized && !config) {
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
// Coalesce concurrent first-time initialization (e.g. the constructor's auto-init
|
|
1395
|
+
// racing with an explicit initialize()) so restoreAuthState does not run twice.
|
|
1396
|
+
if (this.initPromise && !config) {
|
|
1397
|
+
return this.initPromise;
|
|
1398
|
+
}
|
|
1399
|
+
if (config) {
|
|
1400
|
+
this.config = Object.assign(Object.assign({}, this.config), config);
|
|
1066
1401
|
}
|
|
1067
1402
|
// Configure logger
|
|
1068
1403
|
if (this.config.enableLogging !== undefined) {
|
|
@@ -1071,12 +1406,21 @@ class AuthManagerCore {
|
|
|
1071
1406
|
if (this.config.logLevel) {
|
|
1072
1407
|
this.logger.setLogLevel(this.config.logLevel);
|
|
1073
1408
|
}
|
|
1074
|
-
//
|
|
1075
|
-
|
|
1076
|
-
|
|
1409
|
+
// A custom storage backend (e.g. secure native storage) takes precedence. Otherwise only
|
|
1410
|
+
// recreate storage when persistence actually changes (don't discard in-memory state on a
|
|
1411
|
+
// no-op re-initialize).
|
|
1412
|
+
if (this.config.storage) {
|
|
1413
|
+
this.storage = this.config.storage;
|
|
1414
|
+
this.currentPersistence = 'custom';
|
|
1415
|
+
}
|
|
1416
|
+
else if (this.config.persistence &&
|
|
1417
|
+
this.config.persistence !== this.currentPersistence) {
|
|
1418
|
+
this.storage = new WebStorage(toAuthPersistence(this.config.persistence), undefined, this.logger);
|
|
1419
|
+
this.currentPersistence = this.config.persistence;
|
|
1077
1420
|
}
|
|
1078
1421
|
// Restore auth state
|
|
1079
|
-
|
|
1422
|
+
this.initPromise = this.restoreAuthState();
|
|
1423
|
+
await this.initPromise;
|
|
1080
1424
|
this.isInitialized = true;
|
|
1081
1425
|
this.logger.info('Auth manager initialized');
|
|
1082
1426
|
}
|
|
@@ -1088,12 +1432,23 @@ class AuthManagerCore {
|
|
|
1088
1432
|
if (config.logLevel) {
|
|
1089
1433
|
this.logger.setLogLevel(config.logLevel);
|
|
1090
1434
|
}
|
|
1091
|
-
if (config.
|
|
1092
|
-
this.storage =
|
|
1435
|
+
if (config.storage) {
|
|
1436
|
+
this.storage = config.storage;
|
|
1437
|
+
this.currentPersistence = 'custom';
|
|
1438
|
+
}
|
|
1439
|
+
else if (config.persistence &&
|
|
1440
|
+
config.persistence !== this.currentPersistence) {
|
|
1441
|
+
this.storage = new WebStorage(toAuthPersistence(config.persistence), undefined, this.logger);
|
|
1442
|
+
this.currentPersistence = config.persistence;
|
|
1443
|
+
}
|
|
1444
|
+
// Now that providers may be configured, (re)attempt session restore so a persisted
|
|
1445
|
+
// session is rehydrated even when the singleton auto-initialized before configure().
|
|
1446
|
+
if (config.providers && Object.keys(config.providers).length > 0) {
|
|
1447
|
+
void this.restoreAuthState();
|
|
1093
1448
|
}
|
|
1094
1449
|
}
|
|
1095
1450
|
async signIn(providerOrOptions) {
|
|
1096
|
-
var _a;
|
|
1451
|
+
var _a, _b, _c;
|
|
1097
1452
|
await this.ensureInitialized();
|
|
1098
1453
|
let providerName;
|
|
1099
1454
|
let signInOptions = {};
|
|
@@ -1119,10 +1474,12 @@ class AuthManagerCore {
|
|
|
1119
1474
|
throw new AuthError('auth/missing-configuration', `Provider '${providerName}' is not configured. Call auth.configure() first.`);
|
|
1120
1475
|
}
|
|
1121
1476
|
// Get provider instance
|
|
1122
|
-
const provider = await ProviderRegistry.getProvider(providerName, providerConfig);
|
|
1123
|
-
// Sign in
|
|
1477
|
+
const provider = await ProviderRegistry.getProvider(providerName, providerConfig, this.getProviderDeps());
|
|
1478
|
+
// Sign in. Credentials are spread to the top level (where credential providers read
|
|
1479
|
+
// email/password/phoneNumber/username) AND kept nested under `credentials` for
|
|
1480
|
+
// providers that read them there.
|
|
1124
1481
|
this.logger.info(`Signing in with ${providerName}`);
|
|
1125
|
-
const result = await provider.signIn(Object.assign(Object.assign({}, signInOptions.options), { credentials: signInOptions.credentials }));
|
|
1482
|
+
const result = await provider.signIn(Object.assign(Object.assign(Object.assign({}, signInOptions.options), ((_b = signInOptions.credentials) !== null && _b !== void 0 ? _b : {})), { credentials: signInOptions.credentials }));
|
|
1126
1483
|
// Update state
|
|
1127
1484
|
this.updateState({
|
|
1128
1485
|
user: result.user,
|
|
@@ -1137,7 +1494,7 @@ class AuthManagerCore {
|
|
|
1137
1494
|
credential: result.credential,
|
|
1138
1495
|
});
|
|
1139
1496
|
// Setup token refresh
|
|
1140
|
-
if (this.config.autoRefreshToken && result.credential.refreshToken) {
|
|
1497
|
+
if (this.config.autoRefreshToken && ((_c = result.credential) === null || _c === void 0 ? void 0 : _c.refreshToken)) {
|
|
1141
1498
|
this.setupTokenRefresh(providerName, result.credential);
|
|
1142
1499
|
}
|
|
1143
1500
|
return result;
|
|
@@ -1160,11 +1517,17 @@ class AuthManagerCore {
|
|
|
1160
1517
|
try {
|
|
1161
1518
|
// Get provider instance
|
|
1162
1519
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[provider];
|
|
1163
|
-
const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig);
|
|
1520
|
+
const providerInstance = await ProviderRegistry.getProvider(provider, providerConfig, this.getProviderDeps());
|
|
1164
1521
|
// Sign out
|
|
1165
1522
|
await providerInstance.signOut(options);
|
|
1166
|
-
// Clear token refresh
|
|
1167
|
-
|
|
1523
|
+
// Clear token refresh. When no specific provider was targeted, clear ALL refresh timers
|
|
1524
|
+
// (not just the active provider's) so a global sign-out leaves no orphaned timers behind.
|
|
1525
|
+
if (options === null || options === void 0 ? void 0 : options.provider) {
|
|
1526
|
+
this.clearTokenRefresh(provider);
|
|
1527
|
+
}
|
|
1528
|
+
else {
|
|
1529
|
+
this.clearAllTokenRefresh();
|
|
1530
|
+
}
|
|
1168
1531
|
// Clear state
|
|
1169
1532
|
this.updateState({
|
|
1170
1533
|
user: null,
|
|
@@ -1195,7 +1558,7 @@ class AuthManagerCore {
|
|
|
1195
1558
|
return this.state.provider;
|
|
1196
1559
|
}
|
|
1197
1560
|
async refreshToken(provider) {
|
|
1198
|
-
var _a;
|
|
1561
|
+
var _a, _b;
|
|
1199
1562
|
await this.ensureInitialized();
|
|
1200
1563
|
const targetProvider = provider || this.state.provider;
|
|
1201
1564
|
if (!targetProvider) {
|
|
@@ -1203,7 +1566,7 @@ class AuthManagerCore {
|
|
|
1203
1566
|
}
|
|
1204
1567
|
try {
|
|
1205
1568
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[targetProvider];
|
|
1206
|
-
const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig);
|
|
1569
|
+
const providerInstance = await ProviderRegistry.getProvider(targetProvider, providerConfig, this.getProviderDeps());
|
|
1207
1570
|
if (!providerInstance.refreshToken) {
|
|
1208
1571
|
throw new AuthError('auth/operation-not-supported', `Provider '${targetProvider}' does not support token refresh`);
|
|
1209
1572
|
}
|
|
@@ -1211,7 +1574,7 @@ class AuthManagerCore {
|
|
|
1211
1574
|
// Update user
|
|
1212
1575
|
this.updateState({ user: result.user });
|
|
1213
1576
|
// Setup new token refresh
|
|
1214
|
-
if (this.config.autoRefreshToken && result.credential.refreshToken) {
|
|
1577
|
+
if (this.config.autoRefreshToken && ((_b = result.credential) === null || _b === void 0 ? void 0 : _b.refreshToken)) {
|
|
1215
1578
|
this.setupTokenRefresh(targetProvider, result.credential);
|
|
1216
1579
|
}
|
|
1217
1580
|
return result;
|
|
@@ -1221,6 +1584,177 @@ class AuthManagerCore {
|
|
|
1221
1584
|
throw AuthError.fromError(error);
|
|
1222
1585
|
}
|
|
1223
1586
|
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Links an additional auth credential to the current account, delegating to the resolved
|
|
1589
|
+
* provider's optional `linkAccount`. Throws `OPERATION_NOT_ALLOWED` if the provider doesn't
|
|
1590
|
+
* implement it. Mirrors `CapacitorAuthManagerWeb.linkAccount` so React/Vue/Angular consumers
|
|
1591
|
+
* reach the same capability through the `auth` singleton.
|
|
1592
|
+
*/
|
|
1593
|
+
async linkAccount(options) {
|
|
1594
|
+
await this.ensureInitialized();
|
|
1595
|
+
const providerName = typeof options.provider === 'string'
|
|
1596
|
+
? options.provider
|
|
1597
|
+
: exports.AuthProvider[options.provider];
|
|
1598
|
+
const provider = await this.resolveProvider(providerName);
|
|
1599
|
+
if (typeof provider.linkAccount !== 'function') {
|
|
1600
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `linkAccount not supported for ${providerName}`);
|
|
1601
|
+
}
|
|
1602
|
+
try {
|
|
1603
|
+
const result = await provider.linkAccount(options);
|
|
1604
|
+
this.updateState({ user: result.user });
|
|
1605
|
+
return result;
|
|
1606
|
+
}
|
|
1607
|
+
catch (error) {
|
|
1608
|
+
this.logger.error(`Account linking failed for ${providerName}`, error);
|
|
1609
|
+
throw AuthError.fromError(error);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* Unlinks a provider credential from the current account via the resolved provider's optional
|
|
1614
|
+
* `unlinkAccount`. Throws `OPERATION_NOT_ALLOWED` if unsupported.
|
|
1615
|
+
*/
|
|
1616
|
+
async unlinkAccount(options) {
|
|
1617
|
+
await this.ensureInitialized();
|
|
1618
|
+
const providerName = typeof options.provider === 'string'
|
|
1619
|
+
? options.provider
|
|
1620
|
+
: exports.AuthProvider[options.provider];
|
|
1621
|
+
const provider = await this.resolveProvider(providerName);
|
|
1622
|
+
if (typeof provider.unlinkAccount !== 'function') {
|
|
1623
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `unlinkAccount not supported for ${providerName}`);
|
|
1624
|
+
}
|
|
1625
|
+
try {
|
|
1626
|
+
await provider.unlinkAccount(options);
|
|
1627
|
+
}
|
|
1628
|
+
catch (error) {
|
|
1629
|
+
this.logger.error(`Account unlinking failed for ${providerName}`, error);
|
|
1630
|
+
throw AuthError.fromError(error);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
/**
|
|
1634
|
+
* Revokes the access/refresh token for a provider (current provider when `provider` is omitted),
|
|
1635
|
+
* delegating to the provider's optional `revokeAccess`. Throws `OPERATION_NOT_ALLOWED` if
|
|
1636
|
+
* unsupported.
|
|
1637
|
+
*/
|
|
1638
|
+
async revokeAccess(token, provider) {
|
|
1639
|
+
await this.ensureInitialized();
|
|
1640
|
+
const targetProvider = provider || this.state.provider;
|
|
1641
|
+
if (!targetProvider) {
|
|
1642
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to revoke access for');
|
|
1643
|
+
}
|
|
1644
|
+
const providerInstance = await this.resolveProvider(targetProvider);
|
|
1645
|
+
if (typeof providerInstance.revokeAccess !== 'function') {
|
|
1646
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `revokeAccess not supported for ${targetProvider}`);
|
|
1647
|
+
}
|
|
1648
|
+
try {
|
|
1649
|
+
await providerInstance.revokeAccess(token);
|
|
1650
|
+
}
|
|
1651
|
+
catch (error) {
|
|
1652
|
+
this.logger.error(`Access revocation failed for ${targetProvider}`, error);
|
|
1653
|
+
throw AuthError.fromError(error);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
/**
|
|
1657
|
+
* Returns the current ID token for a provider (current provider when `provider` is omitted) by
|
|
1658
|
+
* delegating to the provider's optional `getIdToken`. Throws `OPERATION_NOT_ALLOWED` if the
|
|
1659
|
+
* provider doesn't issue/expose ID tokens.
|
|
1660
|
+
*/
|
|
1661
|
+
async getIdToken(options) {
|
|
1662
|
+
var _a;
|
|
1663
|
+
await this.ensureInitialized();
|
|
1664
|
+
const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
|
|
1665
|
+
? typeof options.provider === 'string'
|
|
1666
|
+
? options.provider
|
|
1667
|
+
: exports.AuthProvider[options.provider]
|
|
1668
|
+
: undefined) || this.state.provider;
|
|
1669
|
+
if (!targetProvider) {
|
|
1670
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active auth session to get an ID token for');
|
|
1671
|
+
}
|
|
1672
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1673
|
+
const getIdTokenFn = provider.getIdToken;
|
|
1674
|
+
if (typeof getIdTokenFn !== 'function') {
|
|
1675
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `getIdToken not supported for ${targetProvider}`);
|
|
1676
|
+
}
|
|
1677
|
+
try {
|
|
1678
|
+
return await getIdTokenFn.call(provider, (_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
|
|
1679
|
+
}
|
|
1680
|
+
catch (error) {
|
|
1681
|
+
this.logger.error(`getIdToken failed for ${targetProvider}`, error);
|
|
1682
|
+
throw AuthError.fromError(error);
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Updates the signed-in user's profile via the current provider's optional `updateProfile`.
|
|
1687
|
+
* Throws `OPERATION_NOT_ALLOWED` if the provider doesn't implement it.
|
|
1688
|
+
*/
|
|
1689
|
+
async updateProfile(options) {
|
|
1690
|
+
await this.ensureInitialized();
|
|
1691
|
+
const targetProvider = this.state.provider;
|
|
1692
|
+
if (!targetProvider) {
|
|
1693
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
|
|
1694
|
+
}
|
|
1695
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1696
|
+
const updateFn = provider.updateProfile;
|
|
1697
|
+
if (typeof updateFn !== 'function') {
|
|
1698
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `updateProfile not supported for ${targetProvider}`);
|
|
1699
|
+
}
|
|
1700
|
+
try {
|
|
1701
|
+
const updatedUser = await updateFn.call(provider, options);
|
|
1702
|
+
this.updateState({ user: updatedUser });
|
|
1703
|
+
return updatedUser;
|
|
1704
|
+
}
|
|
1705
|
+
catch (error) {
|
|
1706
|
+
this.logger.error(`updateProfile failed for ${targetProvider}`, error);
|
|
1707
|
+
throw AuthError.fromError(error);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
/**
|
|
1711
|
+
* Deletes the current account via the provider's optional `deleteAccount` (current provider when
|
|
1712
|
+
* `provider` is omitted), then clears local state. Throws `OPERATION_NOT_ALLOWED` if the provider
|
|
1713
|
+
* doesn't implement it.
|
|
1714
|
+
*/
|
|
1715
|
+
async deleteAccount(options) {
|
|
1716
|
+
await this.ensureInitialized();
|
|
1717
|
+
const targetProvider = ((options === null || options === void 0 ? void 0 : options.provider) !== undefined
|
|
1718
|
+
? typeof options.provider === 'string'
|
|
1719
|
+
? options.provider
|
|
1720
|
+
: exports.AuthProvider[options.provider]
|
|
1721
|
+
: undefined) || this.state.provider;
|
|
1722
|
+
if (!targetProvider) {
|
|
1723
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
|
|
1724
|
+
}
|
|
1725
|
+
const provider = await this.resolveProvider(targetProvider);
|
|
1726
|
+
const deleteFn = provider.deleteAccount;
|
|
1727
|
+
if (typeof deleteFn !== 'function') {
|
|
1728
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
|
|
1729
|
+
}
|
|
1730
|
+
try {
|
|
1731
|
+
await deleteFn.call(provider);
|
|
1732
|
+
// Account deleted server-side: clear local session + timers.
|
|
1733
|
+
this.clearTokenRefresh(targetProvider);
|
|
1734
|
+
this.updateState({
|
|
1735
|
+
user: null,
|
|
1736
|
+
isAuthenticated: false,
|
|
1737
|
+
provider: null,
|
|
1738
|
+
});
|
|
1739
|
+
await this.storage.remove('auth_state');
|
|
1740
|
+
}
|
|
1741
|
+
catch (error) {
|
|
1742
|
+
this.logger.error(`deleteAccount failed for ${targetProvider}`, error);
|
|
1743
|
+
throw AuthError.fromError(error);
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Whether a provider has been supplied to `configure()`/`initialize()`. Public accessor so
|
|
1748
|
+
* adapters (React/Vue/Angular) no longer reach into the private `config` via `as any`.
|
|
1749
|
+
*/
|
|
1750
|
+
isProviderConfigured(name) {
|
|
1751
|
+
var _a;
|
|
1752
|
+
return !!((_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name]);
|
|
1753
|
+
}
|
|
1754
|
+
/** Names of every provider supplied to `configure()`/`initialize()`. */
|
|
1755
|
+
getConfiguredProviders() {
|
|
1756
|
+
return this.config.providers ? Object.keys(this.config.providers) : [];
|
|
1757
|
+
}
|
|
1224
1758
|
onAuthStateChange(listener) {
|
|
1225
1759
|
// Immediately call with current state
|
|
1226
1760
|
listener(this.getAuthState());
|
|
@@ -1242,6 +1776,18 @@ class AuthManagerCore {
|
|
|
1242
1776
|
await this.initialize();
|
|
1243
1777
|
}
|
|
1244
1778
|
}
|
|
1779
|
+
getProviderDeps() {
|
|
1780
|
+
return { storage: this.storage, logger: this.logger };
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Resolves a provider instance through the registry, threading the configured options and the
|
|
1784
|
+
* manager's shared storage/logger. Shared by the capability methods (link/unlink/revoke/
|
|
1785
|
+
* getIdToken/updateProfile/deleteAccount).
|
|
1786
|
+
*/
|
|
1787
|
+
async resolveProvider(name) {
|
|
1788
|
+
var _a;
|
|
1789
|
+
return ProviderRegistry.getProvider(name, (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[name], this.getProviderDeps());
|
|
1790
|
+
}
|
|
1245
1791
|
updateState(partial) {
|
|
1246
1792
|
this.state = Object.assign(Object.assign({}, this.state), partial);
|
|
1247
1793
|
this.stateEmitter.emit(this.state);
|
|
@@ -1255,7 +1801,7 @@ class AuthManagerCore {
|
|
|
1255
1801
|
const providerConfig = (_a = this.config.providers) === null || _a === void 0 ? void 0 : _a[stored.provider];
|
|
1256
1802
|
if (providerConfig) {
|
|
1257
1803
|
try {
|
|
1258
|
-
const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig);
|
|
1804
|
+
const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
|
|
1259
1805
|
const currentUser = await provider.getCurrentUser();
|
|
1260
1806
|
if (currentUser) {
|
|
1261
1807
|
this.updateState({
|
|
@@ -1289,16 +1835,35 @@ class AuthManagerCore {
|
|
|
1289
1835
|
const buffer = this.config.tokenRefreshBuffer || 300000; // 5 minutes
|
|
1290
1836
|
const refreshTime = credential.expiresAt - buffer - Date.now();
|
|
1291
1837
|
if (refreshTime > 0) {
|
|
1292
|
-
|
|
1838
|
+
this.scheduleRefresh(provider, refreshTime, credential);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
|
|
1843
|
+
* (2,147,483,647 ms ≈ 24.8 days). Without clamping, a far-future `expiresAt` overflows the
|
|
1844
|
+
* timer and fires almost immediately, causing a refresh storm. When clamped, the timer simply
|
|
1845
|
+
* re-schedules the remaining wait on fire instead of refreshing early.
|
|
1846
|
+
*/
|
|
1847
|
+
scheduleRefresh(provider, delayMs, credential) {
|
|
1848
|
+
const MAX_TIMEOUT = 2147483647;
|
|
1849
|
+
const clamped = Math.min(delayMs, MAX_TIMEOUT);
|
|
1850
|
+
const timer = setTimeout(() => {
|
|
1851
|
+
const remaining = delayMs - clamped;
|
|
1852
|
+
if (remaining > 0) {
|
|
1853
|
+
// We hit the clamp ceiling — reschedule the rest rather than refreshing prematurely.
|
|
1854
|
+
this.scheduleRefresh(provider, remaining, credential);
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
void (async () => {
|
|
1293
1858
|
try {
|
|
1294
1859
|
await this.refreshToken(provider);
|
|
1295
1860
|
}
|
|
1296
1861
|
catch (error) {
|
|
1297
1862
|
this.logger.error(`Auto token refresh failed for ${provider}`, error);
|
|
1298
1863
|
}
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
|
|
1864
|
+
})();
|
|
1865
|
+
}, clamped);
|
|
1866
|
+
this.tokenRefreshTimers.set(provider, timer);
|
|
1302
1867
|
}
|
|
1303
1868
|
clearTokenRefresh(provider) {
|
|
1304
1869
|
const timer = this.tokenRefreshTimers.get(provider);
|
|
@@ -1307,6 +1872,13 @@ class AuthManagerCore {
|
|
|
1307
1872
|
this.tokenRefreshTimers.delete(provider);
|
|
1308
1873
|
}
|
|
1309
1874
|
}
|
|
1875
|
+
/** Clears every active refresh timer (used on a global, untargeted sign-out). */
|
|
1876
|
+
clearAllTokenRefresh() {
|
|
1877
|
+
for (const timer of this.tokenRefreshTimers.values()) {
|
|
1878
|
+
clearTimeout(timer);
|
|
1879
|
+
}
|
|
1880
|
+
this.tokenRefreshTimers.clear();
|
|
1881
|
+
}
|
|
1310
1882
|
dispose() {
|
|
1311
1883
|
// Clear all timers
|
|
1312
1884
|
for (const timer of this.tokenRefreshTimers.values()) {
|
|
@@ -1327,6 +1899,31 @@ const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
|
|
|
1327
1899
|
web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
|
|
1328
1900
|
});
|
|
1329
1901
|
|
|
1902
|
+
/**
|
|
1903
|
+
* Normalize a provider constructor argument into a full {@link BaseProviderConfig}.
|
|
1904
|
+
*
|
|
1905
|
+
* The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
|
|
1906
|
+
* get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
|
|
1907
|
+
* tests and direct consumers pass the provider's own bare options object. This helper accepts
|
|
1908
|
+
* either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`, so it never
|
|
1909
|
+
* touches `window` and stays safe under SSR / Node test environments) plus the shared
|
|
1910
|
+
* {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
|
|
1911
|
+
*/
|
|
1912
|
+
function resolveProviderConfig(provider, input) {
|
|
1913
|
+
if (typeof input === 'object' &&
|
|
1914
|
+
input !== null &&
|
|
1915
|
+
'storage' in input &&
|
|
1916
|
+
'logger' in input &&
|
|
1917
|
+
'options' in input) {
|
|
1918
|
+
return input;
|
|
1919
|
+
}
|
|
1920
|
+
return {
|
|
1921
|
+
provider,
|
|
1922
|
+
options: (input !== null && input !== void 0 ? input : {}),
|
|
1923
|
+
storage: new WebStorage(exports.AuthPersistence.NONE),
|
|
1924
|
+
logger: defaultLogger,
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1330
1927
|
class BaseAuthProvider {
|
|
1331
1928
|
get name() {
|
|
1332
1929
|
return this.provider;
|
|
@@ -1341,6 +1938,19 @@ class BaseAuthProvider {
|
|
|
1341
1938
|
this.persistence = config.persistence || exports.AuthPersistence.LOCAL;
|
|
1342
1939
|
this.authStateEmitter = new EventEmitter();
|
|
1343
1940
|
}
|
|
1941
|
+
// Capability methods with concrete defaults: providers that support these operations override
|
|
1942
|
+
// them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
|
|
1943
|
+
// across every provider (see AuthProviderInterface, where they are optional). Marking them
|
|
1944
|
+
// abstract previously forced every subclass to re-implement them just to throw.
|
|
1945
|
+
async linkAccount(_options) {
|
|
1946
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking is not supported by provider ${this.provider}`, this.provider);
|
|
1947
|
+
}
|
|
1948
|
+
async unlinkAccount(_options) {
|
|
1949
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking is not supported by provider ${this.provider}`, this.provider);
|
|
1950
|
+
}
|
|
1951
|
+
async revokeAccess(_token) {
|
|
1952
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation is not supported by provider ${this.provider}`, this.provider);
|
|
1953
|
+
}
|
|
1344
1954
|
async getCurrentUser() {
|
|
1345
1955
|
if (!this.isInitialized) {
|
|
1346
1956
|
await this.initialize();
|
|
@@ -1418,7 +2028,19 @@ class BaseAuthProvider {
|
|
|
1418
2028
|
};
|
|
1419
2029
|
}
|
|
1420
2030
|
generateUniqueId() {
|
|
1421
|
-
|
|
2031
|
+
// Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
|
|
2032
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
2033
|
+
return crypto.randomUUID();
|
|
2034
|
+
}
|
|
2035
|
+
const bytes = new Uint8Array(16);
|
|
2036
|
+
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
|
|
2037
|
+
crypto.getRandomValues(bytes);
|
|
2038
|
+
}
|
|
2039
|
+
let hex = '';
|
|
2040
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2041
|
+
hex += bytes[i].toString(16).padStart(2, '0');
|
|
2042
|
+
}
|
|
2043
|
+
return `${Date.now()}-${hex}`;
|
|
1422
2044
|
}
|
|
1423
2045
|
isTokenExpired(expiresAt) {
|
|
1424
2046
|
if (!expiresAt)
|
|
@@ -1446,11 +2068,26 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1446
2068
|
// Generate state and nonce for security
|
|
1447
2069
|
const state = this.generateSecureRandomString();
|
|
1448
2070
|
const nonce = this.generateSecureRandomString();
|
|
1449
|
-
//
|
|
2071
|
+
// PKCE (RFC 7636) — default on; requires Web Crypto 'subtle' (HTTPS / localhost).
|
|
2072
|
+
let codeVerifier;
|
|
2073
|
+
let codeChallenge;
|
|
2074
|
+
if (config.pkceEnabled !== false) {
|
|
2075
|
+
if (typeof crypto !== 'undefined' && crypto.subtle) {
|
|
2076
|
+
codeVerifier = this.generateCodeVerifier();
|
|
2077
|
+
codeChallenge = await this.generateCodeChallenge(codeVerifier);
|
|
2078
|
+
}
|
|
2079
|
+
else {
|
|
2080
|
+
this.logger.warn(`PKCE skipped for ${this.provider}: Web Crypto 'subtle' is unavailable (insecure context). Serve over HTTPS to enable PKCE.`);
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
// Store state, nonce, and PKCE verifier for validation
|
|
1450
2084
|
await this.storage.set(`${this.provider}_oauth_state`, state);
|
|
1451
2085
|
await this.storage.set(`${this.provider}_oauth_nonce`, nonce);
|
|
2086
|
+
if (codeVerifier) {
|
|
2087
|
+
await this.storage.set(`${this.provider}_oauth_verifier`, codeVerifier);
|
|
2088
|
+
}
|
|
1452
2089
|
// Build authorization URL
|
|
1453
|
-
const authUrl = this.buildAuthorizationUrl(config, state, nonce, options);
|
|
2090
|
+
const authUrl = this.buildAuthorizationUrl(config, state, nonce, options, codeChallenge);
|
|
1454
2091
|
// Perform the OAuth flow (platform-specific implementation)
|
|
1455
2092
|
const authResponse = await this.openAuthorizationUrl(authUrl);
|
|
1456
2093
|
// Validate response
|
|
@@ -1459,7 +2096,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1459
2096
|
if (!authResponse.code) {
|
|
1460
2097
|
throw new AuthError(exports.AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
|
|
1461
2098
|
}
|
|
1462
|
-
const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config);
|
|
2099
|
+
const tokenResponse = await this.exchangeCodeForTokens(authResponse.code, config, codeVerifier);
|
|
2100
|
+
// Validate the ID token's nonce + expiry (replay protection). NOTE: the signature is
|
|
2101
|
+
// NOT verified client-side — always re-validate ID tokens on your backend.
|
|
2102
|
+
this.validateIdToken(tokenResponse.id_token, nonce);
|
|
1463
2103
|
// Parse user information
|
|
1464
2104
|
const userInfo = await this.parseUserFromTokenResponse(tokenResponse);
|
|
1465
2105
|
// Create AuthUser and AuthCredential
|
|
@@ -1478,31 +2118,47 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1478
2118
|
// Clean up temporary storage
|
|
1479
2119
|
await this.storage.remove(`${this.provider}_oauth_state`);
|
|
1480
2120
|
await this.storage.remove(`${this.provider}_oauth_nonce`);
|
|
2121
|
+
await this.storage.remove(`${this.provider}_oauth_verifier`);
|
|
1481
2122
|
}
|
|
1482
2123
|
}
|
|
1483
|
-
buildAuthorizationUrl(config, state, nonce, options) {
|
|
2124
|
+
buildAuthorizationUrl(config, state, nonce, options, codeChallenge) {
|
|
1484
2125
|
var _a, _b, _c, _d;
|
|
1485
|
-
const params = new URLSearchParams(
|
|
1486
|
-
|
|
1487
|
-
//
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
2126
|
+
const params = new URLSearchParams();
|
|
2127
|
+
// Developer-supplied params FIRST, so the security-critical params set below cannot be
|
|
2128
|
+
// overridden by additionalParams / customParameters.
|
|
2129
|
+
if (config.additionalParams) {
|
|
2130
|
+
for (const [key, value] of Object.entries(config.additionalParams)) {
|
|
2131
|
+
params.set(key, value);
|
|
2132
|
+
}
|
|
1491
2133
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
Object.entries(options.options.customParameters).forEach(([key, value]) => {
|
|
2134
|
+
if ((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.customParameters) {
|
|
2135
|
+
for (const [key, value] of Object.entries(options.options.customParameters)) {
|
|
1495
2136
|
params.set(key, value);
|
|
1496
|
-
}
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
// Scopes
|
|
2140
|
+
const scopes = ((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.scopes) || config.scopes || [];
|
|
2141
|
+
if (scopes.length > 0) {
|
|
2142
|
+
params.set('scope', scopes.join(' '));
|
|
1497
2143
|
}
|
|
1498
|
-
//
|
|
2144
|
+
// Login hint / prompt
|
|
1499
2145
|
if ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) {
|
|
1500
2146
|
params.set('login_hint', options.options.loginHint);
|
|
1501
2147
|
}
|
|
1502
|
-
// Add prompt if provided
|
|
1503
2148
|
if ((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) {
|
|
1504
2149
|
params.set('prompt', options.options.prompt);
|
|
1505
2150
|
}
|
|
2151
|
+
// Security-critical parameters — set LAST so custom params cannot override them.
|
|
2152
|
+
params.set('client_id', config.clientId);
|
|
2153
|
+
params.set('redirect_uri', config.redirectUri);
|
|
2154
|
+
params.set('response_type', config.responseType || 'code');
|
|
2155
|
+
params.set('state', state);
|
|
2156
|
+
params.set('nonce', nonce);
|
|
2157
|
+
if (codeChallenge) {
|
|
2158
|
+
params.set('code_challenge', codeChallenge);
|
|
2159
|
+
params.set('code_challenge_method', 'S256');
|
|
2160
|
+
}
|
|
2161
|
+
this.assertSecureEndpoint(config.authorizationEndpoint);
|
|
1506
2162
|
return `${config.authorizationEndpoint}?${params.toString()}`;
|
|
1507
2163
|
}
|
|
1508
2164
|
async validateOAuthResponse(response, expectedState, _expectedNonce) {
|
|
@@ -1514,16 +2170,21 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1514
2170
|
}
|
|
1515
2171
|
// Nonce validation is done after ID token is received
|
|
1516
2172
|
}
|
|
1517
|
-
async exchangeCodeForTokens(code, config) {
|
|
2173
|
+
async exchangeCodeForTokens(code, config, codeVerifier) {
|
|
1518
2174
|
const params = new URLSearchParams({
|
|
1519
2175
|
grant_type: config.grantType || 'authorization_code',
|
|
1520
2176
|
code,
|
|
1521
2177
|
redirect_uri: config.redirectUri,
|
|
1522
2178
|
client_id: config.clientId,
|
|
1523
2179
|
});
|
|
2180
|
+
if (codeVerifier) {
|
|
2181
|
+
params.set('code_verifier', codeVerifier);
|
|
2182
|
+
}
|
|
1524
2183
|
if (config.clientSecret) {
|
|
2184
|
+
this.warnClientSecretInBrowser();
|
|
1525
2185
|
params.set('client_secret', config.clientSecret);
|
|
1526
2186
|
}
|
|
2187
|
+
this.assertSecureEndpoint(config.tokenEndpoint);
|
|
1527
2188
|
try {
|
|
1528
2189
|
const response = await fetch(config.tokenEndpoint, {
|
|
1529
2190
|
method: 'POST',
|
|
@@ -1560,8 +2221,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1560
2221
|
client_id: config.clientId,
|
|
1561
2222
|
});
|
|
1562
2223
|
if (config.clientSecret) {
|
|
2224
|
+
this.warnClientSecretInBrowser();
|
|
1563
2225
|
params.set('client_secret', config.clientSecret);
|
|
1564
2226
|
}
|
|
2227
|
+
this.assertSecureEndpoint(config.tokenEndpoint);
|
|
1565
2228
|
const response = await fetch(config.tokenEndpoint, {
|
|
1566
2229
|
method: 'POST',
|
|
1567
2230
|
headers: {
|
|
@@ -1608,8 +2271,10 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1608
2271
|
client_id: config.clientId,
|
|
1609
2272
|
});
|
|
1610
2273
|
if (config.clientSecret) {
|
|
2274
|
+
this.warnClientSecretInBrowser();
|
|
1611
2275
|
params.set('client_secret', config.clientSecret);
|
|
1612
2276
|
}
|
|
2277
|
+
this.assertSecureEndpoint(config.revokeEndpoint);
|
|
1613
2278
|
await fetch(config.revokeEndpoint, {
|
|
1614
2279
|
method: 'POST',
|
|
1615
2280
|
headers: {
|
|
@@ -1696,6 +2361,80 @@ class OAuthProvider extends BaseAuthProvider {
|
|
|
1696
2361
|
}
|
|
1697
2362
|
return result;
|
|
1698
2363
|
}
|
|
2364
|
+
/** RFC 7636 PKCE code verifier: 64 chars from the unreserved set [A-Za-z0-9]. */
|
|
2365
|
+
generateCodeVerifier() {
|
|
2366
|
+
return this.generateSecureRandomString(64);
|
|
2367
|
+
}
|
|
2368
|
+
/** Derives the S256 PKCE code challenge: base64url(SHA-256(verifier)). */
|
|
2369
|
+
async generateCodeChallenge(verifier) {
|
|
2370
|
+
const data = new TextEncoder().encode(verifier);
|
|
2371
|
+
const digest = await crypto.subtle.digest('SHA-256', data);
|
|
2372
|
+
return this.base64UrlEncode(new Uint8Array(digest));
|
|
2373
|
+
}
|
|
2374
|
+
base64UrlEncode(bytes) {
|
|
2375
|
+
let binary = '';
|
|
2376
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2377
|
+
binary += String.fromCharCode(bytes[i]);
|
|
2378
|
+
}
|
|
2379
|
+
return btoa(binary)
|
|
2380
|
+
.replace(/\+/g, '-')
|
|
2381
|
+
.replace(/\//g, '_')
|
|
2382
|
+
.replace(/=+$/, '');
|
|
2383
|
+
}
|
|
2384
|
+
/** Decodes a JWT payload without verifying the signature. Returns null if malformed. */
|
|
2385
|
+
decodeJwtPayload(token) {
|
|
2386
|
+
try {
|
|
2387
|
+
const parts = token.split('.');
|
|
2388
|
+
if (parts.length < 2) {
|
|
2389
|
+
return null;
|
|
2390
|
+
}
|
|
2391
|
+
let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
2392
|
+
const pad = payload.length % 4;
|
|
2393
|
+
if (pad) {
|
|
2394
|
+
payload += '='.repeat(4 - pad);
|
|
2395
|
+
}
|
|
2396
|
+
return JSON.parse(atob(payload));
|
|
2397
|
+
}
|
|
2398
|
+
catch (_a) {
|
|
2399
|
+
return null;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Validates the ID token's nonce (replay protection) and expiry. The signature is NOT
|
|
2404
|
+
* verified client-side — always re-validate ID tokens on your backend before trusting them.
|
|
2405
|
+
*/
|
|
2406
|
+
validateIdToken(idToken, expectedNonce) {
|
|
2407
|
+
if (!idToken) {
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
const payload = this.decodeJwtPayload(idToken);
|
|
2411
|
+
if (!payload) {
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
if (payload.nonce !== undefined && payload.nonce !== expectedNonce) {
|
|
2415
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'OIDC nonce mismatch in ID token', this.provider);
|
|
2416
|
+
}
|
|
2417
|
+
if (typeof payload.exp === 'number' && payload.exp * 1000 < Date.now()) {
|
|
2418
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'ID token is expired', this.provider);
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
warnClientSecretInBrowser() {
|
|
2422
|
+
this.logger.warn(`${this.provider}: a client secret was supplied to a browser-facing provider. Secrets ` +
|
|
2423
|
+
`placed in client config ship in the JS bundle and are recoverable by end users. Use a ` +
|
|
2424
|
+
`backend token-exchange proxy (set tokenEndpoint to your server) instead.`);
|
|
2425
|
+
}
|
|
2426
|
+
assertSecureEndpoint(url) {
|
|
2427
|
+
try {
|
|
2428
|
+
const parsed = new URL(url);
|
|
2429
|
+
const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
|
|
2430
|
+
if (parsed.protocol !== 'https:' && !isLocalhost) {
|
|
2431
|
+
this.logger.warn(`${this.provider}: endpoint ${url} is not HTTPS — credentials/tokens may be sent in cleartext.`);
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
catch (_a) {
|
|
2435
|
+
// Malformed URL: let the subsequent fetch surface the error.
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
1699
2438
|
}
|
|
1700
2439
|
|
|
1701
2440
|
class GoogleAuthProviderWeb extends OAuthProvider {
|
|
@@ -2054,8 +2793,8 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2054
2793
|
const response = await window.AppleID.auth.signIn(signInConfig);
|
|
2055
2794
|
// Validate response
|
|
2056
2795
|
await this.validateAppleResponse(response, state, nonce);
|
|
2057
|
-
// Parse user information from response
|
|
2058
|
-
const user = this.createAppleAuthUser(response);
|
|
2796
|
+
// Parse user information from response (validates ID token nonce + expiry first)
|
|
2797
|
+
const user = this.createAppleAuthUser(response, nonce);
|
|
2059
2798
|
const credential = this.createAppleCredential(response);
|
|
2060
2799
|
// Save user and credential
|
|
2061
2800
|
await this.setCurrentUser(user);
|
|
@@ -2089,6 +2828,12 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2089
2828
|
throw AuthError.fromError(error, this.provider);
|
|
2090
2829
|
}
|
|
2091
2830
|
}
|
|
2831
|
+
async refreshToken(_options) {
|
|
2832
|
+
// Apple's JS (web) Sign In flow never issues a refresh token, so the inherited
|
|
2833
|
+
// OAuthProvider.refreshToken() would fail with a confusing "No refresh token available".
|
|
2834
|
+
// Surface an explicit, accurate error instead: callers must re-authenticate.
|
|
2835
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Apple web sign-in does not issue refresh tokens; re-authenticate instead.', this.provider);
|
|
2836
|
+
}
|
|
2092
2837
|
async isSupported() {
|
|
2093
2838
|
// Check if we're in a browser environment
|
|
2094
2839
|
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
@@ -2169,19 +2914,29 @@ class AppleAuthProviderWeb extends OAuthProvider {
|
|
|
2169
2914
|
// ID token validation with nonce would be done here
|
|
2170
2915
|
// For production, you should validate the ID token on your backend
|
|
2171
2916
|
}
|
|
2172
|
-
createAppleAuthUser(response) {
|
|
2917
|
+
createAppleAuthUser(response, expectedNonce) {
|
|
2173
2918
|
var _a, _b, _c;
|
|
2174
2919
|
const user = response.user || {};
|
|
2175
2920
|
const idToken = (_a = response.authorization) === null || _a === void 0 ? void 0 : _a.id_token;
|
|
2176
|
-
//
|
|
2921
|
+
// Validate the ID token's nonce (replay protection) and expiry BEFORE trusting any
|
|
2922
|
+
// claims. The signature is NOT verified client-side — always re-validate on your backend.
|
|
2923
|
+
// Defensive: only enforce the nonce when both an expected nonce and a token nonce exist.
|
|
2177
2924
|
let claims = {};
|
|
2178
2925
|
if (idToken) {
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
claims =
|
|
2926
|
+
const payload = this.decodeJwtPayload(idToken);
|
|
2927
|
+
if (payload) {
|
|
2928
|
+
claims = payload;
|
|
2929
|
+
if (expectedNonce &&
|
|
2930
|
+
claims.nonce !== undefined &&
|
|
2931
|
+
claims.nonce !== expectedNonce) {
|
|
2932
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'Apple ID token nonce does not match the expected value', this.provider);
|
|
2933
|
+
}
|
|
2934
|
+
if (typeof claims.exp === 'number' && claims.exp * 1000 < Date.now()) {
|
|
2935
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Apple ID token is expired', this.provider);
|
|
2936
|
+
}
|
|
2182
2937
|
}
|
|
2183
|
-
|
|
2184
|
-
this.logger.error('Failed to
|
|
2938
|
+
else {
|
|
2939
|
+
this.logger.error('Failed to decode Apple ID token payload');
|
|
2185
2940
|
}
|
|
2186
2941
|
}
|
|
2187
2942
|
return {
|
|
@@ -2254,11 +3009,16 @@ var appleProvider = /*#__PURE__*/Object.freeze({
|
|
|
2254
3009
|
class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
2255
3010
|
constructor() {
|
|
2256
3011
|
super(...arguments);
|
|
3012
|
+
this.msalConfig = {};
|
|
2257
3013
|
this.clientId = '';
|
|
2258
3014
|
this.authority = '';
|
|
2259
3015
|
this.redirectUri = '';
|
|
2260
3016
|
this.scopes = [];
|
|
2261
3017
|
}
|
|
3018
|
+
/** Reads the host-page MSAL SDK, casting the `window` boundary exactly once. */
|
|
3019
|
+
getMsal() {
|
|
3020
|
+
return window.msal;
|
|
3021
|
+
}
|
|
2262
3022
|
async initialize() {
|
|
2263
3023
|
const options = this.options;
|
|
2264
3024
|
if (!options.clientId) {
|
|
@@ -2270,7 +3030,7 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2270
3030
|
this.redirectUri = options.redirectUri || window.location.origin;
|
|
2271
3031
|
this.scopes = options.scopes || ['openid', 'profile', 'email'];
|
|
2272
3032
|
// Check if MSAL is available
|
|
2273
|
-
const msal =
|
|
3033
|
+
const msal = this.getMsal();
|
|
2274
3034
|
if (!msal) {
|
|
2275
3035
|
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Microsoft Authentication Library (MSAL) is not loaded. Please include the MSAL script in your HTML.', this.provider);
|
|
2276
3036
|
}
|
|
@@ -2317,9 +3077,22 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2317
3077
|
}
|
|
2318
3078
|
}
|
|
2319
3079
|
async signIn(options) {
|
|
3080
|
+
var _a, _b, _c, _d;
|
|
2320
3081
|
this.validateInitialized();
|
|
2321
3082
|
try {
|
|
2322
|
-
|
|
3083
|
+
// Build the MSAL login request EXPLICITLY from the standard options shape — spreading
|
|
3084
|
+
// raw `options` here would leak junk (provider, credentials, …) into MSAL and ignore
|
|
3085
|
+
// per-sign-in scopes. Honour per-call scopes/loginHint/prompt, fall back to configured
|
|
3086
|
+
// scopes, and omit undefined keys.
|
|
3087
|
+
const loginRequest = {
|
|
3088
|
+
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,
|
|
3089
|
+
};
|
|
3090
|
+
if (((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) !== undefined) {
|
|
3091
|
+
loginRequest.loginHint = options.options.loginHint;
|
|
3092
|
+
}
|
|
3093
|
+
if (((_d = options === null || options === void 0 ? void 0 : options.options) === null || _d === void 0 ? void 0 : _d.prompt) !== undefined) {
|
|
3094
|
+
loginRequest.prompt = options.options.prompt;
|
|
3095
|
+
}
|
|
2323
3096
|
// Try popup first, fallback to redirect
|
|
2324
3097
|
let response;
|
|
2325
3098
|
try {
|
|
@@ -2338,10 +3111,11 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2338
3111
|
}
|
|
2339
3112
|
catch (error) {
|
|
2340
3113
|
this.logger.error('Microsoft sign in failed', error);
|
|
2341
|
-
|
|
3114
|
+
const err = error;
|
|
3115
|
+
if (err.errorCode === 'user_cancelled') {
|
|
2342
3116
|
throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
|
|
2343
3117
|
}
|
|
2344
|
-
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${
|
|
3118
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Microsoft sign in failed: ${err.message}`, this.provider);
|
|
2345
3119
|
}
|
|
2346
3120
|
}
|
|
2347
3121
|
async signOut(options) {
|
|
@@ -2387,15 +3161,16 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2387
3161
|
}
|
|
2388
3162
|
catch (error) {
|
|
2389
3163
|
this.logger.error('Token refresh failed', error);
|
|
2390
|
-
|
|
3164
|
+
const err = error;
|
|
3165
|
+
if (err.errorCode === 'interaction_required') {
|
|
2391
3166
|
// Need user interaction, trigger sign in
|
|
2392
3167
|
return await this.signIn();
|
|
2393
3168
|
}
|
|
2394
|
-
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${
|
|
3169
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, `Token refresh failed: ${err.message}`, this.provider);
|
|
2395
3170
|
}
|
|
2396
3171
|
}
|
|
2397
3172
|
async isSupported() {
|
|
2398
|
-
return typeof window !== 'undefined' && !!
|
|
3173
|
+
return typeof window !== 'undefined' && !!this.getMsal();
|
|
2399
3174
|
}
|
|
2400
3175
|
async linkAccount() {
|
|
2401
3176
|
// Microsoft doesn't support account linking in the same way
|
|
@@ -2425,32 +3200,37 @@ class MicrosoftAuthProviderWeb extends BaseAuthProvider {
|
|
|
2425
3200
|
scope: response.scopes.join(' '),
|
|
2426
3201
|
};
|
|
2427
3202
|
await this.saveCredential(credential);
|
|
2428
|
-
return this.createAuthResult(user, credential, ((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser)
|
|
3203
|
+
return this.createAuthResult(user, credential, Boolean((_a = response.account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.newUser));
|
|
2429
3204
|
}
|
|
2430
3205
|
createUserFromMSALAccount(account) {
|
|
2431
3206
|
const idTokenClaims = account.idTokenClaims || {};
|
|
3207
|
+
const claim = (key) => {
|
|
3208
|
+
const value = idTokenClaims[key];
|
|
3209
|
+
return typeof value === 'string' ? value : undefined;
|
|
3210
|
+
};
|
|
3211
|
+
const iat = idTokenClaims.iat;
|
|
2432
3212
|
return {
|
|
2433
|
-
uid: account.localAccountId || account.homeAccountId,
|
|
2434
|
-
email:
|
|
3213
|
+
uid: account.localAccountId || account.homeAccountId || '',
|
|
3214
|
+
email: claim('email') || account.username || null,
|
|
2435
3215
|
emailVerified: !!idTokenClaims.email_verified,
|
|
2436
|
-
displayName: account.name ||
|
|
2437
|
-
photoURL:
|
|
2438
|
-
phoneNumber:
|
|
3216
|
+
displayName: account.name || claim('name') || null,
|
|
3217
|
+
photoURL: claim('picture') || null,
|
|
3218
|
+
phoneNumber: claim('phone_number') || null,
|
|
2439
3219
|
isAnonymous: false,
|
|
2440
|
-
tenantId: account.tenantId,
|
|
3220
|
+
tenantId: account.tenantId || null,
|
|
2441
3221
|
providerData: [
|
|
2442
3222
|
{
|
|
2443
3223
|
providerId: this.provider,
|
|
2444
|
-
uid: account.localAccountId,
|
|
2445
|
-
displayName: account.name,
|
|
2446
|
-
email: account.username,
|
|
3224
|
+
uid: account.localAccountId || '',
|
|
3225
|
+
displayName: account.name || null,
|
|
3226
|
+
email: account.username || null,
|
|
2447
3227
|
phoneNumber: null,
|
|
2448
|
-
photoURL:
|
|
3228
|
+
photoURL: claim('picture') || null,
|
|
2449
3229
|
},
|
|
2450
3230
|
],
|
|
2451
3231
|
metadata: {
|
|
2452
|
-
creationTime:
|
|
2453
|
-
? new Date(
|
|
3232
|
+
creationTime: typeof iat === 'number'
|
|
3233
|
+
? new Date(iat * 1000).toISOString()
|
|
2454
3234
|
: undefined,
|
|
2455
3235
|
lastSignInTime: new Date().toISOString(),
|
|
2456
3236
|
},
|
|
@@ -2548,7 +3328,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
|
|
|
2548
3328
|
checkLoginStatus() {
|
|
2549
3329
|
return new Promise((resolve) => {
|
|
2550
3330
|
window.FB.getLoginStatus(async (response) => {
|
|
2551
|
-
if (response.status === 'connected') {
|
|
3331
|
+
if (response.status === 'connected' && response.authResponse) {
|
|
2552
3332
|
await this.handleAuthResponse(response.authResponse);
|
|
2553
3333
|
}
|
|
2554
3334
|
resolve();
|
|
@@ -2603,7 +3383,7 @@ class FacebookAuthProviderWeb extends BaseAuthProvider {
|
|
|
2603
3383
|
// Facebook access tokens are short-lived and need to be refreshed via re-authentication
|
|
2604
3384
|
return new Promise((resolve, reject) => {
|
|
2605
3385
|
window.FB.getLoginStatus(async (response) => {
|
|
2606
|
-
if (response.status === 'connected') {
|
|
3386
|
+
if (response.status === 'connected' && response.authResponse) {
|
|
2607
3387
|
try {
|
|
2608
3388
|
const result = await this.handleAuthResponse(response.authResponse, true);
|
|
2609
3389
|
resolve(result);
|
|
@@ -2723,6 +3503,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2723
3503
|
this.scopes = [];
|
|
2724
3504
|
this.authWindow = null;
|
|
2725
3505
|
this.authPromise = null;
|
|
3506
|
+
/** Bound 'message' handler reference so it can be removed in dispose(). */
|
|
3507
|
+
this.boundAuthMessageHandler = null;
|
|
3508
|
+
/** Active popup-closed polling interval, tracked so it is cleared on every exit path. */
|
|
3509
|
+
this.popupCheckInterval = null;
|
|
3510
|
+
/** CSRF state from the most recent sign-in, forwarded to the proxy for re-verification. */
|
|
3511
|
+
this.lastState = null;
|
|
2726
3512
|
}
|
|
2727
3513
|
async initialize() {
|
|
2728
3514
|
const options = this.options;
|
|
@@ -2733,8 +3519,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2733
3519
|
this.redirectUri =
|
|
2734
3520
|
options.redirectUri || window.location.origin + '/auth/github/callback';
|
|
2735
3521
|
this.scopes = options.scopes || ['read:user', 'user:email'];
|
|
2736
|
-
|
|
2737
|
-
|
|
3522
|
+
this.tokenExchangeProxy =
|
|
3523
|
+
options.tokenExchangeProxy || options.tokenEndpoint;
|
|
3524
|
+
// Set up message listener for OAuth callback. Keep the bound reference so the exact
|
|
3525
|
+
// same function can be removed in dispose() (a fresh `.bind()` would not match).
|
|
3526
|
+
this.boundAuthMessageHandler = this.handleAuthMessage.bind(this);
|
|
3527
|
+
window.addEventListener('message', this.boundAuthMessageHandler);
|
|
2738
3528
|
// Check for stored session
|
|
2739
3529
|
await this.loadCurrentUser();
|
|
2740
3530
|
this.isInitialized = true;
|
|
@@ -2745,6 +3535,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2745
3535
|
return new Promise((resolve, reject) => {
|
|
2746
3536
|
this.authPromise = { resolve, reject };
|
|
2747
3537
|
const state = this.generateState();
|
|
3538
|
+
this.lastState = state;
|
|
2748
3539
|
const authUrl = this.buildAuthUrl(state);
|
|
2749
3540
|
// Open GitHub OAuth in a popup window
|
|
2750
3541
|
const width = 600;
|
|
@@ -2757,11 +3548,13 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2757
3548
|
reject(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, 'Popup window was blocked. Please allow popups for this site.', this.provider));
|
|
2758
3549
|
return;
|
|
2759
3550
|
}
|
|
2760
|
-
// Check if popup is closed
|
|
2761
|
-
|
|
3551
|
+
// Check if popup is closed. Track the interval so the success path
|
|
3552
|
+
// (handleAuthMessage) and dispose() can also clear it — otherwise it leaks.
|
|
3553
|
+
this.clearPopupCheckInterval();
|
|
3554
|
+
this.popupCheckInterval = setInterval(() => {
|
|
2762
3555
|
var _a;
|
|
2763
3556
|
if ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.closed) {
|
|
2764
|
-
|
|
3557
|
+
this.clearPopupCheckInterval();
|
|
2765
3558
|
if (this.authPromise) {
|
|
2766
3559
|
this.authPromise = null;
|
|
2767
3560
|
reject(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User closed the authentication window', this.provider));
|
|
@@ -2770,6 +3563,12 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2770
3563
|
}, 1000);
|
|
2771
3564
|
});
|
|
2772
3565
|
}
|
|
3566
|
+
clearPopupCheckInterval() {
|
|
3567
|
+
if (this.popupCheckInterval !== null) {
|
|
3568
|
+
clearInterval(this.popupCheckInterval);
|
|
3569
|
+
this.popupCheckInterval = null;
|
|
3570
|
+
}
|
|
3571
|
+
}
|
|
2773
3572
|
async signOut(options) {
|
|
2774
3573
|
this.validateInitialized();
|
|
2775
3574
|
try {
|
|
@@ -2848,6 +3647,8 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2848
3647
|
if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) !== 'github-auth-callback') {
|
|
2849
3648
|
return;
|
|
2850
3649
|
}
|
|
3650
|
+
// The callback arrived — stop polling for a closed popup (success path cleanup).
|
|
3651
|
+
this.clearPopupCheckInterval();
|
|
2851
3652
|
if (this.authWindow) {
|
|
2852
3653
|
this.authWindow.close();
|
|
2853
3654
|
this.authWindow = null;
|
|
@@ -2890,9 +3691,44 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2890
3691
|
reject(AuthError.fromError(error, this.provider));
|
|
2891
3692
|
}
|
|
2892
3693
|
}
|
|
2893
|
-
async exchangeCodeForToken(
|
|
2894
|
-
//
|
|
2895
|
-
|
|
3694
|
+
async exchangeCodeForToken(code) {
|
|
3695
|
+
// GitHub does NOT permit browser-side code→token exchange (it needs the client secret
|
|
3696
|
+
// and blocks CORS), so the exchange must run on a developer-supplied backend proxy.
|
|
3697
|
+
if (!this.tokenExchangeProxy) {
|
|
3698
|
+
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIG, 'GitHub sign-in requires a backend token-exchange proxy. Set `tokenExchangeProxy` ' +
|
|
3699
|
+
'(or `tokenEndpoint`) in the GitHub provider config to a server endpoint that ' +
|
|
3700
|
+
'exchanges the authorization code for an access token. See the GitHub provider ' +
|
|
3701
|
+
'setup guide / docs/providers for an example.', this.provider);
|
|
3702
|
+
}
|
|
3703
|
+
let response;
|
|
3704
|
+
try {
|
|
3705
|
+
response = await fetch(this.tokenExchangeProxy, {
|
|
3706
|
+
method: 'POST',
|
|
3707
|
+
headers: {
|
|
3708
|
+
'Content-Type': 'application/json',
|
|
3709
|
+
Accept: 'application/json',
|
|
3710
|
+
},
|
|
3711
|
+
body: JSON.stringify({
|
|
3712
|
+
code,
|
|
3713
|
+
redirectUri: this.redirectUri,
|
|
3714
|
+
state: this.lastState,
|
|
3715
|
+
}),
|
|
3716
|
+
});
|
|
3717
|
+
}
|
|
3718
|
+
catch (error) {
|
|
3719
|
+
throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach the GitHub token-exchange proxy', this.provider, error);
|
|
3720
|
+
}
|
|
3721
|
+
const data = (await response
|
|
3722
|
+
.json()
|
|
3723
|
+
.catch(() => null));
|
|
3724
|
+
if (!response.ok || !data || !data.access_token) {
|
|
3725
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `GitHub token exchange failed${(data === null || data === void 0 ? void 0 : data.error_description)
|
|
3726
|
+
? `: ${data.error_description}`
|
|
3727
|
+
: (data === null || data === void 0 ? void 0 : data.error)
|
|
3728
|
+
? `: ${data.error}`
|
|
3729
|
+
: ''}`, this.provider);
|
|
3730
|
+
}
|
|
3731
|
+
return Object.assign(Object.assign({}, data), { access_token: data.access_token });
|
|
2896
3732
|
}
|
|
2897
3733
|
async fetchUserData(accessToken) {
|
|
2898
3734
|
const response = await fetch('https://api.github.com/user', {
|
|
@@ -2919,6 +3755,7 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2919
3755
|
return await response.json();
|
|
2920
3756
|
}
|
|
2921
3757
|
async createUserFromGitHubData(userData, accessToken) {
|
|
3758
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2922
3759
|
// Get primary email
|
|
2923
3760
|
const emails = await this.fetchUserEmails(accessToken);
|
|
2924
3761
|
const primaryEmail = emails.find((e) => e.primary) || emails[0];
|
|
@@ -2949,15 +3786,35 @@ class GitHubAuthProviderWeb extends BaseAuthProvider {
|
|
|
2949
3786
|
},
|
|
2950
3787
|
customClaims: {
|
|
2951
3788
|
login: userData.login,
|
|
2952
|
-
company: userData.company,
|
|
2953
|
-
location: userData.location,
|
|
2954
|
-
bio: userData.bio,
|
|
2955
|
-
public_repos: userData.public_repos,
|
|
2956
|
-
followers: userData.followers,
|
|
2957
|
-
following: userData.following,
|
|
3789
|
+
company: (_a = userData.company) !== null && _a !== void 0 ? _a : null,
|
|
3790
|
+
location: (_b = userData.location) !== null && _b !== void 0 ? _b : null,
|
|
3791
|
+
bio: (_c = userData.bio) !== null && _c !== void 0 ? _c : null,
|
|
3792
|
+
public_repos: (_d = userData.public_repos) !== null && _d !== void 0 ? _d : null,
|
|
3793
|
+
followers: (_e = userData.followers) !== null && _e !== void 0 ? _e : null,
|
|
3794
|
+
following: (_f = userData.following) !== null && _f !== void 0 ? _f : null,
|
|
2958
3795
|
},
|
|
2959
3796
|
};
|
|
2960
3797
|
}
|
|
3798
|
+
dispose() {
|
|
3799
|
+
// Remove the global 'message' listener added in initialize() so it doesn't leak across
|
|
3800
|
+
// repeated init/dispose cycles, and stop any active popup-polling interval.
|
|
3801
|
+
if (this.boundAuthMessageHandler) {
|
|
3802
|
+
window.removeEventListener('message', this.boundAuthMessageHandler);
|
|
3803
|
+
this.boundAuthMessageHandler = null;
|
|
3804
|
+
}
|
|
3805
|
+
this.clearPopupCheckInterval();
|
|
3806
|
+
if (this.authWindow) {
|
|
3807
|
+
try {
|
|
3808
|
+
this.authWindow.close();
|
|
3809
|
+
}
|
|
3810
|
+
catch (_a) {
|
|
3811
|
+
// window already closed / cross-origin — safe to ignore
|
|
3812
|
+
}
|
|
3813
|
+
this.authWindow = null;
|
|
3814
|
+
}
|
|
3815
|
+
this.authPromise = null;
|
|
3816
|
+
super.dispose();
|
|
3817
|
+
}
|
|
2961
3818
|
}
|
|
2962
3819
|
|
|
2963
3820
|
var githubProvider = /*#__PURE__*/Object.freeze({
|
|
@@ -2970,6 +3827,11 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
2970
3827
|
super(...arguments);
|
|
2971
3828
|
this.unsubscribeAuth = null;
|
|
2972
3829
|
}
|
|
3830
|
+
/** Reads the host-page Firebase SDK, casting the `window` boundary exactly once. */
|
|
3831
|
+
getFirebase() {
|
|
3832
|
+
return window
|
|
3833
|
+
.firebase;
|
|
3834
|
+
}
|
|
2973
3835
|
async initialize() {
|
|
2974
3836
|
const options = this.options;
|
|
2975
3837
|
if (!options.apiKey || !options.authDomain || !options.projectId) {
|
|
@@ -2977,7 +3839,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
2977
3839
|
}
|
|
2978
3840
|
try {
|
|
2979
3841
|
// Check if Firebase is available
|
|
2980
|
-
const firebase =
|
|
3842
|
+
const firebase = this.getFirebase();
|
|
2981
3843
|
if (!firebase) {
|
|
2982
3844
|
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded. Please include the Firebase scripts in your HTML.', this.provider);
|
|
2983
3845
|
}
|
|
@@ -3025,73 +3887,88 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3025
3887
|
}
|
|
3026
3888
|
}
|
|
3027
3889
|
getPersistenceMode() {
|
|
3028
|
-
const firebase =
|
|
3890
|
+
const firebase = this.getFirebase();
|
|
3891
|
+
const persistence = firebase === null || firebase === void 0 ? void 0 : firebase.auth.Auth.Persistence;
|
|
3029
3892
|
switch (this.persistence) {
|
|
3030
3893
|
case 'session':
|
|
3031
|
-
return
|
|
3894
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.SESSION;
|
|
3032
3895
|
case 'none':
|
|
3033
|
-
return
|
|
3896
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.NONE;
|
|
3034
3897
|
default:
|
|
3035
|
-
return
|
|
3898
|
+
return persistence === null || persistence === void 0 ? void 0 : persistence.LOCAL;
|
|
3036
3899
|
}
|
|
3037
3900
|
}
|
|
3038
3901
|
async signIn(options) {
|
|
3902
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
|
3039
3903
|
this.validateInitialized();
|
|
3040
|
-
|
|
3904
|
+
// The manager spreads credentials to the top level AND nests them under `credentials`,
|
|
3905
|
+
// and spreads `options.*` (scopes, prompt, etc.) to the top level too. Derive the
|
|
3906
|
+
// Firebase sub-method from the STANDARD shape instead of an undocumented `options.method`.
|
|
3907
|
+
const raw = options || {};
|
|
3908
|
+
const nestedOptions = raw.options || {};
|
|
3909
|
+
const credentials = raw.credentials || {};
|
|
3910
|
+
// email/password may arrive nested under `credentials` or spread to the top level.
|
|
3911
|
+
const email = ((_a = credentials.email) !== null && _a !== void 0 ? _a : raw.email);
|
|
3912
|
+
const password = ((_b = credentials.password) !== null && _b !== void 0 ? _b : raw.password);
|
|
3913
|
+
const scopes = ((_c = nestedOptions.scopes) !== null && _c !== void 0 ? _c : raw.scopes);
|
|
3914
|
+
const firebaseOptions = this.options;
|
|
3915
|
+
const method = ((_e = (_d = nestedOptions.method) !== null && _d !== void 0 ? _d : raw.method) !== null && _e !== void 0 ? _e : (email && password
|
|
3916
|
+
? 'email'
|
|
3917
|
+
: firebaseOptions.defaultMethod || 'google'));
|
|
3918
|
+
const signInOptions = { method, email, password, scopes };
|
|
3919
|
+
const firebase = this.getFirebase();
|
|
3920
|
+
if (!firebase) {
|
|
3921
|
+
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
|
|
3922
|
+
}
|
|
3923
|
+
const applyScopes = (provider) => {
|
|
3924
|
+
if (signInOptions.scopes) {
|
|
3925
|
+
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3926
|
+
}
|
|
3927
|
+
};
|
|
3041
3928
|
try {
|
|
3042
3929
|
let firebaseUser;
|
|
3043
3930
|
let credential;
|
|
3044
3931
|
let additionalUserInfo;
|
|
3045
3932
|
// Determine sign-in method
|
|
3046
3933
|
if (signInOptions.method === 'google') {
|
|
3047
|
-
const provider = new
|
|
3048
|
-
|
|
3049
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3050
|
-
}
|
|
3934
|
+
const provider = new firebase.auth.GoogleAuthProvider();
|
|
3935
|
+
applyScopes(provider);
|
|
3051
3936
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3052
3937
|
firebaseUser = result.user;
|
|
3053
3938
|
credential = result.credential;
|
|
3054
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3939
|
+
additionalUserInfo = (_f = result.additionalUserInfo) !== null && _f !== void 0 ? _f : {};
|
|
3055
3940
|
}
|
|
3056
3941
|
else if (signInOptions.method === 'facebook') {
|
|
3057
|
-
const provider = new
|
|
3058
|
-
|
|
3059
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3060
|
-
}
|
|
3942
|
+
const provider = new firebase.auth.FacebookAuthProvider();
|
|
3943
|
+
applyScopes(provider);
|
|
3061
3944
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3062
3945
|
firebaseUser = result.user;
|
|
3063
3946
|
credential = result.credential;
|
|
3064
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3947
|
+
additionalUserInfo = (_g = result.additionalUserInfo) !== null && _g !== void 0 ? _g : {};
|
|
3065
3948
|
}
|
|
3066
3949
|
else if (signInOptions.method === 'github') {
|
|
3067
|
-
const provider = new
|
|
3068
|
-
|
|
3069
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3070
|
-
}
|
|
3950
|
+
const provider = new firebase.auth.GithubAuthProvider();
|
|
3951
|
+
applyScopes(provider);
|
|
3071
3952
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3072
3953
|
firebaseUser = result.user;
|
|
3073
3954
|
credential = result.credential;
|
|
3074
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3955
|
+
additionalUserInfo = (_h = result.additionalUserInfo) !== null && _h !== void 0 ? _h : {};
|
|
3075
3956
|
}
|
|
3076
3957
|
else if (signInOptions.method === 'microsoft') {
|
|
3077
|
-
const provider = new
|
|
3078
|
-
|
|
3079
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3080
|
-
}
|
|
3958
|
+
const provider = new firebase.auth.OAuthProvider('microsoft.com');
|
|
3959
|
+
applyScopes(provider);
|
|
3081
3960
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3082
3961
|
firebaseUser = result.user;
|
|
3083
3962
|
credential = result.credential;
|
|
3084
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3963
|
+
additionalUserInfo = (_j = result.additionalUserInfo) !== null && _j !== void 0 ? _j : {};
|
|
3085
3964
|
}
|
|
3086
3965
|
else if (signInOptions.method === 'apple') {
|
|
3087
|
-
const provider = new
|
|
3088
|
-
|
|
3089
|
-
signInOptions.scopes.forEach((scope) => provider.addScope(scope));
|
|
3090
|
-
}
|
|
3966
|
+
const provider = new firebase.auth.OAuthProvider('apple.com');
|
|
3967
|
+
applyScopes(provider);
|
|
3091
3968
|
const result = await this.firebaseAuth.signInWithPopup(provider);
|
|
3092
3969
|
firebaseUser = result.user;
|
|
3093
3970
|
credential = result.credential;
|
|
3094
|
-
additionalUserInfo = result.additionalUserInfo;
|
|
3971
|
+
additionalUserInfo = (_k = result.additionalUserInfo) !== null && _k !== void 0 ? _k : {};
|
|
3095
3972
|
}
|
|
3096
3973
|
else if (signInOptions.method === 'email' &&
|
|
3097
3974
|
signInOptions.email &&
|
|
@@ -3123,11 +4000,12 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3123
4000
|
}
|
|
3124
4001
|
catch (error) {
|
|
3125
4002
|
this.logger.error('Firebase sign in failed', error);
|
|
3126
|
-
|
|
3127
|
-
|
|
4003
|
+
const err = error;
|
|
4004
|
+
if (err.code === 'auth/popup-closed-by-user' ||
|
|
4005
|
+
err.code === 'auth/cancelled-popup-request') {
|
|
3128
4006
|
throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'User cancelled the sign in', this.provider);
|
|
3129
4007
|
}
|
|
3130
|
-
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${
|
|
4008
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Firebase sign in failed: ${err.message}`, this.provider);
|
|
3131
4009
|
}
|
|
3132
4010
|
}
|
|
3133
4011
|
async signOut(options) {
|
|
@@ -3171,24 +4049,33 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3171
4049
|
}
|
|
3172
4050
|
}
|
|
3173
4051
|
async isSupported() {
|
|
3174
|
-
return typeof window !== 'undefined' && !!
|
|
4052
|
+
return typeof window !== 'undefined' && !!this.getFirebase();
|
|
3175
4053
|
}
|
|
3176
4054
|
async linkAccount(options) {
|
|
4055
|
+
var _a, _b, _c, _d;
|
|
3177
4056
|
this.validateInitialized();
|
|
3178
4057
|
const currentUser = this.firebaseAuth.currentUser;
|
|
3179
4058
|
if (!currentUser) {
|
|
3180
4059
|
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session to link account to', this.provider);
|
|
3181
4060
|
}
|
|
4061
|
+
const firebase = this.getFirebase();
|
|
4062
|
+
if (!firebase) {
|
|
4063
|
+
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Firebase SDK is not loaded.', this.provider);
|
|
4064
|
+
}
|
|
4065
|
+
// `method`/`email`/`password` may arrive nested under credentials or in provider options.
|
|
4066
|
+
const raw = options;
|
|
4067
|
+
const creds = (_a = raw.credentials) !== null && _a !== void 0 ? _a : {};
|
|
4068
|
+
const method = ((_b = raw.method) !== null && _b !== void 0 ? _b : creds.method);
|
|
4069
|
+
const linkEmail = ((_c = creds.email) !== null && _c !== void 0 ? _c : raw.email);
|
|
4070
|
+
const linkPassword = ((_d = creds.password) !== null && _d !== void 0 ? _d : raw.password);
|
|
3182
4071
|
try {
|
|
3183
4072
|
let result;
|
|
3184
|
-
if (
|
|
3185
|
-
const provider = new
|
|
4073
|
+
if (method === 'google') {
|
|
4074
|
+
const provider = new firebase.auth.GoogleAuthProvider();
|
|
3186
4075
|
result = await currentUser.linkWithPopup(provider);
|
|
3187
4076
|
}
|
|
3188
|
-
else if (
|
|
3189
|
-
|
|
3190
|
-
options.password) {
|
|
3191
|
-
const credential = window.firebase.auth.EmailAuthProvider.credential(options.email, options.password);
|
|
4077
|
+
else if (method === 'email' && linkEmail && linkPassword) {
|
|
4078
|
+
const credential = firebase.auth.EmailAuthProvider.credential(linkEmail, linkPassword);
|
|
3192
4079
|
result = await currentUser.linkWithCredential(credential);
|
|
3193
4080
|
}
|
|
3194
4081
|
else {
|
|
@@ -3199,6 +4086,8 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3199
4086
|
return this.createAuthResult(user, authCredential, false, 'link');
|
|
3200
4087
|
}
|
|
3201
4088
|
catch (error) {
|
|
4089
|
+
if (error instanceof AuthError)
|
|
4090
|
+
throw error;
|
|
3202
4091
|
throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to link account: ${error.message}`, this.provider);
|
|
3203
4092
|
}
|
|
3204
4093
|
}
|
|
@@ -3209,7 +4098,7 @@ class FirebaseAuthProviderWeb extends BaseAuthProvider {
|
|
|
3209
4098
|
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No active session', this.provider);
|
|
3210
4099
|
}
|
|
3211
4100
|
try {
|
|
3212
|
-
await currentUser.unlink(options.
|
|
4101
|
+
await currentUser.unlink(options.provider);
|
|
3213
4102
|
}
|
|
3214
4103
|
catch (error) {
|
|
3215
4104
|
throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, `Failed to unlink account: ${error.message}`, this.provider);
|
|
@@ -3273,26 +4162,137 @@ var firebaseProvider = /*#__PURE__*/Object.freeze({
|
|
|
3273
4162
|
FirebaseAuthProviderWeb: FirebaseAuthProviderWeb
|
|
3274
4163
|
});
|
|
3275
4164
|
|
|
3276
|
-
class
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
4165
|
+
class PendingVerificationStore {
|
|
4166
|
+
/**
|
|
4167
|
+
* @param namespace Provider namespace (e.g. `'sms'`, `'email-code'`, `'magic-link'`). Keys are
|
|
4168
|
+
* stored under `cap_auth_pending_<namespace>` so providers never collide.
|
|
4169
|
+
*/
|
|
4170
|
+
constructor(namespace) {
|
|
4171
|
+
/** In-memory mirror so the store works in SSR / private-mode where localStorage is unavailable. */
|
|
4172
|
+
this.memory = new Map();
|
|
4173
|
+
this.storageKey = `cap_auth_pending_${namespace}`;
|
|
4174
|
+
}
|
|
4175
|
+
getLocalStorage() {
|
|
4176
|
+
try {
|
|
4177
|
+
return typeof localStorage !== 'undefined' ? localStorage : null;
|
|
4178
|
+
}
|
|
4179
|
+
catch (_a) {
|
|
4180
|
+
// Access to localStorage can throw (e.g. sandboxed iframe) — fall back to memory only.
|
|
4181
|
+
return null;
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
readAll() {
|
|
4185
|
+
const ls = this.getLocalStorage();
|
|
4186
|
+
if (!ls) {
|
|
4187
|
+
return Object.fromEntries(this.memory);
|
|
4188
|
+
}
|
|
4189
|
+
try {
|
|
4190
|
+
const raw = ls.getItem(this.storageKey);
|
|
4191
|
+
if (!raw)
|
|
4192
|
+
return {};
|
|
4193
|
+
const parsed = JSON.parse(raw);
|
|
4194
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
4195
|
+
}
|
|
4196
|
+
catch (error) {
|
|
4197
|
+
defaultLogger.warn(`PendingVerificationStore: failed to read ${this.storageKey}`, error);
|
|
4198
|
+
return {};
|
|
4199
|
+
}
|
|
4200
|
+
}
|
|
4201
|
+
writeAll(all) {
|
|
4202
|
+
const ls = this.getLocalStorage();
|
|
4203
|
+
if (!ls) {
|
|
4204
|
+
this.memory.clear();
|
|
4205
|
+
for (const [k, v] of Object.entries(all))
|
|
4206
|
+
this.memory.set(k, v);
|
|
4207
|
+
return;
|
|
4208
|
+
}
|
|
4209
|
+
try {
|
|
4210
|
+
ls.setItem(this.storageKey, JSON.stringify(all));
|
|
4211
|
+
}
|
|
4212
|
+
catch (error) {
|
|
4213
|
+
defaultLogger.warn(`PendingVerificationStore: failed to write ${this.storageKey}`, error);
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
/**
|
|
4217
|
+
* Stores (or replaces) the pending record for `key` (phone / email / magic-link token). Other
|
|
4218
|
+
* expired entries in the namespace are pruned here to bound storage growth.
|
|
4219
|
+
*/
|
|
4220
|
+
set(key, record) {
|
|
4221
|
+
const all = this.readAll();
|
|
4222
|
+
this.pruneExpired(all, key);
|
|
4223
|
+
all[key] = record;
|
|
4224
|
+
this.writeAll(all);
|
|
4225
|
+
}
|
|
4226
|
+
/**
|
|
4227
|
+
* Returns the pending record for `key`, or null if absent. Does NOT filter by expiry — the
|
|
4228
|
+
* caller owns the expiry decision so it can throw a precise error and clean up itself.
|
|
4229
|
+
*/
|
|
4230
|
+
get(key) {
|
|
4231
|
+
var _a;
|
|
4232
|
+
const all = this.readAll();
|
|
4233
|
+
return (_a = all[key]) !== null && _a !== void 0 ? _a : null;
|
|
4234
|
+
}
|
|
4235
|
+
/** Removes the pending record for `key` (e.g. after a successful or expired verification). */
|
|
4236
|
+
delete(key) {
|
|
4237
|
+
const all = this.readAll();
|
|
4238
|
+
if (key in all) {
|
|
4239
|
+
delete all[key];
|
|
4240
|
+
this.writeAll(all);
|
|
4241
|
+
}
|
|
4242
|
+
}
|
|
4243
|
+
/** Clears every pending record in this namespace. */
|
|
4244
|
+
clear() {
|
|
4245
|
+
const ls = this.getLocalStorage();
|
|
4246
|
+
this.memory.clear();
|
|
4247
|
+
if (ls) {
|
|
4248
|
+
try {
|
|
4249
|
+
ls.removeItem(this.storageKey);
|
|
4250
|
+
}
|
|
4251
|
+
catch (error) {
|
|
4252
|
+
defaultLogger.warn(`PendingVerificationStore: failed to clear ${this.storageKey}`, error);
|
|
4253
|
+
}
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
pruneExpired(all, exceptKey) {
|
|
4257
|
+
const now = Date.now();
|
|
4258
|
+
for (const [k, v] of Object.entries(all)) {
|
|
4259
|
+
if (k !== exceptKey && now > v.expires) {
|
|
4260
|
+
delete all[k];
|
|
4261
|
+
}
|
|
4262
|
+
}
|
|
4263
|
+
return all;
|
|
4264
|
+
}
|
|
4265
|
+
}
|
|
4266
|
+
|
|
4267
|
+
class MagicLinkProvider extends BaseAuthProvider {
|
|
4268
|
+
get name() {
|
|
4269
|
+
return 'magic-link';
|
|
4270
|
+
}
|
|
4271
|
+
constructor(input) {
|
|
4272
|
+
super(resolveProviderConfig(exports.AuthProvider.EMAIL_MAGIC_LINK, input));
|
|
4273
|
+
// Persisted (SSR-guarded localStorage) so a magic link clicked from an email — which opens a
|
|
4274
|
+
// FRESH page load with empty in-memory state — can still find its pending entry to verify
|
|
4275
|
+
// against. Keyed by the link token (already present in the callback URL); we store only the
|
|
4276
|
+
// email + expiry, never any additional secret (see PendingVerificationStore + F-11).
|
|
4277
|
+
this.pendingVerification = new PendingVerificationStore('magic-link');
|
|
4278
|
+
// Magic link uses its config as-is (no defaults to merge).
|
|
4279
|
+
this.config = this.options;
|
|
3282
4280
|
// Check for magic link callback on initialization
|
|
3283
4281
|
this.checkForMagicLinkCallback();
|
|
3284
4282
|
}
|
|
3285
4283
|
async signIn(options) {
|
|
3286
4284
|
if (!(options === null || options === void 0 ? void 0 : options.email)) {
|
|
3287
|
-
throw new AuthError(
|
|
4285
|
+
throw new AuthError(exports.AuthErrorCode.EMAIL_REQUIRED, 'Email is required for magic link authentication');
|
|
3288
4286
|
}
|
|
3289
4287
|
try {
|
|
3290
4288
|
// Send magic link to email
|
|
3291
4289
|
const token = this.generateToken();
|
|
3292
4290
|
const magicLink = this.generateMagicLink(token);
|
|
3293
|
-
// Store pending verification
|
|
4291
|
+
// Store pending verification (persisted; email + expiry only, keyed by the link token).
|
|
3294
4292
|
this.pendingVerification.set(token, {
|
|
3295
|
-
|
|
4293
|
+
identifier: options.email,
|
|
4294
|
+
sessionId: token,
|
|
4295
|
+
attempts: 0,
|
|
3296
4296
|
expires: Date.now() + 15 * 60 * 1000, // 15 minutes
|
|
3297
4297
|
});
|
|
3298
4298
|
// Send email via backend API
|
|
@@ -3309,7 +4309,7 @@ class MagicLinkProvider {
|
|
|
3309
4309
|
}),
|
|
3310
4310
|
});
|
|
3311
4311
|
if (!response.ok) {
|
|
3312
|
-
throw new AuthError(
|
|
4312
|
+
throw new AuthError(exports.AuthErrorCode.SEND_LINK_FAILED, 'Failed to send magic link');
|
|
3313
4313
|
}
|
|
3314
4314
|
// Return partial auth result for pending state
|
|
3315
4315
|
const tempUser = {
|
|
@@ -3343,18 +4343,22 @@ class MagicLinkProvider {
|
|
|
3343
4343
|
};
|
|
3344
4344
|
}
|
|
3345
4345
|
catch (error) {
|
|
3346
|
-
|
|
4346
|
+
if (error instanceof AuthError)
|
|
4347
|
+
throw error;
|
|
4348
|
+
throw new AuthError(exports.AuthErrorCode.SEND_LINK_FAILED, error.message || 'Failed to send magic link');
|
|
3347
4349
|
}
|
|
3348
4350
|
}
|
|
3349
4351
|
async verifyMagicLink(token) {
|
|
3350
4352
|
const pending = this.pendingVerification.get(token);
|
|
3351
4353
|
if (!pending) {
|
|
3352
|
-
throw new AuthError(
|
|
4354
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Invalid or expired magic link');
|
|
3353
4355
|
}
|
|
3354
4356
|
if (Date.now() > pending.expires) {
|
|
3355
4357
|
this.pendingVerification.delete(token);
|
|
3356
|
-
throw new AuthError(
|
|
4358
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Magic link has expired');
|
|
3357
4359
|
}
|
|
4360
|
+
// The persisted record stores the email under `identifier`.
|
|
4361
|
+
const email = pending.identifier;
|
|
3358
4362
|
try {
|
|
3359
4363
|
// Verify token with backend if configured
|
|
3360
4364
|
if (this.config.verifyUrl) {
|
|
@@ -3365,27 +4369,27 @@ class MagicLinkProvider {
|
|
|
3365
4369
|
},
|
|
3366
4370
|
body: JSON.stringify({
|
|
3367
4371
|
token,
|
|
3368
|
-
email:
|
|
4372
|
+
email: email,
|
|
3369
4373
|
clientId: this.config.clientId,
|
|
3370
4374
|
}),
|
|
3371
4375
|
});
|
|
3372
4376
|
if (!response.ok) {
|
|
3373
|
-
throw new AuthError(
|
|
4377
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, 'Failed to verify magic link');
|
|
3374
4378
|
}
|
|
3375
4379
|
const data = await response.json();
|
|
3376
4380
|
// Create user from verified data
|
|
3377
4381
|
const user = {
|
|
3378
|
-
uid: data.uid || this.generateUid(
|
|
3379
|
-
email:
|
|
3380
|
-
displayName: data.displayName ||
|
|
4382
|
+
uid: data.uid || this.generateUid(email),
|
|
4383
|
+
email: email,
|
|
4384
|
+
displayName: data.displayName || email.split('@')[0],
|
|
3381
4385
|
photoURL: data.photoURL || null,
|
|
3382
4386
|
emailVerified: true,
|
|
3383
4387
|
providerData: [
|
|
3384
4388
|
{
|
|
3385
4389
|
providerId: this.name,
|
|
3386
|
-
uid: data.uid ||
|
|
3387
|
-
displayName: data.displayName ||
|
|
3388
|
-
email:
|
|
4390
|
+
uid: data.uid || email,
|
|
4391
|
+
displayName: data.displayName || email.split('@')[0],
|
|
4392
|
+
email: email,
|
|
3389
4393
|
phoneNumber: null,
|
|
3390
4394
|
photoURL: data.photoURL || null,
|
|
3391
4395
|
},
|
|
@@ -3414,17 +4418,17 @@ class MagicLinkProvider {
|
|
|
3414
4418
|
else {
|
|
3415
4419
|
// Simple verification without backend
|
|
3416
4420
|
const user = {
|
|
3417
|
-
uid: this.generateUid(
|
|
3418
|
-
email:
|
|
3419
|
-
displayName:
|
|
4421
|
+
uid: this.generateUid(email),
|
|
4422
|
+
email: email,
|
|
4423
|
+
displayName: email.split('@')[0],
|
|
3420
4424
|
photoURL: null,
|
|
3421
4425
|
emailVerified: true,
|
|
3422
4426
|
providerData: [
|
|
3423
4427
|
{
|
|
3424
4428
|
providerId: this.name,
|
|
3425
|
-
uid:
|
|
3426
|
-
displayName:
|
|
3427
|
-
email:
|
|
4429
|
+
uid: email,
|
|
4430
|
+
displayName: email.split('@')[0],
|
|
4431
|
+
email: email,
|
|
3428
4432
|
phoneNumber: null,
|
|
3429
4433
|
photoURL: null,
|
|
3430
4434
|
},
|
|
@@ -3451,7 +4455,9 @@ class MagicLinkProvider {
|
|
|
3451
4455
|
}
|
|
3452
4456
|
}
|
|
3453
4457
|
catch (error) {
|
|
3454
|
-
|
|
4458
|
+
if (error instanceof AuthError)
|
|
4459
|
+
throw error;
|
|
4460
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify magic link');
|
|
3455
4461
|
}
|
|
3456
4462
|
}
|
|
3457
4463
|
async signOut() {
|
|
@@ -3463,7 +4469,7 @@ class MagicLinkProvider {
|
|
|
3463
4469
|
return null;
|
|
3464
4470
|
}
|
|
3465
4471
|
async refreshToken() {
|
|
3466
|
-
throw new AuthError(
|
|
4472
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Token refresh is not supported for magic link authentication');
|
|
3467
4473
|
}
|
|
3468
4474
|
generateToken() {
|
|
3469
4475
|
const array = new Uint8Array(32);
|
|
@@ -3520,14 +4526,9 @@ class MagicLinkProvider {
|
|
|
3520
4526
|
// Magic link auth is supported if we have the required config
|
|
3521
4527
|
return !!this.config.sendLinkUrl;
|
|
3522
4528
|
}
|
|
3523
|
-
|
|
3524
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for magic link authentication');
|
|
3525
|
-
}
|
|
3526
|
-
async unlinkAccount(_options) {
|
|
3527
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for magic link authentication');
|
|
3528
|
-
}
|
|
4529
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
3529
4530
|
async revokeAccess(_token) {
|
|
3530
|
-
// Magic link doesn't have persistent access to revoke
|
|
4531
|
+
// Magic link doesn't have persistent access to revoke; clear any pending verification.
|
|
3531
4532
|
this.pendingVerification.clear();
|
|
3532
4533
|
}
|
|
3533
4534
|
}
|
|
@@ -3537,17 +4538,22 @@ var magicLinkProvider = /*#__PURE__*/Object.freeze({
|
|
|
3537
4538
|
MagicLinkProvider: MagicLinkProvider
|
|
3538
4539
|
});
|
|
3539
4540
|
|
|
3540
|
-
class SMSProvider {
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
4541
|
+
class SMSProvider extends BaseAuthProvider {
|
|
4542
|
+
get name() {
|
|
4543
|
+
return 'sms';
|
|
4544
|
+
}
|
|
4545
|
+
constructor(input) {
|
|
4546
|
+
super(resolveProviderConfig(exports.AuthProvider.SMS, input));
|
|
4547
|
+
// Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
|
|
4548
|
+
// page change between sending and verifying the code. Only non-secret metadata is stored —
|
|
4549
|
+
// never the SMS code itself (see PendingVerificationStore + F-11).
|
|
4550
|
+
this.pendingVerifications = new PendingVerificationStore('sms');
|
|
3544
4551
|
this.MAX_ATTEMPTS = 3;
|
|
3545
|
-
|
|
3546
|
-
this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, config);
|
|
4552
|
+
this.config = Object.assign({ countryCode: '+1', codeLength: 6, resendDelay: 60000 }, this.options);
|
|
3547
4553
|
}
|
|
3548
4554
|
async signIn(options) {
|
|
3549
4555
|
if (!(options === null || options === void 0 ? void 0 : options.phoneNumber)) {
|
|
3550
|
-
throw new AuthError(
|
|
4556
|
+
throw new AuthError(exports.AuthErrorCode.PHONE_REQUIRED, 'Phone number is required for SMS authentication');
|
|
3551
4557
|
}
|
|
3552
4558
|
// If code is provided, verify it
|
|
3553
4559
|
if (options.code) {
|
|
@@ -3566,7 +4572,7 @@ class SMSProvider {
|
|
|
3566
4572
|
const timeSinceLastResend = Date.now() - existing.lastResent;
|
|
3567
4573
|
if (timeSinceLastResend < this.config.resendDelay) {
|
|
3568
4574
|
const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
|
|
3569
|
-
throw new AuthError(
|
|
4575
|
+
throw new AuthError(exports.AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
|
|
3570
4576
|
}
|
|
3571
4577
|
}
|
|
3572
4578
|
// Send SMS code via backend
|
|
@@ -3583,12 +4589,12 @@ class SMSProvider {
|
|
|
3583
4589
|
});
|
|
3584
4590
|
if (!response.ok) {
|
|
3585
4591
|
const error = await response.json().catch(() => ({}));
|
|
3586
|
-
throw new AuthError(
|
|
4592
|
+
throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
|
|
3587
4593
|
}
|
|
3588
4594
|
const data = await response.json();
|
|
3589
|
-
// Store pending verification
|
|
4595
|
+
// Store pending verification (persisted; metadata only, never the code).
|
|
3590
4596
|
this.pendingVerifications.set(formattedPhone, {
|
|
3591
|
-
|
|
4597
|
+
identifier: formattedPhone,
|
|
3592
4598
|
sessionId: data.sessionId,
|
|
3593
4599
|
expires: Date.now() + 10 * 60 * 1000, // 10 minutes
|
|
3594
4600
|
attempts: 0,
|
|
@@ -3631,26 +4637,27 @@ class SMSProvider {
|
|
|
3631
4637
|
catch (error) {
|
|
3632
4638
|
if (error instanceof AuthError)
|
|
3633
4639
|
throw error;
|
|
3634
|
-
throw new AuthError(
|
|
4640
|
+
throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send SMS code');
|
|
3635
4641
|
}
|
|
3636
4642
|
}
|
|
3637
4643
|
async verifyCode(phoneNumber, code) {
|
|
3638
4644
|
const formattedPhone = this.formatPhoneNumber(phoneNumber);
|
|
3639
4645
|
const pending = this.pendingVerifications.get(formattedPhone);
|
|
3640
4646
|
if (!pending) {
|
|
3641
|
-
throw new AuthError(
|
|
4647
|
+
throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending SMS verification found');
|
|
3642
4648
|
}
|
|
3643
4649
|
if (Date.now() > pending.expires) {
|
|
3644
4650
|
this.pendingVerifications.delete(formattedPhone);
|
|
3645
|
-
throw new AuthError(
|
|
4651
|
+
throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'SMS code has expired');
|
|
3646
4652
|
}
|
|
3647
4653
|
if (pending.attempts >= this.MAX_ATTEMPTS) {
|
|
3648
4654
|
this.pendingVerifications.delete(formattedPhone);
|
|
3649
|
-
throw new AuthError(
|
|
4655
|
+
throw new AuthError(exports.AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts');
|
|
3650
4656
|
}
|
|
3651
4657
|
try {
|
|
3652
|
-
// Increment attempts
|
|
4658
|
+
// Increment attempts and persist the bump (so the count survives a reload mid-flow).
|
|
3653
4659
|
pending.attempts++;
|
|
4660
|
+
this.pendingVerifications.set(formattedPhone, pending);
|
|
3654
4661
|
// Verify code with backend
|
|
3655
4662
|
const response = await fetch(this.config.verifyCodeUrl, {
|
|
3656
4663
|
method: 'POST',
|
|
@@ -3667,9 +4674,9 @@ class SMSProvider {
|
|
|
3667
4674
|
if (!response.ok) {
|
|
3668
4675
|
const error = await response.json().catch(() => ({}));
|
|
3669
4676
|
if (response.status === 401) {
|
|
3670
|
-
throw new AuthError(
|
|
4677
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid SMS code');
|
|
3671
4678
|
}
|
|
3672
|
-
throw new AuthError(
|
|
4679
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
|
|
3673
4680
|
}
|
|
3674
4681
|
const data = await response.json();
|
|
3675
4682
|
// Create user from verified data
|
|
@@ -3715,7 +4722,7 @@ class SMSProvider {
|
|
|
3715
4722
|
catch (error) {
|
|
3716
4723
|
if (error instanceof AuthError)
|
|
3717
4724
|
throw error;
|
|
3718
|
-
throw new AuthError(
|
|
4725
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify SMS code');
|
|
3719
4726
|
}
|
|
3720
4727
|
}
|
|
3721
4728
|
async signOut() {
|
|
@@ -3727,8 +4734,9 @@ class SMSProvider {
|
|
|
3727
4734
|
return null;
|
|
3728
4735
|
}
|
|
3729
4736
|
async refreshToken(_options) {
|
|
3730
|
-
//
|
|
3731
|
-
|
|
4737
|
+
// SMS code authentication is single-use and has no refresh flow; the user must request
|
|
4738
|
+
// a new verification code rather than refresh a token.
|
|
4739
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'SMS authentication does not support token refresh; request a new code instead.');
|
|
3732
4740
|
}
|
|
3733
4741
|
formatPhoneNumber(phoneNumber) {
|
|
3734
4742
|
// Remove all non-numeric characters
|
|
@@ -3779,14 +4787,9 @@ class SMSProvider {
|
|
|
3779
4787
|
// SMS auth is supported if we have the required config
|
|
3780
4788
|
return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
|
|
3781
4789
|
}
|
|
3782
|
-
|
|
3783
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for SMS authentication');
|
|
3784
|
-
}
|
|
3785
|
-
async unlinkAccount(_options) {
|
|
3786
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for SMS authentication');
|
|
3787
|
-
}
|
|
4790
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
3788
4791
|
async revokeAccess(_token) {
|
|
3789
|
-
// SMS auth doesn't have persistent access to revoke
|
|
4792
|
+
// SMS auth doesn't have persistent access to revoke; clear any pending verification.
|
|
3790
4793
|
this.pendingVerifications.clear();
|
|
3791
4794
|
}
|
|
3792
4795
|
}
|
|
@@ -3796,24 +4799,27 @@ var smsProvider = /*#__PURE__*/Object.freeze({
|
|
|
3796
4799
|
SMSProvider: SMSProvider
|
|
3797
4800
|
});
|
|
3798
4801
|
|
|
3799
|
-
class EmailPasswordProvider {
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
4802
|
+
class EmailPasswordProvider extends BaseAuthProvider {
|
|
4803
|
+
get name() {
|
|
4804
|
+
return 'email-password';
|
|
4805
|
+
}
|
|
4806
|
+
constructor(input) {
|
|
4807
|
+
super(resolveProviderConfig(exports.AuthProvider.EMAIL_PASSWORD, input));
|
|
4808
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
4809
|
+
// so email/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
3803
4810
|
this.authToken = null;
|
|
3804
4811
|
this.refreshTokenValue = null;
|
|
3805
|
-
// Initialize with config
|
|
3806
4812
|
this.config = Object.assign({ allowSignUp: true, passwordRequirements: {
|
|
3807
4813
|
minLength: 8,
|
|
3808
4814
|
requireUppercase: true,
|
|
3809
4815
|
requireLowercase: true,
|
|
3810
4816
|
requireNumbers: true,
|
|
3811
4817
|
requireSpecialChars: false,
|
|
3812
|
-
} },
|
|
4818
|
+
} }, this.options);
|
|
3813
4819
|
}
|
|
3814
4820
|
async signIn(options) {
|
|
3815
4821
|
if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
3816
|
-
throw new AuthError(
|
|
4822
|
+
throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
|
|
3817
4823
|
}
|
|
3818
4824
|
try {
|
|
3819
4825
|
const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
|
|
@@ -3830,9 +4836,9 @@ class EmailPasswordProvider {
|
|
|
3830
4836
|
if (!response.ok) {
|
|
3831
4837
|
const error = await response.json().catch(() => ({}));
|
|
3832
4838
|
if (response.status === 401) {
|
|
3833
|
-
throw new AuthError(
|
|
4839
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid email or password');
|
|
3834
4840
|
}
|
|
3835
|
-
throw new AuthError(
|
|
4841
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
|
|
3836
4842
|
}
|
|
3837
4843
|
const data = await response.json();
|
|
3838
4844
|
// Create user object
|
|
@@ -3879,24 +4885,24 @@ class EmailPasswordProvider {
|
|
|
3879
4885
|
catch (error) {
|
|
3880
4886
|
if (error instanceof AuthError)
|
|
3881
4887
|
throw error;
|
|
3882
|
-
throw new AuthError(
|
|
4888
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with email and password');
|
|
3883
4889
|
}
|
|
3884
4890
|
}
|
|
3885
4891
|
async signUp(options) {
|
|
3886
4892
|
if (!this.config.allowSignUp) {
|
|
3887
|
-
throw new AuthError(
|
|
4893
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
|
|
3888
4894
|
}
|
|
3889
4895
|
if (!(options === null || options === void 0 ? void 0 : options.email) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
3890
|
-
throw new AuthError(
|
|
4896
|
+
throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Email and password are required');
|
|
3891
4897
|
}
|
|
3892
4898
|
// Validate email
|
|
3893
4899
|
if (!this.isValidEmail(options.email)) {
|
|
3894
|
-
throw new AuthError(
|
|
4900
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
3895
4901
|
}
|
|
3896
4902
|
// Validate password
|
|
3897
4903
|
const passwordError = this.validatePassword(options.password);
|
|
3898
4904
|
if (passwordError) {
|
|
3899
|
-
throw new AuthError(
|
|
4905
|
+
throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
3900
4906
|
}
|
|
3901
4907
|
try {
|
|
3902
4908
|
const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
|
|
@@ -3915,9 +4921,9 @@ class EmailPasswordProvider {
|
|
|
3915
4921
|
if (!response.ok) {
|
|
3916
4922
|
const error = await response.json().catch(() => ({}));
|
|
3917
4923
|
if (response.status === 409) {
|
|
3918
|
-
throw new AuthError(
|
|
4924
|
+
throw new AuthError(exports.AuthErrorCode.EMAIL_ALREADY_IN_USE, 'Email already in use');
|
|
3919
4925
|
}
|
|
3920
|
-
throw new AuthError(
|
|
4926
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
3921
4927
|
}
|
|
3922
4928
|
const data = await response.json();
|
|
3923
4929
|
// Create user object
|
|
@@ -3964,7 +4970,7 @@ class EmailPasswordProvider {
|
|
|
3964
4970
|
catch (error) {
|
|
3965
4971
|
if (error instanceof AuthError)
|
|
3966
4972
|
throw error;
|
|
3967
|
-
throw new AuthError(
|
|
4973
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
3968
4974
|
}
|
|
3969
4975
|
}
|
|
3970
4976
|
async signOut() {
|
|
@@ -3994,7 +5000,7 @@ class EmailPasswordProvider {
|
|
|
3994
5000
|
}
|
|
3995
5001
|
async refreshToken(_options) {
|
|
3996
5002
|
if (!this.refreshTokenValue) {
|
|
3997
|
-
throw new AuthError(
|
|
5003
|
+
throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
|
|
3998
5004
|
}
|
|
3999
5005
|
try {
|
|
4000
5006
|
const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
|
|
@@ -4008,7 +5014,7 @@ class EmailPasswordProvider {
|
|
|
4008
5014
|
}),
|
|
4009
5015
|
});
|
|
4010
5016
|
if (!response.ok) {
|
|
4011
|
-
throw new AuthError(
|
|
5017
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
|
|
4012
5018
|
}
|
|
4013
5019
|
const data = await response.json();
|
|
4014
5020
|
// Update tokens
|
|
@@ -4030,17 +5036,17 @@ class EmailPasswordProvider {
|
|
|
4030
5036
|
catch (error) {
|
|
4031
5037
|
if (error instanceof AuthError)
|
|
4032
5038
|
throw error;
|
|
4033
|
-
throw new AuthError(
|
|
5039
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
|
|
4034
5040
|
}
|
|
4035
5041
|
}
|
|
4036
5042
|
async updatePassword(currentPassword, newPassword) {
|
|
4037
5043
|
if (!this.currentUser || !this.authToken) {
|
|
4038
|
-
throw new AuthError(
|
|
5044
|
+
throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
4039
5045
|
}
|
|
4040
5046
|
// Validate new password
|
|
4041
5047
|
const passwordError = this.validatePassword(newPassword);
|
|
4042
5048
|
if (passwordError) {
|
|
4043
|
-
throw new AuthError(
|
|
5049
|
+
throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
4044
5050
|
}
|
|
4045
5051
|
try {
|
|
4046
5052
|
const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
|
|
@@ -4058,20 +5064,20 @@ class EmailPasswordProvider {
|
|
|
4058
5064
|
if (!response.ok) {
|
|
4059
5065
|
const error = await response.json().catch(() => ({}));
|
|
4060
5066
|
if (response.status === 401) {
|
|
4061
|
-
throw new AuthError(
|
|
5067
|
+
throw new AuthError(exports.AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
|
|
4062
5068
|
}
|
|
4063
|
-
throw new AuthError(
|
|
5069
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4064
5070
|
}
|
|
4065
5071
|
}
|
|
4066
5072
|
catch (error) {
|
|
4067
5073
|
if (error instanceof AuthError)
|
|
4068
5074
|
throw error;
|
|
4069
|
-
throw new AuthError(
|
|
5075
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
4070
5076
|
}
|
|
4071
5077
|
}
|
|
4072
5078
|
async sendPasswordResetEmail(email) {
|
|
4073
5079
|
if (!this.isValidEmail(email)) {
|
|
4074
|
-
throw new AuthError(
|
|
5080
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
4075
5081
|
}
|
|
4076
5082
|
try {
|
|
4077
5083
|
const response = await fetch(`${this.config.apiUrl}/auth/reset-password`, {
|
|
@@ -4086,21 +5092,21 @@ class EmailPasswordProvider {
|
|
|
4086
5092
|
});
|
|
4087
5093
|
if (!response.ok) {
|
|
4088
5094
|
const error = await response.json().catch(() => ({}));
|
|
4089
|
-
throw new AuthError(
|
|
5095
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send reset email');
|
|
4090
5096
|
}
|
|
4091
5097
|
}
|
|
4092
5098
|
catch (error) {
|
|
4093
5099
|
if (error instanceof AuthError)
|
|
4094
5100
|
throw error;
|
|
4095
|
-
throw new AuthError(
|
|
5101
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset email');
|
|
4096
5102
|
}
|
|
4097
5103
|
}
|
|
4098
5104
|
async sendEmailVerification() {
|
|
4099
5105
|
if (!this.currentUser || !this.authToken) {
|
|
4100
|
-
throw new AuthError(
|
|
5106
|
+
throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
4101
5107
|
}
|
|
4102
5108
|
if (this.currentUser.emailVerified) {
|
|
4103
|
-
throw new AuthError(
|
|
5109
|
+
throw new AuthError(exports.AuthErrorCode.EMAIL_ALREADY_VERIFIED, 'Email already verified');
|
|
4104
5110
|
}
|
|
4105
5111
|
try {
|
|
4106
5112
|
const response = await fetch(`${this.config.apiUrl}/auth/verify-email`, {
|
|
@@ -4115,13 +5121,13 @@ class EmailPasswordProvider {
|
|
|
4115
5121
|
});
|
|
4116
5122
|
if (!response.ok) {
|
|
4117
5123
|
const error = await response.json().catch(() => ({}));
|
|
4118
|
-
throw new AuthError(
|
|
5124
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
|
|
4119
5125
|
}
|
|
4120
5126
|
}
|
|
4121
5127
|
catch (error) {
|
|
4122
5128
|
if (error instanceof AuthError)
|
|
4123
5129
|
throw error;
|
|
4124
|
-
throw new AuthError(
|
|
5130
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to send verification email');
|
|
4125
5131
|
}
|
|
4126
5132
|
}
|
|
4127
5133
|
isValidEmail(email) {
|
|
@@ -4155,12 +5161,7 @@ class EmailPasswordProvider {
|
|
|
4155
5161
|
// Email/Password auth is supported if we have the required config
|
|
4156
5162
|
return !!this.config.apiUrl;
|
|
4157
5163
|
}
|
|
4158
|
-
|
|
4159
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for email/password authentication');
|
|
4160
|
-
}
|
|
4161
|
-
async unlinkAccount(_options) {
|
|
4162
|
-
throw new AuthError('NOT_SUPPORTED', 'Account unlinking is not supported for email/password authentication');
|
|
4163
|
-
}
|
|
5164
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
4164
5165
|
async revokeAccess(_token) {
|
|
4165
5166
|
// For email/password auth, revoking access means signing out
|
|
4166
5167
|
await this.signOut();
|
|
@@ -4172,10 +5173,15 @@ var emailPasswordProvider = /*#__PURE__*/Object.freeze({
|
|
|
4172
5173
|
EmailPasswordProvider: EmailPasswordProvider
|
|
4173
5174
|
});
|
|
4174
5175
|
|
|
4175
|
-
class BiometricProvider {
|
|
4176
|
-
|
|
4177
|
-
|
|
5176
|
+
class BiometricProvider extends BaseAuthProvider {
|
|
5177
|
+
get name() {
|
|
5178
|
+
return 'biometric';
|
|
5179
|
+
}
|
|
5180
|
+
constructor(input = {}) {
|
|
5181
|
+
super(resolveProviderConfig(exports.AuthProvider.BIOMETRIC, input));
|
|
4178
5182
|
this.biometricAuth = null;
|
|
5183
|
+
this.cryptoKeyPromise = null;
|
|
5184
|
+
const config = this.options;
|
|
4179
5185
|
this.config = Object.assign({ reason: 'Authenticate to access your account', title: 'Authentication Required', subtitle: 'Access your account securely', fallbackTitle: 'Use Passcode', requireRecentAuth: true, recentAuthTimeout: 5 * 60 * 1000 }, config);
|
|
4180
5186
|
this.storageKey =
|
|
4181
5187
|
config.storageKey || 'capacitor-auth-biometric-credentials';
|
|
@@ -4189,31 +5195,31 @@ class BiometricProvider {
|
|
|
4189
5195
|
this.biometricAuth = BiometricAuth;
|
|
4190
5196
|
}
|
|
4191
5197
|
catch (_a) {
|
|
4192
|
-
|
|
5198
|
+
defaultLogger.warn('Biometric authentication plugin not available');
|
|
4193
5199
|
}
|
|
4194
5200
|
}
|
|
4195
5201
|
async signIn(_options) {
|
|
4196
5202
|
var _a, _b, _c;
|
|
4197
5203
|
if (!this.biometricAuth) {
|
|
4198
|
-
throw new AuthError(
|
|
5204
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric authentication plugin is not installed. Please install capacitor-biometric-authentication');
|
|
4199
5205
|
}
|
|
4200
5206
|
try {
|
|
4201
5207
|
// Check if biometry is available
|
|
4202
5208
|
const checkResult = await this.biometricAuth.checkBiometry();
|
|
4203
5209
|
if (!checkResult.isAvailable) {
|
|
4204
|
-
throw new AuthError(
|
|
5210
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, checkResult.reason ||
|
|
4205
5211
|
'Biometric authentication is not available on this device');
|
|
4206
5212
|
}
|
|
4207
5213
|
// Check if we have stored credentials
|
|
4208
5214
|
const storedCredentials = await this.getStoredCredentials();
|
|
4209
5215
|
if (!storedCredentials) {
|
|
4210
|
-
throw new AuthError(
|
|
5216
|
+
throw new AuthError(exports.AuthErrorCode.NO_STORED_CREDENTIALS, 'No stored credentials found. Please sign in with another method first.');
|
|
4211
5217
|
}
|
|
4212
5218
|
// Check if recent auth is required
|
|
4213
5219
|
if (this.config.requireRecentAuth) {
|
|
4214
5220
|
const timeSinceLastAuth = Date.now() - storedCredentials.lastAuthTime;
|
|
4215
5221
|
if (timeSinceLastAuth > this.config.recentAuthTimeout) {
|
|
4216
|
-
throw new AuthError(
|
|
5222
|
+
throw new AuthError(exports.AuthErrorCode.REQUIRES_RECENT_LOGIN, 'Authentication expired. Please sign in with another method.');
|
|
4217
5223
|
}
|
|
4218
5224
|
}
|
|
4219
5225
|
// Perform biometric authentication
|
|
@@ -4249,17 +5255,17 @@ class BiometricProvider {
|
|
|
4249
5255
|
throw error;
|
|
4250
5256
|
// Handle biometric errors
|
|
4251
5257
|
if (error.code === 'userCancel' || ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('cancel'))) {
|
|
4252
|
-
throw new AuthError(
|
|
5258
|
+
throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Authentication cancelled by user');
|
|
4253
5259
|
}
|
|
4254
5260
|
else if (error.code === 'biometryLockout' ||
|
|
4255
5261
|
((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('lockout'))) {
|
|
4256
|
-
throw new AuthError(
|
|
5262
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_LOCKOUT, 'Too many failed attempts. Biometry is locked.');
|
|
4257
5263
|
}
|
|
4258
5264
|
else if (error.code === 'biometryNotEnrolled' ||
|
|
4259
5265
|
((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('enrolled'))) {
|
|
4260
|
-
throw new AuthError(
|
|
5266
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_ENROLLED, 'No biometric credentials are enrolled');
|
|
4261
5267
|
}
|
|
4262
|
-
throw new AuthError(
|
|
5268
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_AUTHENTICATION_FAILED, error.message || 'Biometric authentication failed');
|
|
4263
5269
|
}
|
|
4264
5270
|
}
|
|
4265
5271
|
async signOut() {
|
|
@@ -4323,6 +5329,8 @@ class BiometricProvider {
|
|
|
4323
5329
|
return true;
|
|
4324
5330
|
}
|
|
4325
5331
|
async getStoredCredentials() {
|
|
5332
|
+
if (typeof localStorage === 'undefined')
|
|
5333
|
+
return null;
|
|
4326
5334
|
try {
|
|
4327
5335
|
const stored = localStorage.getItem(this.storageKey);
|
|
4328
5336
|
if (!stored)
|
|
@@ -4335,25 +5343,118 @@ class BiometricProvider {
|
|
|
4335
5343
|
}
|
|
4336
5344
|
}
|
|
4337
5345
|
async storeCredentials(credentials) {
|
|
5346
|
+
if (typeof localStorage === 'undefined') {
|
|
5347
|
+
throw new AuthError(exports.AuthErrorCode.BIOMETRIC_NOT_AVAILABLE, 'Biometric credential storage is unavailable in this environment');
|
|
5348
|
+
}
|
|
4338
5349
|
try {
|
|
4339
5350
|
const encrypted = await this.encrypt(JSON.stringify(credentials));
|
|
4340
5351
|
localStorage.setItem(this.storageKey, encrypted);
|
|
4341
5352
|
}
|
|
4342
|
-
catch (
|
|
4343
|
-
throw new AuthError(
|
|
5353
|
+
catch (error) {
|
|
5354
|
+
throw new AuthError(exports.AuthErrorCode.STORAGE_ERROR, 'Failed to store credentials', undefined, { cause: String(error) });
|
|
4344
5355
|
}
|
|
4345
5356
|
}
|
|
4346
5357
|
async clearStoredCredentials() {
|
|
4347
|
-
localStorage
|
|
5358
|
+
if (typeof localStorage !== 'undefined') {
|
|
5359
|
+
localStorage.removeItem(this.storageKey);
|
|
5360
|
+
}
|
|
5361
|
+
}
|
|
5362
|
+
/**
|
|
5363
|
+
* Persistent, non-extractable AES-GCM key kept in IndexedDB so it cannot be read back out by
|
|
5364
|
+
* script — stored biometric credentials are therefore not recoverable by simply reading
|
|
5365
|
+
* localStorage (unlike the previous base64 encoding).
|
|
5366
|
+
*/
|
|
5367
|
+
getEncryptionKey() {
|
|
5368
|
+
if (!this.cryptoKeyPromise) {
|
|
5369
|
+
this.cryptoKeyPromise = (async () => {
|
|
5370
|
+
const existing = await this.loadKeyFromIndexedDb();
|
|
5371
|
+
if (existing)
|
|
5372
|
+
return existing;
|
|
5373
|
+
const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
5374
|
+
await this.saveKeyToIndexedDb(key);
|
|
5375
|
+
return key;
|
|
5376
|
+
})();
|
|
5377
|
+
}
|
|
5378
|
+
return this.cryptoKeyPromise;
|
|
5379
|
+
}
|
|
5380
|
+
openKeyDb() {
|
|
5381
|
+
return new Promise((resolve, reject) => {
|
|
5382
|
+
const req = indexedDB.open('capacitor-auth-keys', 1);
|
|
5383
|
+
req.onupgradeneeded = () => req.result.createObjectStore('keys');
|
|
5384
|
+
req.onsuccess = () => resolve(req.result);
|
|
5385
|
+
req.onerror = () => reject(req.error);
|
|
5386
|
+
});
|
|
5387
|
+
}
|
|
5388
|
+
async loadKeyFromIndexedDb() {
|
|
5389
|
+
if (typeof indexedDB === 'undefined')
|
|
5390
|
+
return null;
|
|
5391
|
+
try {
|
|
5392
|
+
const db = await this.openKeyDb();
|
|
5393
|
+
return await new Promise((resolve) => {
|
|
5394
|
+
const tx = db.transaction('keys', 'readonly');
|
|
5395
|
+
const req = tx.objectStore('keys').get(this.storageKey);
|
|
5396
|
+
req.onsuccess = () => { var _a; return resolve((_a = req.result) !== null && _a !== void 0 ? _a : null); };
|
|
5397
|
+
req.onerror = () => resolve(null);
|
|
5398
|
+
});
|
|
5399
|
+
}
|
|
5400
|
+
catch (_a) {
|
|
5401
|
+
return null;
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
5404
|
+
async saveKeyToIndexedDb(key) {
|
|
5405
|
+
if (typeof indexedDB === 'undefined')
|
|
5406
|
+
return;
|
|
5407
|
+
try {
|
|
5408
|
+
const db = await this.openKeyDb();
|
|
5409
|
+
await new Promise((resolve) => {
|
|
5410
|
+
const tx = db.transaction('keys', 'readwrite');
|
|
5411
|
+
tx.objectStore('keys').put(key, this.storageKey);
|
|
5412
|
+
tx.oncomplete = () => resolve();
|
|
5413
|
+
tx.onerror = () => resolve();
|
|
5414
|
+
});
|
|
5415
|
+
}
|
|
5416
|
+
catch (_a) {
|
|
5417
|
+
// Best-effort: a fresh key is generated next time if persistence fails.
|
|
5418
|
+
}
|
|
4348
5419
|
}
|
|
4349
|
-
|
|
5420
|
+
/**
|
|
5421
|
+
* Encrypts with AES-GCM (Web Crypto). Falls back to base64 ONLY when Web Crypto / IndexedDB
|
|
5422
|
+
* are unavailable (insecure context); the `b64:`/`aes:` prefix tells decrypt() the format.
|
|
5423
|
+
*/
|
|
4350
5424
|
async encrypt(data) {
|
|
4351
|
-
|
|
4352
|
-
|
|
5425
|
+
if (typeof crypto === 'undefined' ||
|
|
5426
|
+
!crypto.subtle ||
|
|
5427
|
+
typeof indexedDB === 'undefined') {
|
|
5428
|
+
return `b64:${btoa(data)}`;
|
|
5429
|
+
}
|
|
5430
|
+
const key = await this.getEncryptionKey();
|
|
5431
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
5432
|
+
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(data));
|
|
5433
|
+
const packed = new Uint8Array(iv.length + ciphertext.byteLength);
|
|
5434
|
+
packed.set(iv, 0);
|
|
5435
|
+
packed.set(new Uint8Array(ciphertext), iv.length);
|
|
5436
|
+
let binary = '';
|
|
5437
|
+
for (let i = 0; i < packed.length; i++) {
|
|
5438
|
+
binary += String.fromCharCode(packed[i]);
|
|
5439
|
+
}
|
|
5440
|
+
return `aes:${btoa(binary)}`;
|
|
4353
5441
|
}
|
|
4354
5442
|
async decrypt(data) {
|
|
4355
|
-
|
|
4356
|
-
|
|
5443
|
+
if (data.startsWith('aes:')) {
|
|
5444
|
+
const key = await this.getEncryptionKey();
|
|
5445
|
+
const binary = atob(data.slice(4));
|
|
5446
|
+
const bytes = new Uint8Array(binary.length);
|
|
5447
|
+
for (let i = 0; i < binary.length; i++) {
|
|
5448
|
+
bytes[i] = binary.charCodeAt(i);
|
|
5449
|
+
}
|
|
5450
|
+
const iv = bytes.slice(0, 12);
|
|
5451
|
+
const ciphertext = bytes.slice(12);
|
|
5452
|
+
const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
|
|
5453
|
+
return new TextDecoder().decode(plaintext);
|
|
5454
|
+
}
|
|
5455
|
+
// Legacy (older versions) or insecure-context fallback: base64-encoded payload.
|
|
5456
|
+
const payload = data.startsWith('b64:') ? data.slice(4) : data;
|
|
5457
|
+
return atob(payload);
|
|
4357
5458
|
}
|
|
4358
5459
|
async initialize() {
|
|
4359
5460
|
// Biometric provider is initialized in constructor
|
|
@@ -4364,9 +5465,7 @@ class BiometricProvider {
|
|
|
4364
5465
|
const result = await this.isAvailable();
|
|
4365
5466
|
return result.available;
|
|
4366
5467
|
}
|
|
4367
|
-
|
|
4368
|
-
throw new AuthError('NOT_SUPPORTED', 'Account linking is not supported for biometric authentication');
|
|
4369
|
-
}
|
|
5468
|
+
// linkAccount inherits BaseAuthProvider's OPERATION_NOT_ALLOWED default (F-44).
|
|
4370
5469
|
async unlinkAccount(_options) {
|
|
4371
5470
|
// Unlinking biometric auth means clearing stored credentials
|
|
4372
5471
|
await this.clearStoredCredentials();
|
|
@@ -4402,9 +5501,9 @@ class SlackProvider extends OAuthProvider {
|
|
|
4402
5501
|
async signIn(options) {
|
|
4403
5502
|
return this.performOAuthFlow(options);
|
|
4404
5503
|
}
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
5504
|
+
// Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
|
|
5505
|
+
// Note: Slack's OAuth 2.0 for public web apps typically doesn't issue refresh tokens.
|
|
5506
|
+
// If no refresh token is available, the base class will throw "No refresh token available".
|
|
4408
5507
|
getOAuthConfig() {
|
|
4409
5508
|
return {
|
|
4410
5509
|
clientId: this.clientId,
|
|
@@ -4415,15 +5514,39 @@ class SlackProvider extends OAuthProvider {
|
|
|
4415
5514
|
additionalParams: this.teamId ? { team: this.teamId } : {},
|
|
4416
5515
|
};
|
|
4417
5516
|
}
|
|
4418
|
-
async parseUserFromTokenResponse(
|
|
4419
|
-
|
|
4420
|
-
|
|
5517
|
+
async parseUserFromTokenResponse(response) {
|
|
5518
|
+
var _a;
|
|
5519
|
+
const accessToken = response.access_token;
|
|
5520
|
+
if (!accessToken) {
|
|
5521
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Slack token response did not include an access token; cannot fetch the user profile.', this.provider);
|
|
5522
|
+
}
|
|
5523
|
+
// Fetch the real profile via Slack's OpenID Connect userInfo endpoint.
|
|
5524
|
+
// https://api.slack.com/methods/openid.connect.userInfo
|
|
5525
|
+
let res;
|
|
5526
|
+
try {
|
|
5527
|
+
res = await fetch('https://slack.com/api/openid.connect.userInfo', {
|
|
5528
|
+
method: 'GET',
|
|
5529
|
+
headers: {
|
|
5530
|
+
Authorization: `Bearer ${accessToken}`,
|
|
5531
|
+
Accept: 'application/json',
|
|
5532
|
+
},
|
|
5533
|
+
});
|
|
5534
|
+
}
|
|
5535
|
+
catch (error) {
|
|
5536
|
+
throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach Slack userInfo endpoint', this.provider, error);
|
|
5537
|
+
}
|
|
5538
|
+
// Slack returns HTTP 200 with `{ ok: false, error }` on API-level failures.
|
|
5539
|
+
const data = (await res.json().catch(() => null));
|
|
5540
|
+
if (!res.ok || !data || data.ok === false || !data.sub) {
|
|
5541
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, `Failed to fetch Slack user profile${(data === null || data === void 0 ? void 0 : data.error) ? `: ${data.error}` : ''}`, this.provider);
|
|
5542
|
+
}
|
|
4421
5543
|
return {
|
|
4422
|
-
id:
|
|
4423
|
-
|
|
4424
|
-
|
|
4425
|
-
|
|
4426
|
-
|
|
5544
|
+
id: data.sub,
|
|
5545
|
+
sub: data.sub,
|
|
5546
|
+
email: data.email,
|
|
5547
|
+
email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
|
|
5548
|
+
name: data.name,
|
|
5549
|
+
picture: data.picture,
|
|
4427
5550
|
isNewUser: false,
|
|
4428
5551
|
};
|
|
4429
5552
|
}
|
|
@@ -4469,10 +5592,10 @@ class SlackProvider extends OAuthProvider {
|
|
|
4469
5592
|
return true;
|
|
4470
5593
|
}
|
|
4471
5594
|
async linkAccount(_options) {
|
|
4472
|
-
throw new AuthError(
|
|
5595
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for Slack provider');
|
|
4473
5596
|
}
|
|
4474
5597
|
async unlinkAccount(_options) {
|
|
4475
|
-
throw new AuthError(
|
|
5598
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for Slack provider');
|
|
4476
5599
|
}
|
|
4477
5600
|
async revokeAccess(token) {
|
|
4478
5601
|
await super.revokeAccess(token);
|
|
@@ -4511,9 +5634,10 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4511
5634
|
await this.clearStoredData();
|
|
4512
5635
|
await this.setCurrentUser(null);
|
|
4513
5636
|
}
|
|
4514
|
-
|
|
4515
|
-
|
|
4516
|
-
|
|
5637
|
+
// Uses base OAuthProvider.refreshToken() which handles refresh tokens if available.
|
|
5638
|
+
// Note: LinkedIn's OAuth 2.0 issues long-lived access tokens (60 days) and typically
|
|
5639
|
+
// doesn't provide refresh tokens for web apps. If no refresh token is available,
|
|
5640
|
+
// the base class will throw "No refresh token available".
|
|
4517
5641
|
getOAuthConfig() {
|
|
4518
5642
|
return {
|
|
4519
5643
|
clientId: this.clientId,
|
|
@@ -4523,15 +5647,40 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4523
5647
|
scopes: this.scopes,
|
|
4524
5648
|
};
|
|
4525
5649
|
}
|
|
4526
|
-
async parseUserFromTokenResponse(
|
|
4527
|
-
|
|
4528
|
-
|
|
5650
|
+
async parseUserFromTokenResponse(response) {
|
|
5651
|
+
var _a;
|
|
5652
|
+
const accessToken = response.access_token;
|
|
5653
|
+
if (!accessToken) {
|
|
5654
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'LinkedIn token response did not include an access token; cannot fetch the user profile.', this.provider);
|
|
5655
|
+
}
|
|
5656
|
+
// Fetch the real profile via LinkedIn's OpenID Connect userinfo endpoint.
|
|
5657
|
+
// https://learn.microsoft.com/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2
|
|
5658
|
+
let res;
|
|
5659
|
+
try {
|
|
5660
|
+
res = await fetch('https://api.linkedin.com/v2/userinfo', {
|
|
5661
|
+
method: 'GET',
|
|
5662
|
+
headers: {
|
|
5663
|
+
Authorization: `Bearer ${accessToken}`,
|
|
5664
|
+
Accept: 'application/json',
|
|
5665
|
+
},
|
|
5666
|
+
});
|
|
5667
|
+
}
|
|
5668
|
+
catch (error) {
|
|
5669
|
+
throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to reach LinkedIn userinfo endpoint', this.provider, error);
|
|
5670
|
+
}
|
|
5671
|
+
const data = (await res
|
|
5672
|
+
.json()
|
|
5673
|
+
.catch(() => null));
|
|
5674
|
+
if (!res.ok || !data || !data.sub) {
|
|
5675
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Failed to fetch LinkedIn user profile', this.provider);
|
|
5676
|
+
}
|
|
4529
5677
|
return {
|
|
4530
|
-
id:
|
|
4531
|
-
|
|
4532
|
-
|
|
4533
|
-
|
|
4534
|
-
|
|
5678
|
+
id: data.sub,
|
|
5679
|
+
sub: data.sub,
|
|
5680
|
+
email: data.email,
|
|
5681
|
+
email_verified: (_a = data.email_verified) !== null && _a !== void 0 ? _a : false,
|
|
5682
|
+
name: data.name,
|
|
5683
|
+
picture: data.picture,
|
|
4535
5684
|
isNewUser: false,
|
|
4536
5685
|
};
|
|
4537
5686
|
}
|
|
@@ -4578,10 +5727,10 @@ class LinkedInProvider extends OAuthProvider {
|
|
|
4578
5727
|
return true;
|
|
4579
5728
|
}
|
|
4580
5729
|
async linkAccount(_options) {
|
|
4581
|
-
throw new AuthError(
|
|
5730
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account linking is not supported for LinkedIn provider');
|
|
4582
5731
|
}
|
|
4583
5732
|
async unlinkAccount(_options) {
|
|
4584
|
-
throw new AuthError(
|
|
5733
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Account unlinking is not supported for LinkedIn provider');
|
|
4585
5734
|
}
|
|
4586
5735
|
async revokeAccess(token) {
|
|
4587
5736
|
await super.revokeAccess(token);
|
|
@@ -4593,17 +5742,22 @@ var linkedinProvider = /*#__PURE__*/Object.freeze({
|
|
|
4593
5742
|
LinkedInProvider: LinkedInProvider
|
|
4594
5743
|
});
|
|
4595
5744
|
|
|
4596
|
-
class UsernamePasswordProvider {
|
|
4597
|
-
|
|
4598
|
-
|
|
4599
|
-
|
|
5745
|
+
class UsernamePasswordProvider extends BaseAuthProvider {
|
|
5746
|
+
get name() {
|
|
5747
|
+
return 'username-password';
|
|
5748
|
+
}
|
|
5749
|
+
constructor(input) {
|
|
5750
|
+
super(resolveProviderConfig(exports.AuthProvider.USERNAME_PASSWORD, input));
|
|
5751
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
5752
|
+
// so username/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
4600
5753
|
this.authToken = null;
|
|
4601
5754
|
this.refreshTokenValue = null;
|
|
5755
|
+
const config = this.options;
|
|
4602
5756
|
this.config = Object.assign({ allowSignUp: true, usernameRequirements: Object.assign({ minLength: 3, maxLength: 20, allowedCharacters: /^[a-zA-Z0-9_-]+$/, reservedUsernames: ['admin', 'root', 'system', 'user'] }, config.usernameRequirements), passwordRequirements: Object.assign({ minLength: 8, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSpecialChars: false }, config.passwordRequirements) }, config);
|
|
4603
5757
|
}
|
|
4604
5758
|
async signIn(options) {
|
|
4605
5759
|
if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
4606
|
-
throw new AuthError(
|
|
5760
|
+
throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
|
|
4607
5761
|
}
|
|
4608
5762
|
try {
|
|
4609
5763
|
const response = await fetch(`${this.config.apiUrl}/auth/signin`, {
|
|
@@ -4620,9 +5774,9 @@ class UsernamePasswordProvider {
|
|
|
4620
5774
|
if (!response.ok) {
|
|
4621
5775
|
const error = await response.json().catch(() => ({}));
|
|
4622
5776
|
if (response.status === 401) {
|
|
4623
|
-
throw new AuthError(
|
|
5777
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid username or password');
|
|
4624
5778
|
}
|
|
4625
|
-
throw new AuthError(
|
|
5779
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in');
|
|
4626
5780
|
}
|
|
4627
5781
|
const data = await response.json();
|
|
4628
5782
|
// Create user object
|
|
@@ -4670,29 +5824,29 @@ class UsernamePasswordProvider {
|
|
|
4670
5824
|
catch (error) {
|
|
4671
5825
|
if (error instanceof AuthError)
|
|
4672
5826
|
throw error;
|
|
4673
|
-
throw new AuthError(
|
|
5827
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Failed to sign in with username and password');
|
|
4674
5828
|
}
|
|
4675
5829
|
}
|
|
4676
5830
|
async signUp(options) {
|
|
4677
5831
|
if (!this.config.allowSignUp) {
|
|
4678
|
-
throw new AuthError(
|
|
5832
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_DISABLED, 'Sign up is not allowed');
|
|
4679
5833
|
}
|
|
4680
5834
|
if (!(options === null || options === void 0 ? void 0 : options.username) || !(options === null || options === void 0 ? void 0 : options.password)) {
|
|
4681
|
-
throw new AuthError(
|
|
5835
|
+
throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Username and password are required');
|
|
4682
5836
|
}
|
|
4683
5837
|
// Validate username
|
|
4684
5838
|
const usernameError = this.validateUsername(options.username);
|
|
4685
5839
|
if (usernameError) {
|
|
4686
|
-
throw new AuthError(
|
|
5840
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_USERNAME, usernameError);
|
|
4687
5841
|
}
|
|
4688
5842
|
// Validate password
|
|
4689
5843
|
const passwordError = this.validatePassword(options.password);
|
|
4690
5844
|
if (passwordError) {
|
|
4691
|
-
throw new AuthError(
|
|
5845
|
+
throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
4692
5846
|
}
|
|
4693
5847
|
// Validate email if provided
|
|
4694
5848
|
if (options.email && !this.isValidEmail(options.email)) {
|
|
4695
|
-
throw new AuthError(
|
|
5849
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Invalid email address');
|
|
4696
5850
|
}
|
|
4697
5851
|
try {
|
|
4698
5852
|
const response = await fetch(`${this.config.apiUrl}/auth/signup`, {
|
|
@@ -4712,9 +5866,9 @@ class UsernamePasswordProvider {
|
|
|
4712
5866
|
if (!response.ok) {
|
|
4713
5867
|
const error = await response.json().catch(() => ({}));
|
|
4714
5868
|
if (response.status === 409) {
|
|
4715
|
-
throw new AuthError(
|
|
5869
|
+
throw new AuthError(exports.AuthErrorCode.USERNAME_ALREADY_EXISTS, 'Username already taken');
|
|
4716
5870
|
}
|
|
4717
|
-
throw new AuthError(
|
|
5871
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
4718
5872
|
}
|
|
4719
5873
|
const data = await response.json();
|
|
4720
5874
|
// Create user object
|
|
@@ -4762,7 +5916,7 @@ class UsernamePasswordProvider {
|
|
|
4762
5916
|
catch (error) {
|
|
4763
5917
|
if (error instanceof AuthError)
|
|
4764
5918
|
throw error;
|
|
4765
|
-
throw new AuthError(
|
|
5919
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Failed to create account');
|
|
4766
5920
|
}
|
|
4767
5921
|
}
|
|
4768
5922
|
async signOut() {
|
|
@@ -4792,7 +5946,7 @@ class UsernamePasswordProvider {
|
|
|
4792
5946
|
}
|
|
4793
5947
|
async refreshToken(_options) {
|
|
4794
5948
|
if (!this.refreshTokenValue) {
|
|
4795
|
-
throw new AuthError(
|
|
5949
|
+
throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available');
|
|
4796
5950
|
}
|
|
4797
5951
|
try {
|
|
4798
5952
|
const response = await fetch(`${this.config.apiUrl}/auth/refresh`, {
|
|
@@ -4806,7 +5960,7 @@ class UsernamePasswordProvider {
|
|
|
4806
5960
|
}),
|
|
4807
5961
|
});
|
|
4808
5962
|
if (!response.ok) {
|
|
4809
|
-
throw new AuthError(
|
|
5963
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Failed to refresh token');
|
|
4810
5964
|
}
|
|
4811
5965
|
const data = await response.json();
|
|
4812
5966
|
// Update tokens
|
|
@@ -4814,150 +5968,777 @@ class UsernamePasswordProvider {
|
|
|
4814
5968
|
if (data.refreshToken) {
|
|
4815
5969
|
this.refreshTokenValue = data.refreshToken;
|
|
4816
5970
|
}
|
|
4817
|
-
return {
|
|
4818
|
-
user: this.currentUser,
|
|
4819
|
-
credential: {
|
|
4820
|
-
providerId: this.name,
|
|
4821
|
-
signInMethod: 'password',
|
|
4822
|
-
accessToken: data.accessToken,
|
|
4823
|
-
refreshToken: data.refreshToken,
|
|
4824
|
-
expiresAt: data.expiresAt,
|
|
4825
|
-
},
|
|
4826
|
-
};
|
|
5971
|
+
return {
|
|
5972
|
+
user: this.currentUser,
|
|
5973
|
+
credential: {
|
|
5974
|
+
providerId: this.name,
|
|
5975
|
+
signInMethod: 'password',
|
|
5976
|
+
accessToken: data.accessToken,
|
|
5977
|
+
refreshToken: data.refreshToken,
|
|
5978
|
+
expiresAt: data.expiresAt,
|
|
5979
|
+
},
|
|
5980
|
+
};
|
|
5981
|
+
}
|
|
5982
|
+
catch (error) {
|
|
5983
|
+
if (error instanceof AuthError)
|
|
5984
|
+
throw error;
|
|
5985
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Failed to refresh token');
|
|
5986
|
+
}
|
|
5987
|
+
}
|
|
5988
|
+
async updatePassword(currentPassword, newPassword) {
|
|
5989
|
+
if (!this.currentUser || !this.authToken) {
|
|
5990
|
+
throw new AuthError(exports.AuthErrorCode.NOT_AUTHENTICATED, 'User not authenticated');
|
|
5991
|
+
}
|
|
5992
|
+
// Validate new password
|
|
5993
|
+
const passwordError = this.validatePassword(newPassword);
|
|
5994
|
+
if (passwordError) {
|
|
5995
|
+
throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, passwordError);
|
|
5996
|
+
}
|
|
5997
|
+
try {
|
|
5998
|
+
const response = await fetch(`${this.config.apiUrl}/auth/update-password`, {
|
|
5999
|
+
method: 'POST',
|
|
6000
|
+
headers: {
|
|
6001
|
+
Authorization: `Bearer ${this.authToken}`,
|
|
6002
|
+
'Content-Type': 'application/json',
|
|
6003
|
+
},
|
|
6004
|
+
body: JSON.stringify({
|
|
6005
|
+
currentPassword,
|
|
6006
|
+
newPassword,
|
|
6007
|
+
clientId: this.config.clientId,
|
|
6008
|
+
}),
|
|
6009
|
+
});
|
|
6010
|
+
if (!response.ok) {
|
|
6011
|
+
const error = await response.json().catch(() => ({}));
|
|
6012
|
+
if (response.status === 401) {
|
|
6013
|
+
throw new AuthError(exports.AuthErrorCode.WRONG_PASSWORD, 'Current password is incorrect');
|
|
6014
|
+
}
|
|
6015
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
6016
|
+
}
|
|
6017
|
+
}
|
|
6018
|
+
catch (error) {
|
|
6019
|
+
if (error instanceof AuthError)
|
|
6020
|
+
throw error;
|
|
6021
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to update password');
|
|
6022
|
+
}
|
|
6023
|
+
}
|
|
6024
|
+
async checkUsernameAvailability(username) {
|
|
6025
|
+
// Validate username format first
|
|
6026
|
+
const usernameError = this.validateUsername(username);
|
|
6027
|
+
if (usernameError) {
|
|
6028
|
+
return false;
|
|
6029
|
+
}
|
|
6030
|
+
try {
|
|
6031
|
+
const response = await fetch(`${this.config.apiUrl}/auth/check-username`, {
|
|
6032
|
+
method: 'POST',
|
|
6033
|
+
headers: {
|
|
6034
|
+
'Content-Type': 'application/json',
|
|
6035
|
+
},
|
|
6036
|
+
body: JSON.stringify({
|
|
6037
|
+
username,
|
|
6038
|
+
clientId: this.config.clientId,
|
|
6039
|
+
}),
|
|
6040
|
+
});
|
|
6041
|
+
if (!response.ok) {
|
|
6042
|
+
return false;
|
|
6043
|
+
}
|
|
6044
|
+
const data = await response.json();
|
|
6045
|
+
return data.available || false;
|
|
6046
|
+
}
|
|
6047
|
+
catch (_a) {
|
|
6048
|
+
return false;
|
|
6049
|
+
}
|
|
6050
|
+
}
|
|
6051
|
+
isValidEmail(email) {
|
|
6052
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
6053
|
+
return emailRegex.test(email);
|
|
6054
|
+
}
|
|
6055
|
+
validateUsername(username) {
|
|
6056
|
+
const requirements = this.config.usernameRequirements;
|
|
6057
|
+
if (username.length < requirements.minLength) {
|
|
6058
|
+
return `Username must be at least ${requirements.minLength} characters long`;
|
|
6059
|
+
}
|
|
6060
|
+
if (username.length > requirements.maxLength) {
|
|
6061
|
+
return `Username must be no more than ${requirements.maxLength} characters long`;
|
|
6062
|
+
}
|
|
6063
|
+
if (requirements.allowedCharacters &&
|
|
6064
|
+
!requirements.allowedCharacters.test(username)) {
|
|
6065
|
+
return 'Username contains invalid characters. Only letters, numbers, underscores, and hyphens are allowed';
|
|
6066
|
+
}
|
|
6067
|
+
if (requirements.reservedUsernames &&
|
|
6068
|
+
requirements.reservedUsernames.includes(username.toLowerCase())) {
|
|
6069
|
+
return 'This username is reserved and cannot be used';
|
|
6070
|
+
}
|
|
6071
|
+
return null;
|
|
6072
|
+
}
|
|
6073
|
+
validatePassword(password) {
|
|
6074
|
+
const requirements = this.config.passwordRequirements;
|
|
6075
|
+
if (password.length < requirements.minLength) {
|
|
6076
|
+
return `Password must be at least ${requirements.minLength} characters long`;
|
|
6077
|
+
}
|
|
6078
|
+
if (requirements.requireUppercase && !/[A-Z]/.test(password)) {
|
|
6079
|
+
return 'Password must contain at least one uppercase letter';
|
|
6080
|
+
}
|
|
6081
|
+
if (requirements.requireLowercase && !/[a-z]/.test(password)) {
|
|
6082
|
+
return 'Password must contain at least one lowercase letter';
|
|
6083
|
+
}
|
|
6084
|
+
if (requirements.requireNumbers && !/\d/.test(password)) {
|
|
6085
|
+
return 'Password must contain at least one number';
|
|
6086
|
+
}
|
|
6087
|
+
if (requirements.requireSpecialChars &&
|
|
6088
|
+
!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
|
|
6089
|
+
return 'Password must contain at least one special character';
|
|
6090
|
+
}
|
|
6091
|
+
return null;
|
|
6092
|
+
}
|
|
6093
|
+
async initialize() {
|
|
6094
|
+
// Username/Password provider doesn't require initialization
|
|
6095
|
+
}
|
|
6096
|
+
async isSupported() {
|
|
6097
|
+
// Username/Password auth is supported if we have the required config
|
|
6098
|
+
return !!this.config.apiUrl;
|
|
6099
|
+
}
|
|
6100
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
6101
|
+
async revokeAccess(_token) {
|
|
6102
|
+
// For username/password auth, revoking access means signing out
|
|
6103
|
+
await this.signOut();
|
|
6104
|
+
}
|
|
6105
|
+
}
|
|
6106
|
+
|
|
6107
|
+
var usernamePasswordProvider = /*#__PURE__*/Object.freeze({
|
|
6108
|
+
__proto__: null,
|
|
6109
|
+
UsernamePasswordProvider: UsernamePasswordProvider
|
|
6110
|
+
});
|
|
6111
|
+
|
|
6112
|
+
class EmailCodeProvider extends BaseAuthProvider {
|
|
6113
|
+
get name() {
|
|
6114
|
+
return 'email-code';
|
|
6115
|
+
}
|
|
6116
|
+
constructor(input) {
|
|
6117
|
+
super(resolveProviderConfig(exports.AuthProvider.EMAIL_CODE, input));
|
|
6118
|
+
// Pending verifications are persisted (SSR-guarded localStorage) so they survive a reload /
|
|
6119
|
+
// page change between sending and verifying the code. Only non-secret metadata is stored —
|
|
6120
|
+
// never the verification code itself (see PendingVerificationStore + F-11).
|
|
6121
|
+
this.pendingVerifications = new PendingVerificationStore('email-code');
|
|
6122
|
+
this.MAX_ATTEMPTS = 3;
|
|
6123
|
+
this.config = Object.assign({ codeLength: 6, resendDelay: 60000, codeExpiration: 10 * 60 * 1000 }, this.options);
|
|
6124
|
+
}
|
|
6125
|
+
async signIn(options) {
|
|
6126
|
+
if (!(options === null || options === void 0 ? void 0 : options.email)) {
|
|
6127
|
+
throw new AuthError(exports.AuthErrorCode.EMAIL_REQUIRED, 'Email is required for email code authentication');
|
|
6128
|
+
}
|
|
6129
|
+
// Validate email format
|
|
6130
|
+
if (!this.isValidEmail(options.email)) {
|
|
6131
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_EMAIL, 'Please enter a valid email address');
|
|
6132
|
+
}
|
|
6133
|
+
// If code is provided, verify it
|
|
6134
|
+
if (options.code) {
|
|
6135
|
+
return this.verifyCode(options.email, options.code);
|
|
6136
|
+
}
|
|
6137
|
+
// Otherwise, send code
|
|
6138
|
+
return this.sendCode(options.email);
|
|
6139
|
+
}
|
|
6140
|
+
async sendCode(email) {
|
|
6141
|
+
try {
|
|
6142
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6143
|
+
// Check if we can resend
|
|
6144
|
+
const existing = this.pendingVerifications.get(normalizedEmail);
|
|
6145
|
+
if (existing && existing.lastResent) {
|
|
6146
|
+
const timeSinceLastResend = Date.now() - existing.lastResent;
|
|
6147
|
+
if (timeSinceLastResend < this.config.resendDelay) {
|
|
6148
|
+
const waitTime = Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000);
|
|
6149
|
+
throw new AuthError(exports.AuthErrorCode.RESEND_DELAY, `Please wait ${waitTime} seconds before requesting a new code`);
|
|
6150
|
+
}
|
|
6151
|
+
}
|
|
6152
|
+
// Send email code via backend
|
|
6153
|
+
const response = await fetch(this.config.sendCodeUrl, {
|
|
6154
|
+
method: 'POST',
|
|
6155
|
+
headers: {
|
|
6156
|
+
'Content-Type': 'application/json',
|
|
6157
|
+
},
|
|
6158
|
+
body: JSON.stringify({
|
|
6159
|
+
email: normalizedEmail,
|
|
6160
|
+
clientId: this.config.clientId,
|
|
6161
|
+
codeLength: this.config.codeLength,
|
|
6162
|
+
}),
|
|
6163
|
+
});
|
|
6164
|
+
if (!response.ok) {
|
|
6165
|
+
const error = await response.json().catch(() => ({}));
|
|
6166
|
+
throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6167
|
+
}
|
|
6168
|
+
const data = await response.json();
|
|
6169
|
+
// Store pending verification (persisted; metadata only, never the code).
|
|
6170
|
+
this.pendingVerifications.set(normalizedEmail, {
|
|
6171
|
+
identifier: normalizedEmail,
|
|
6172
|
+
sessionId: data.sessionId,
|
|
6173
|
+
expires: Date.now() + this.config.codeExpiration,
|
|
6174
|
+
attempts: 0,
|
|
6175
|
+
lastResent: Date.now(),
|
|
6176
|
+
});
|
|
6177
|
+
// Return partial auth result for pending state
|
|
6178
|
+
const tempUser = {
|
|
6179
|
+
uid: `email-code-pending:${data.sessionId}`,
|
|
6180
|
+
email: normalizedEmail,
|
|
6181
|
+
displayName: normalizedEmail.split('@')[0],
|
|
6182
|
+
photoURL: null,
|
|
6183
|
+
phoneNumber: null,
|
|
6184
|
+
emailVerified: false,
|
|
6185
|
+
providerData: [],
|
|
6186
|
+
metadata: {
|
|
6187
|
+
creationTime: new Date().toISOString(),
|
|
6188
|
+
lastSignInTime: new Date().toISOString(),
|
|
6189
|
+
},
|
|
6190
|
+
};
|
|
6191
|
+
return {
|
|
6192
|
+
user: tempUser,
|
|
6193
|
+
credential: {
|
|
6194
|
+
providerId: this.name,
|
|
6195
|
+
signInMethod: 'email-code',
|
|
6196
|
+
accessToken: data.sessionId,
|
|
6197
|
+
},
|
|
6198
|
+
additionalUserInfo: {
|
|
6199
|
+
isNewUser: false,
|
|
6200
|
+
providerId: this.name,
|
|
6201
|
+
profile: {
|
|
6202
|
+
email: normalizedEmail,
|
|
6203
|
+
sessionId: data.sessionId,
|
|
6204
|
+
message: `Verification code sent to ${this.maskEmail(normalizedEmail)}`,
|
|
6205
|
+
pending: true,
|
|
6206
|
+
},
|
|
6207
|
+
},
|
|
6208
|
+
};
|
|
6209
|
+
}
|
|
6210
|
+
catch (error) {
|
|
6211
|
+
if (error instanceof AuthError)
|
|
6212
|
+
throw error;
|
|
6213
|
+
throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6214
|
+
}
|
|
6215
|
+
}
|
|
6216
|
+
async verifyCode(email, code) {
|
|
6217
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6218
|
+
const pending = this.pendingVerifications.get(normalizedEmail);
|
|
6219
|
+
if (!pending) {
|
|
6220
|
+
throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending email verification found. Please request a new code.');
|
|
6221
|
+
}
|
|
6222
|
+
if (Date.now() > pending.expires) {
|
|
6223
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6224
|
+
throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
|
|
6225
|
+
}
|
|
6226
|
+
if (pending.attempts >= this.MAX_ATTEMPTS) {
|
|
6227
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6228
|
+
throw new AuthError(exports.AuthErrorCode.TOO_MANY_ATTEMPTS, 'Too many failed attempts. Please request a new code.');
|
|
6229
|
+
}
|
|
6230
|
+
try {
|
|
6231
|
+
// Increment attempts and persist the bump (so the count survives a reload mid-flow).
|
|
6232
|
+
pending.attempts++;
|
|
6233
|
+
this.pendingVerifications.set(normalizedEmail, pending);
|
|
6234
|
+
// Verify code with backend
|
|
6235
|
+
const response = await fetch(this.config.verifyCodeUrl, {
|
|
6236
|
+
method: 'POST',
|
|
6237
|
+
headers: {
|
|
6238
|
+
'Content-Type': 'application/json',
|
|
6239
|
+
},
|
|
6240
|
+
body: JSON.stringify({
|
|
6241
|
+
email: normalizedEmail,
|
|
6242
|
+
code,
|
|
6243
|
+
sessionId: pending.sessionId,
|
|
6244
|
+
clientId: this.config.clientId,
|
|
6245
|
+
}),
|
|
6246
|
+
});
|
|
6247
|
+
if (!response.ok) {
|
|
6248
|
+
const error = await response.json().catch(() => ({}));
|
|
6249
|
+
if (response.status === 401) {
|
|
6250
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid verification code');
|
|
6251
|
+
}
|
|
6252
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
|
|
6253
|
+
}
|
|
6254
|
+
const data = await response.json();
|
|
6255
|
+
// Create user from verified data
|
|
6256
|
+
const user = {
|
|
6257
|
+
uid: data.uid || this.generateUid(normalizedEmail),
|
|
6258
|
+
email: normalizedEmail,
|
|
6259
|
+
displayName: data.displayName || normalizedEmail.split('@')[0],
|
|
6260
|
+
photoURL: data.photoURL || null,
|
|
6261
|
+
phoneNumber: data.phoneNumber || null,
|
|
6262
|
+
emailVerified: true,
|
|
6263
|
+
providerData: [
|
|
6264
|
+
{
|
|
6265
|
+
providerId: this.name,
|
|
6266
|
+
uid: data.uid || normalizedEmail,
|
|
6267
|
+
displayName: data.displayName || normalizedEmail.split('@')[0],
|
|
6268
|
+
email: normalizedEmail,
|
|
6269
|
+
phoneNumber: null,
|
|
6270
|
+
photoURL: data.photoURL || null,
|
|
6271
|
+
},
|
|
6272
|
+
],
|
|
6273
|
+
metadata: {
|
|
6274
|
+
creationTime: data.createdAt || new Date().toISOString(),
|
|
6275
|
+
lastSignInTime: new Date().toISOString(),
|
|
6276
|
+
},
|
|
6277
|
+
};
|
|
6278
|
+
// Clean up pending verification
|
|
6279
|
+
this.pendingVerifications.delete(normalizedEmail);
|
|
6280
|
+
return {
|
|
6281
|
+
user,
|
|
6282
|
+
credential: {
|
|
6283
|
+
providerId: this.name,
|
|
6284
|
+
signInMethod: 'email-code',
|
|
6285
|
+
accessToken: data.accessToken,
|
|
6286
|
+
refreshToken: data.refreshToken,
|
|
6287
|
+
expiresAt: data.expiresAt,
|
|
6288
|
+
},
|
|
6289
|
+
additionalUserInfo: {
|
|
6290
|
+
isNewUser: data.isNewUser || false,
|
|
6291
|
+
providerId: this.name,
|
|
6292
|
+
},
|
|
6293
|
+
};
|
|
6294
|
+
}
|
|
6295
|
+
catch (error) {
|
|
6296
|
+
if (error instanceof AuthError)
|
|
6297
|
+
throw error;
|
|
6298
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Failed to verify code');
|
|
6299
|
+
}
|
|
6300
|
+
}
|
|
6301
|
+
async signOut() {
|
|
6302
|
+
this.pendingVerifications.clear();
|
|
6303
|
+
}
|
|
6304
|
+
async getCurrentUser() {
|
|
6305
|
+
return null;
|
|
6306
|
+
}
|
|
6307
|
+
async refreshToken(_options) {
|
|
6308
|
+
// Email code authentication is single-use and has no refresh flow; the user must request
|
|
6309
|
+
// a new verification code rather than refresh a token.
|
|
6310
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Email code authentication does not support token refresh; request a new code instead.');
|
|
6311
|
+
}
|
|
6312
|
+
async initialize() {
|
|
6313
|
+
// Email code provider doesn't require initialization
|
|
6314
|
+
}
|
|
6315
|
+
async isSupported() {
|
|
6316
|
+
return !!(this.config.sendCodeUrl && this.config.verifyCodeUrl);
|
|
6317
|
+
}
|
|
6318
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
6319
|
+
async revokeAccess(_token) {
|
|
6320
|
+
this.pendingVerifications.clear();
|
|
6321
|
+
}
|
|
6322
|
+
// Public method to resend code
|
|
6323
|
+
async resendCode(email) {
|
|
6324
|
+
return this.sendCode(email);
|
|
6325
|
+
}
|
|
6326
|
+
// Public method to check if can resend
|
|
6327
|
+
canResendCode(email) {
|
|
6328
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
6329
|
+
const pending = this.pendingVerifications.get(normalizedEmail);
|
|
6330
|
+
if (!pending || !pending.lastResent) {
|
|
6331
|
+
return { canResend: true };
|
|
6332
|
+
}
|
|
6333
|
+
const timeSinceLastResend = Date.now() - pending.lastResent;
|
|
6334
|
+
if (timeSinceLastResend < this.config.resendDelay) {
|
|
6335
|
+
return {
|
|
6336
|
+
canResend: false,
|
|
6337
|
+
waitTime: Math.ceil((this.config.resendDelay - timeSinceLastResend) / 1000),
|
|
6338
|
+
};
|
|
6339
|
+
}
|
|
6340
|
+
return { canResend: true };
|
|
6341
|
+
}
|
|
6342
|
+
isValidEmail(email) {
|
|
6343
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
6344
|
+
return emailRegex.test(email);
|
|
6345
|
+
}
|
|
6346
|
+
maskEmail(email) {
|
|
6347
|
+
const [local, domain] = email.split('@');
|
|
6348
|
+
if (local.length <= 2) {
|
|
6349
|
+
return `${local[0]}***@${domain}`;
|
|
6350
|
+
}
|
|
6351
|
+
return `${local[0]}***${local[local.length - 1]}@${domain}`;
|
|
6352
|
+
}
|
|
6353
|
+
generateUid(email) {
|
|
6354
|
+
return `email-code:${email.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
|
|
6355
|
+
}
|
|
6356
|
+
}
|
|
6357
|
+
|
|
6358
|
+
var emailCodeProvider = /*#__PURE__*/Object.freeze({
|
|
6359
|
+
__proto__: null,
|
|
6360
|
+
EmailCodeProvider: EmailCodeProvider
|
|
6361
|
+
});
|
|
6362
|
+
|
|
6363
|
+
class PhonePasswordProvider extends BaseAuthProvider {
|
|
6364
|
+
get name() {
|
|
6365
|
+
return 'phone-password';
|
|
6366
|
+
}
|
|
6367
|
+
constructor(input) {
|
|
6368
|
+
super(resolveProviderConfig(exports.AuthProvider.PHONE_PASSWORD, input));
|
|
6369
|
+
this.pendingVerifications = new Map();
|
|
6370
|
+
// currentUser is the inherited (in-memory) field from BaseAuthProvider; assigned directly here
|
|
6371
|
+
// so phone/password sessions stay in-memory exactly as before (no new storage persistence).
|
|
6372
|
+
this.storedAccessToken = null;
|
|
6373
|
+
this.storedRefreshToken = null;
|
|
6374
|
+
this.config = Object.assign({ countryCode: '+1', requirePhoneVerification: false, passwordStrength: {
|
|
6375
|
+
minLength: 8,
|
|
6376
|
+
requireUppercase: true,
|
|
6377
|
+
requireLowercase: true,
|
|
6378
|
+
requireNumbers: true,
|
|
6379
|
+
requireSpecialChars: false,
|
|
6380
|
+
} }, this.options);
|
|
6381
|
+
}
|
|
6382
|
+
async signIn(options) {
|
|
6383
|
+
const credentials = options === null || options === void 0 ? void 0 : options.credentials;
|
|
6384
|
+
if (!(credentials === null || credentials === void 0 ? void 0 : credentials.phoneNumber) || !(credentials === null || credentials === void 0 ? void 0 : credentials.password)) {
|
|
6385
|
+
throw new AuthError(exports.AuthErrorCode.CREDENTIALS_REQUIRED, 'Phone number and password are required');
|
|
6386
|
+
}
|
|
6387
|
+
const formattedPhone = this.formatPhoneNumber(credentials.phoneNumber);
|
|
6388
|
+
// Handle sign up flow
|
|
6389
|
+
if (options === null || options === void 0 ? void 0 : options.isSignUp) {
|
|
6390
|
+
return this.signUp(formattedPhone, credentials.password);
|
|
6391
|
+
}
|
|
6392
|
+
// Handle phone verification if code is provided
|
|
6393
|
+
if (credentials.code && this.config.requirePhoneVerification) {
|
|
6394
|
+
return this.verifyPhone(formattedPhone, credentials.code, credentials.password);
|
|
6395
|
+
}
|
|
6396
|
+
// Standard sign in
|
|
6397
|
+
return this.performSignIn(formattedPhone, credentials.password);
|
|
6398
|
+
}
|
|
6399
|
+
async performSignIn(phoneNumber, password) {
|
|
6400
|
+
try {
|
|
6401
|
+
const response = await fetch(this.config.signInUrl, {
|
|
6402
|
+
method: 'POST',
|
|
6403
|
+
headers: {
|
|
6404
|
+
'Content-Type': 'application/json',
|
|
6405
|
+
},
|
|
6406
|
+
body: JSON.stringify({
|
|
6407
|
+
phoneNumber,
|
|
6408
|
+
password,
|
|
6409
|
+
clientId: this.config.clientId,
|
|
6410
|
+
}),
|
|
6411
|
+
});
|
|
6412
|
+
if (!response.ok) {
|
|
6413
|
+
const error = await response.json().catch(() => ({}));
|
|
6414
|
+
if (response.status === 401) {
|
|
6415
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CREDENTIALS, 'Invalid phone number or password');
|
|
6416
|
+
}
|
|
6417
|
+
if (response.status === 403) {
|
|
6418
|
+
throw new AuthError(exports.AuthErrorCode.PHONE_NOT_VERIFIED, 'Please verify your phone number first');
|
|
6419
|
+
}
|
|
6420
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
|
|
6421
|
+
}
|
|
6422
|
+
const data = await response.json();
|
|
6423
|
+
return this.buildAuthResult(data, phoneNumber);
|
|
6424
|
+
}
|
|
6425
|
+
catch (error) {
|
|
6426
|
+
if (error instanceof AuthError)
|
|
6427
|
+
throw error;
|
|
6428
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, error.message || 'Sign in failed');
|
|
6429
|
+
}
|
|
6430
|
+
}
|
|
6431
|
+
async signUp(phoneNumber, password) {
|
|
6432
|
+
// Validate password strength
|
|
6433
|
+
this.validatePassword(password);
|
|
6434
|
+
try {
|
|
6435
|
+
const response = await fetch(this.config.signUpUrl, {
|
|
6436
|
+
method: 'POST',
|
|
6437
|
+
headers: {
|
|
6438
|
+
'Content-Type': 'application/json',
|
|
6439
|
+
},
|
|
6440
|
+
body: JSON.stringify({
|
|
6441
|
+
phoneNumber,
|
|
6442
|
+
password,
|
|
6443
|
+
clientId: this.config.clientId,
|
|
6444
|
+
}),
|
|
6445
|
+
});
|
|
6446
|
+
if (!response.ok) {
|
|
6447
|
+
const error = await response.json().catch(() => ({}));
|
|
6448
|
+
if (response.status === 409) {
|
|
6449
|
+
throw new AuthError(exports.AuthErrorCode.PHONE_NUMBER_ALREADY_EXISTS, 'An account with this phone number already exists');
|
|
6450
|
+
}
|
|
6451
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
|
|
6452
|
+
}
|
|
6453
|
+
const data = await response.json();
|
|
6454
|
+
// If phone verification is required, send verification code
|
|
6455
|
+
if (this.config.requirePhoneVerification && this.config.sendVerificationUrl) {
|
|
6456
|
+
await this.sendVerificationCode(phoneNumber);
|
|
6457
|
+
return {
|
|
6458
|
+
user: {
|
|
6459
|
+
uid: `phone-pending:${data.sessionId || phoneNumber}`,
|
|
6460
|
+
email: null,
|
|
6461
|
+
displayName: this.maskPhoneNumber(phoneNumber),
|
|
6462
|
+
photoURL: null,
|
|
6463
|
+
phoneNumber,
|
|
6464
|
+
emailVerified: false,
|
|
6465
|
+
providerData: [],
|
|
6466
|
+
metadata: {
|
|
6467
|
+
creationTime: new Date().toISOString(),
|
|
6468
|
+
lastSignInTime: new Date().toISOString(),
|
|
6469
|
+
},
|
|
6470
|
+
},
|
|
6471
|
+
credential: {
|
|
6472
|
+
providerId: this.name,
|
|
6473
|
+
signInMethod: 'phone-password',
|
|
6474
|
+
accessToken: data.sessionId,
|
|
6475
|
+
},
|
|
6476
|
+
additionalUserInfo: {
|
|
6477
|
+
isNewUser: true,
|
|
6478
|
+
providerId: this.name,
|
|
6479
|
+
profile: {
|
|
6480
|
+
phoneNumber,
|
|
6481
|
+
message: 'Phone verification required. Check your SMS.',
|
|
6482
|
+
pending: true,
|
|
6483
|
+
},
|
|
6484
|
+
},
|
|
6485
|
+
};
|
|
6486
|
+
}
|
|
6487
|
+
return this.buildAuthResult(data, phoneNumber, true);
|
|
4827
6488
|
}
|
|
4828
6489
|
catch (error) {
|
|
4829
6490
|
if (error instanceof AuthError)
|
|
4830
6491
|
throw error;
|
|
4831
|
-
throw new AuthError(
|
|
6492
|
+
throw new AuthError(exports.AuthErrorCode.SIGN_UP_FAILED, error.message || 'Sign up failed');
|
|
4832
6493
|
}
|
|
4833
6494
|
}
|
|
4834
|
-
async
|
|
4835
|
-
if (!this.
|
|
4836
|
-
throw new AuthError(
|
|
6495
|
+
async sendVerificationCode(phoneNumber) {
|
|
6496
|
+
if (!this.config.sendVerificationUrl) {
|
|
6497
|
+
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
|
|
4837
6498
|
}
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
6499
|
+
const response = await fetch(this.config.sendVerificationUrl, {
|
|
6500
|
+
method: 'POST',
|
|
6501
|
+
headers: {
|
|
6502
|
+
'Content-Type': 'application/json',
|
|
6503
|
+
},
|
|
6504
|
+
body: JSON.stringify({
|
|
6505
|
+
phoneNumber,
|
|
6506
|
+
clientId: this.config.clientId,
|
|
6507
|
+
}),
|
|
6508
|
+
});
|
|
6509
|
+
if (!response.ok) {
|
|
6510
|
+
const error = await response.json().catch(() => ({}));
|
|
6511
|
+
throw new AuthError(exports.AuthErrorCode.SEND_CODE_FAILED, error.message || 'Failed to send verification code');
|
|
6512
|
+
}
|
|
6513
|
+
const data = await response.json();
|
|
6514
|
+
this.pendingVerifications.set(phoneNumber, {
|
|
6515
|
+
phoneNumber,
|
|
6516
|
+
sessionId: data.sessionId,
|
|
6517
|
+
expires: Date.now() + 10 * 60 * 1000, // 10 minutes
|
|
6518
|
+
});
|
|
6519
|
+
}
|
|
6520
|
+
async verifyPhone(phoneNumber, code, password) {
|
|
6521
|
+
if (!this.config.verifyPhoneUrl) {
|
|
6522
|
+
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Phone verification URL not configured');
|
|
6523
|
+
}
|
|
6524
|
+
const pending = this.pendingVerifications.get(phoneNumber);
|
|
6525
|
+
if (!pending) {
|
|
6526
|
+
throw new AuthError(exports.AuthErrorCode.NO_PENDING_VERIFICATION, 'No pending phone verification found');
|
|
6527
|
+
}
|
|
6528
|
+
if (Date.now() > pending.expires) {
|
|
6529
|
+
this.pendingVerifications.delete(phoneNumber);
|
|
6530
|
+
throw new AuthError(exports.AuthErrorCode.CODE_EXPIRED, 'Verification code has expired');
|
|
4842
6531
|
}
|
|
4843
6532
|
try {
|
|
4844
|
-
const response = await fetch(
|
|
6533
|
+
const response = await fetch(this.config.verifyPhoneUrl, {
|
|
4845
6534
|
method: 'POST',
|
|
4846
6535
|
headers: {
|
|
4847
|
-
Authorization: `Bearer ${this.authToken}`,
|
|
4848
6536
|
'Content-Type': 'application/json',
|
|
4849
6537
|
},
|
|
4850
6538
|
body: JSON.stringify({
|
|
4851
|
-
|
|
4852
|
-
|
|
6539
|
+
phoneNumber,
|
|
6540
|
+
code,
|
|
6541
|
+
password,
|
|
6542
|
+
sessionId: pending.sessionId,
|
|
4853
6543
|
clientId: this.config.clientId,
|
|
4854
6544
|
}),
|
|
4855
6545
|
});
|
|
4856
6546
|
if (!response.ok) {
|
|
4857
6547
|
const error = await response.json().catch(() => ({}));
|
|
4858
6548
|
if (response.status === 401) {
|
|
4859
|
-
throw new AuthError(
|
|
6549
|
+
throw new AuthError(exports.AuthErrorCode.INVALID_CODE, 'Invalid verification code');
|
|
4860
6550
|
}
|
|
4861
|
-
throw new AuthError(
|
|
6551
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
|
|
4862
6552
|
}
|
|
6553
|
+
const data = await response.json();
|
|
6554
|
+
this.pendingVerifications.delete(phoneNumber);
|
|
6555
|
+
return this.buildAuthResult(data, phoneNumber);
|
|
4863
6556
|
}
|
|
4864
6557
|
catch (error) {
|
|
4865
6558
|
if (error instanceof AuthError)
|
|
4866
6559
|
throw error;
|
|
4867
|
-
throw new AuthError(
|
|
6560
|
+
throw new AuthError(exports.AuthErrorCode.VERIFICATION_FAILED, error.message || 'Phone verification failed');
|
|
4868
6561
|
}
|
|
4869
6562
|
}
|
|
4870
|
-
async
|
|
4871
|
-
|
|
4872
|
-
|
|
4873
|
-
|
|
4874
|
-
|
|
6563
|
+
async signOut() {
|
|
6564
|
+
this.currentUser = null;
|
|
6565
|
+
this.storedAccessToken = null;
|
|
6566
|
+
this.storedRefreshToken = null;
|
|
6567
|
+
this.pendingVerifications.clear();
|
|
6568
|
+
}
|
|
6569
|
+
async getCurrentUser() {
|
|
6570
|
+
return this.currentUser;
|
|
6571
|
+
}
|
|
6572
|
+
async refreshToken(_options) {
|
|
6573
|
+
if (!this.storedRefreshToken || !this.config.refreshTokenUrl) {
|
|
6574
|
+
throw new AuthError(exports.AuthErrorCode.NO_REFRESH_TOKEN, 'No refresh token available or refresh URL not configured');
|
|
4875
6575
|
}
|
|
4876
6576
|
try {
|
|
4877
|
-
const response = await fetch(
|
|
6577
|
+
const response = await fetch(this.config.refreshTokenUrl, {
|
|
4878
6578
|
method: 'POST',
|
|
4879
6579
|
headers: {
|
|
4880
6580
|
'Content-Type': 'application/json',
|
|
4881
6581
|
},
|
|
4882
6582
|
body: JSON.stringify({
|
|
4883
|
-
|
|
6583
|
+
refreshToken: this.storedRefreshToken,
|
|
4884
6584
|
clientId: this.config.clientId,
|
|
4885
6585
|
}),
|
|
4886
6586
|
});
|
|
4887
6587
|
if (!response.ok) {
|
|
4888
|
-
|
|
6588
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, 'Token refresh failed');
|
|
4889
6589
|
}
|
|
4890
6590
|
const data = await response.json();
|
|
4891
|
-
|
|
6591
|
+
this.storedAccessToken = data.accessToken;
|
|
6592
|
+
if (data.refreshToken) {
|
|
6593
|
+
this.storedRefreshToken = data.refreshToken;
|
|
6594
|
+
}
|
|
6595
|
+
if (!this.currentUser) {
|
|
6596
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No current user');
|
|
6597
|
+
}
|
|
6598
|
+
return {
|
|
6599
|
+
user: this.currentUser,
|
|
6600
|
+
credential: {
|
|
6601
|
+
providerId: this.name,
|
|
6602
|
+
signInMethod: 'phone-password',
|
|
6603
|
+
accessToken: data.accessToken,
|
|
6604
|
+
refreshToken: data.refreshToken || this.storedRefreshToken,
|
|
6605
|
+
expiresAt: data.expiresAt,
|
|
6606
|
+
},
|
|
6607
|
+
additionalUserInfo: {
|
|
6608
|
+
isNewUser: false,
|
|
6609
|
+
providerId: this.name,
|
|
6610
|
+
},
|
|
6611
|
+
};
|
|
4892
6612
|
}
|
|
4893
|
-
catch (
|
|
4894
|
-
|
|
6613
|
+
catch (error) {
|
|
6614
|
+
if (error instanceof AuthError)
|
|
6615
|
+
throw error;
|
|
6616
|
+
throw new AuthError(exports.AuthErrorCode.TOKEN_REFRESH_FAILED, error.message || 'Token refresh failed');
|
|
4895
6617
|
}
|
|
4896
6618
|
}
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
return emailRegex.test(email);
|
|
6619
|
+
async initialize() {
|
|
6620
|
+
// Phone password provider doesn't require initialization
|
|
4900
6621
|
}
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
6622
|
+
async isSupported() {
|
|
6623
|
+
return !!(this.config.signInUrl && this.config.signUpUrl);
|
|
6624
|
+
}
|
|
6625
|
+
// linkAccount + unlinkAccount inherit BaseAuthProvider's OPERATION_NOT_ALLOWED defaults (F-44).
|
|
6626
|
+
async revokeAccess(_token) {
|
|
6627
|
+
await this.signOut();
|
|
6628
|
+
}
|
|
6629
|
+
getAccessToken() {
|
|
6630
|
+
return this.storedAccessToken;
|
|
6631
|
+
}
|
|
6632
|
+
async sendPasswordReset(phoneNumber) {
|
|
6633
|
+
if (!this.config.resetPasswordUrl) {
|
|
6634
|
+
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Password reset URL not configured');
|
|
4912
6635
|
}
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
6636
|
+
const formattedPhone = this.formatPhoneNumber(phoneNumber);
|
|
6637
|
+
const response = await fetch(this.config.resetPasswordUrl, {
|
|
6638
|
+
method: 'POST',
|
|
6639
|
+
headers: {
|
|
6640
|
+
'Content-Type': 'application/json',
|
|
6641
|
+
},
|
|
6642
|
+
body: JSON.stringify({
|
|
6643
|
+
phoneNumber: formattedPhone,
|
|
6644
|
+
clientId: this.config.clientId,
|
|
6645
|
+
}),
|
|
6646
|
+
});
|
|
6647
|
+
if (!response.ok) {
|
|
6648
|
+
const error = await response.json().catch(() => ({}));
|
|
6649
|
+
throw new AuthError(exports.AuthErrorCode.SERVER_ERROR, error.message || 'Failed to send password reset');
|
|
4916
6650
|
}
|
|
4917
|
-
|
|
6651
|
+
}
|
|
6652
|
+
// Renamed from createAuthResult to avoid colliding with BaseAuthProvider.createAuthResult,
|
|
6653
|
+
// which has a different signature (this builds a phone-specific result from a backend payload).
|
|
6654
|
+
buildAuthResult(data, phoneNumber, isNewUser = false) {
|
|
6655
|
+
const user = {
|
|
6656
|
+
uid: data.uid || this.generateUid(phoneNumber),
|
|
6657
|
+
email: data.email || null,
|
|
6658
|
+
displayName: data.displayName || phoneNumber,
|
|
6659
|
+
photoURL: data.photoURL || null,
|
|
6660
|
+
phoneNumber,
|
|
6661
|
+
emailVerified: false,
|
|
6662
|
+
providerData: [
|
|
6663
|
+
{
|
|
6664
|
+
providerId: this.name,
|
|
6665
|
+
uid: data.uid || phoneNumber,
|
|
6666
|
+
displayName: data.displayName || phoneNumber,
|
|
6667
|
+
email: data.email || null,
|
|
6668
|
+
phoneNumber,
|
|
6669
|
+
photoURL: data.photoURL || null,
|
|
6670
|
+
},
|
|
6671
|
+
],
|
|
6672
|
+
metadata: {
|
|
6673
|
+
creationTime: data.createdAt || new Date().toISOString(),
|
|
6674
|
+
lastSignInTime: new Date().toISOString(),
|
|
6675
|
+
},
|
|
6676
|
+
};
|
|
6677
|
+
this.currentUser = user;
|
|
6678
|
+
this.storedAccessToken = data.accessToken;
|
|
6679
|
+
this.storedRefreshToken = data.refreshToken;
|
|
6680
|
+
return {
|
|
6681
|
+
user,
|
|
6682
|
+
credential: {
|
|
6683
|
+
providerId: this.name,
|
|
6684
|
+
signInMethod: 'phone-password',
|
|
6685
|
+
accessToken: data.accessToken,
|
|
6686
|
+
refreshToken: data.refreshToken,
|
|
6687
|
+
expiresAt: data.expiresAt,
|
|
6688
|
+
},
|
|
6689
|
+
additionalUserInfo: {
|
|
6690
|
+
isNewUser: data.isNewUser || isNewUser,
|
|
6691
|
+
providerId: this.name,
|
|
6692
|
+
},
|
|
6693
|
+
};
|
|
4918
6694
|
}
|
|
4919
6695
|
validatePassword(password) {
|
|
4920
|
-
const
|
|
4921
|
-
if (
|
|
4922
|
-
return
|
|
6696
|
+
const { passwordStrength } = this.config;
|
|
6697
|
+
if (!passwordStrength)
|
|
6698
|
+
return;
|
|
6699
|
+
const errors = [];
|
|
6700
|
+
if (passwordStrength.minLength && password.length < passwordStrength.minLength) {
|
|
6701
|
+
errors.push(`at least ${passwordStrength.minLength} characters`);
|
|
4923
6702
|
}
|
|
4924
|
-
if (
|
|
4925
|
-
|
|
6703
|
+
if (passwordStrength.requireUppercase && !/[A-Z]/.test(password)) {
|
|
6704
|
+
errors.push('an uppercase letter');
|
|
4926
6705
|
}
|
|
4927
|
-
if (
|
|
4928
|
-
|
|
6706
|
+
if (passwordStrength.requireLowercase && !/[a-z]/.test(password)) {
|
|
6707
|
+
errors.push('a lowercase letter');
|
|
4929
6708
|
}
|
|
4930
|
-
if (
|
|
4931
|
-
|
|
6709
|
+
if (passwordStrength.requireNumbers && !/\d/.test(password)) {
|
|
6710
|
+
errors.push('a number');
|
|
4932
6711
|
}
|
|
4933
|
-
if (
|
|
4934
|
-
|
|
4935
|
-
|
|
6712
|
+
if (passwordStrength.requireSpecialChars && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
|
|
6713
|
+
errors.push('a special character');
|
|
6714
|
+
}
|
|
6715
|
+
if (errors.length > 0) {
|
|
6716
|
+
throw new AuthError(exports.AuthErrorCode.WEAK_PASSWORD, `Password must contain ${errors.join(', ')}`);
|
|
4936
6717
|
}
|
|
4937
|
-
return null;
|
|
4938
|
-
}
|
|
4939
|
-
async initialize() {
|
|
4940
|
-
// Username/Password provider doesn't require initialization
|
|
4941
|
-
}
|
|
4942
|
-
async isSupported() {
|
|
4943
|
-
// Username/Password auth is supported if we have the required config
|
|
4944
|
-
return !!this.config.apiUrl;
|
|
4945
6718
|
}
|
|
4946
|
-
|
|
4947
|
-
|
|
6719
|
+
formatPhoneNumber(phoneNumber) {
|
|
6720
|
+
let cleaned = phoneNumber.replace(/\D/g, '');
|
|
6721
|
+
if (!phoneNumber.startsWith('+')) {
|
|
6722
|
+
if (cleaned.length === 10) {
|
|
6723
|
+
cleaned = '1' + cleaned;
|
|
6724
|
+
}
|
|
6725
|
+
cleaned = this.config.countryCode.replace('+', '') + cleaned;
|
|
6726
|
+
}
|
|
6727
|
+
return '+' + cleaned;
|
|
4948
6728
|
}
|
|
4949
|
-
|
|
4950
|
-
|
|
6729
|
+
maskPhoneNumber(phoneNumber) {
|
|
6730
|
+
const digits = phoneNumber.replace(/\D/g, '');
|
|
6731
|
+
const lastFour = digits.slice(-4);
|
|
6732
|
+
return `***-***-${lastFour}`;
|
|
4951
6733
|
}
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
await this.signOut();
|
|
6734
|
+
generateUid(phoneNumber) {
|
|
6735
|
+
return `phone-password:${phoneNumber.replace(/\D/g, '')}`;
|
|
4955
6736
|
}
|
|
4956
6737
|
}
|
|
4957
6738
|
|
|
4958
|
-
var
|
|
6739
|
+
var phonePasswordProvider = /*#__PURE__*/Object.freeze({
|
|
4959
6740
|
__proto__: null,
|
|
4960
|
-
|
|
6741
|
+
PhonePasswordProvider: PhonePasswordProvider
|
|
4961
6742
|
});
|
|
4962
6743
|
|
|
4963
6744
|
class ProviderFactory {
|
|
@@ -4975,57 +6756,32 @@ class ProviderFactory {
|
|
|
4975
6756
|
case exports.AuthProvider.APPLE:
|
|
4976
6757
|
return new AppleAuthProviderWeb(providerConfig);
|
|
4977
6758
|
case exports.AuthProvider.MICROSOFT:
|
|
4978
|
-
|
|
4979
|
-
logger.warn('Microsoft provider not yet implemented');
|
|
4980
|
-
return null;
|
|
6759
|
+
return new MicrosoftAuthProviderWeb(providerConfig);
|
|
4981
6760
|
case exports.AuthProvider.FACEBOOK:
|
|
4982
|
-
|
|
4983
|
-
logger.warn('Facebook provider not yet implemented');
|
|
4984
|
-
return null;
|
|
6761
|
+
return new FacebookAuthProviderWeb(providerConfig);
|
|
4985
6762
|
case exports.AuthProvider.GITHUB:
|
|
4986
|
-
|
|
4987
|
-
logger.warn('GitHub provider not yet implemented');
|
|
4988
|
-
return null;
|
|
6763
|
+
return new GitHubAuthProviderWeb(providerConfig);
|
|
4989
6764
|
case exports.AuthProvider.SLACK:
|
|
4990
|
-
|
|
4991
|
-
logger.warn('Slack provider not yet implemented');
|
|
4992
|
-
return null;
|
|
6765
|
+
return new SlackProvider(providerConfig);
|
|
4993
6766
|
case exports.AuthProvider.LINKEDIN:
|
|
4994
|
-
|
|
4995
|
-
logger.warn('LinkedIn provider not yet implemented');
|
|
4996
|
-
return null;
|
|
6767
|
+
return new LinkedInProvider(providerConfig);
|
|
4997
6768
|
case exports.AuthProvider.FIREBASE:
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
return null;
|
|
6769
|
+
return new FirebaseAuthProviderWeb(providerConfig);
|
|
6770
|
+
// Standalone providers with their own config types
|
|
5001
6771
|
case exports.AuthProvider.EMAIL_MAGIC_LINK:
|
|
5002
|
-
|
|
5003
|
-
logger.warn('Email Magic Link provider not yet implemented');
|
|
5004
|
-
return null;
|
|
6772
|
+
return new MagicLinkProvider(config.options);
|
|
5005
6773
|
case exports.AuthProvider.SMS:
|
|
5006
|
-
|
|
5007
|
-
logger.warn('SMS provider not yet implemented');
|
|
5008
|
-
return null;
|
|
6774
|
+
return new SMSProvider(config.options);
|
|
5009
6775
|
case exports.AuthProvider.EMAIL_PASSWORD:
|
|
5010
|
-
|
|
5011
|
-
logger.warn('Email/Password provider not yet implemented');
|
|
5012
|
-
return null;
|
|
5013
|
-
case exports.AuthProvider.PHONE_PASSWORD:
|
|
5014
|
-
// TODO: Implement Phone/Password provider
|
|
5015
|
-
logger.warn('Phone/Password provider not yet implemented');
|
|
5016
|
-
return null;
|
|
6776
|
+
return new EmailPasswordProvider(config.options);
|
|
5017
6777
|
case exports.AuthProvider.USERNAME_PASSWORD:
|
|
5018
|
-
|
|
5019
|
-
logger.warn('Username/Password provider not yet implemented');
|
|
5020
|
-
return null;
|
|
5021
|
-
case exports.AuthProvider.EMAIL_CODE:
|
|
5022
|
-
// TODO: Implement Email Code provider
|
|
5023
|
-
logger.warn('Email Code provider not yet implemented');
|
|
5024
|
-
return null;
|
|
6778
|
+
return new UsernamePasswordProvider(config.options);
|
|
5025
6779
|
case exports.AuthProvider.BIOMETRIC:
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
return
|
|
6780
|
+
return new BiometricProvider(config.options);
|
|
6781
|
+
case exports.AuthProvider.PHONE_PASSWORD:
|
|
6782
|
+
return new PhonePasswordProvider(config.options);
|
|
6783
|
+
case exports.AuthProvider.EMAIL_CODE:
|
|
6784
|
+
return new EmailCodeProvider(config.options);
|
|
5029
6785
|
default:
|
|
5030
6786
|
logger.error(`Unknown provider: ${config.provider}`);
|
|
5031
6787
|
return null;
|
|
@@ -5089,6 +6845,7 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5089
6845
|
}
|
|
5090
6846
|
}
|
|
5091
6847
|
async signIn(options) {
|
|
6848
|
+
var _a;
|
|
5092
6849
|
this.validateInitialized();
|
|
5093
6850
|
const provider = this.getProvider(options.provider);
|
|
5094
6851
|
try {
|
|
@@ -5098,7 +6855,7 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5098
6855
|
this.currentProvider = options.provider;
|
|
5099
6856
|
await this.storage.set('last_auth_provider', options.provider);
|
|
5100
6857
|
// Setup token refresh if needed
|
|
5101
|
-
if (this.autoRefreshToken && result.credential.refreshToken) {
|
|
6858
|
+
if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
|
|
5102
6859
|
this.setupTokenRefresh(options.provider, result.credential);
|
|
5103
6860
|
}
|
|
5104
6861
|
// Forward auth state change
|
|
@@ -5124,8 +6881,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5124
6881
|
// Sign out from current provider
|
|
5125
6882
|
const provider = this.getProvider(this.currentProvider);
|
|
5126
6883
|
await provider.signOut(options);
|
|
5127
|
-
//
|
|
5128
|
-
|
|
6884
|
+
// Untargeted sign-out: clear ALL refresh timers, not just the current provider's, so
|
|
6885
|
+
// no orphaned timers remain for previously-active providers (F-18).
|
|
6886
|
+
this.cancelAllTokenRefresh();
|
|
5129
6887
|
// Clear current provider
|
|
5130
6888
|
this.currentProvider = null;
|
|
5131
6889
|
await this.storage.remove('last_auth_provider');
|
|
@@ -5141,6 +6899,8 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5141
6899
|
this.logger.error(`Failed to sign out from ${providerId}`, error);
|
|
5142
6900
|
}
|
|
5143
6901
|
}
|
|
6902
|
+
// Defensive: clear any remaining timers (e.g. for providers that errored above).
|
|
6903
|
+
this.cancelAllTokenRefresh();
|
|
5144
6904
|
this.currentProvider = null;
|
|
5145
6905
|
await this.storage.remove('last_auth_provider');
|
|
5146
6906
|
}
|
|
@@ -5158,26 +6918,39 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5158
6918
|
const provider = this.getProvider(this.currentProvider);
|
|
5159
6919
|
return provider.getCurrentUser();
|
|
5160
6920
|
}
|
|
5161
|
-
// Try to get user from any provider
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
6921
|
+
// Try to get user from any provider. A not-yet-initialized provider can throw from
|
|
6922
|
+
// getCurrentUser() (it lazily initializes), so isolate each and skip failures.
|
|
6923
|
+
for (const [providerId, provider] of this.providers.entries()) {
|
|
6924
|
+
try {
|
|
6925
|
+
const user = await provider.getCurrentUser();
|
|
6926
|
+
if (user) {
|
|
6927
|
+
// Remember which provider owns the active session for subsequent calls.
|
|
6928
|
+
this.currentProvider = providerId;
|
|
6929
|
+
return user;
|
|
6930
|
+
}
|
|
6931
|
+
}
|
|
6932
|
+
catch (error) {
|
|
6933
|
+
this.logger.debug(`getCurrentUser: provider ${providerId} threw; skipping`, error);
|
|
6934
|
+
continue;
|
|
5166
6935
|
}
|
|
5167
6936
|
}
|
|
5168
6937
|
return null;
|
|
5169
6938
|
}
|
|
5170
6939
|
async refreshToken(options) {
|
|
6940
|
+
var _a;
|
|
5171
6941
|
this.validateInitialized();
|
|
5172
6942
|
const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
|
|
5173
6943
|
if (!providerId) {
|
|
5174
6944
|
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for token refresh');
|
|
5175
6945
|
}
|
|
5176
6946
|
const provider = this.getProvider(providerId);
|
|
6947
|
+
if (!provider.refreshToken) {
|
|
6948
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Token refresh not supported for provider ${providerId}`);
|
|
6949
|
+
}
|
|
5177
6950
|
try {
|
|
5178
6951
|
const result = await provider.refreshToken(options);
|
|
5179
6952
|
// Setup new token refresh
|
|
5180
|
-
if (this.autoRefreshToken && result.credential.refreshToken) {
|
|
6953
|
+
if (this.autoRefreshToken && ((_a = result.credential) === null || _a === void 0 ? void 0 : _a.refreshToken)) {
|
|
5181
6954
|
this.setupTokenRefresh(providerId, result.credential);
|
|
5182
6955
|
}
|
|
5183
6956
|
return result;
|
|
@@ -5201,10 +6974,11 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5201
6974
|
return handle;
|
|
5202
6975
|
}
|
|
5203
6976
|
async removeAllListeners() {
|
|
6977
|
+
var _a;
|
|
5204
6978
|
this.authStateEmitter.clear();
|
|
5205
6979
|
// Also clear provider listeners
|
|
5206
6980
|
for (const provider of this.providers.values()) {
|
|
5207
|
-
provider.dispose();
|
|
6981
|
+
(_a = provider.dispose) === null || _a === void 0 ? void 0 : _a.call(provider);
|
|
5208
6982
|
}
|
|
5209
6983
|
}
|
|
5210
6984
|
async isSupported(options) {
|
|
@@ -5245,6 +7019,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5245
7019
|
async linkAccount(options) {
|
|
5246
7020
|
this.validateInitialized();
|
|
5247
7021
|
const provider = this.getProvider(options.provider);
|
|
7022
|
+
if (!provider.linkAccount) {
|
|
7023
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking not supported for provider ${options.provider}`);
|
|
7024
|
+
}
|
|
5248
7025
|
try {
|
|
5249
7026
|
return await provider.linkAccount(options);
|
|
5250
7027
|
}
|
|
@@ -5256,6 +7033,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5256
7033
|
async unlinkAccount(options) {
|
|
5257
7034
|
this.validateInitialized();
|
|
5258
7035
|
const provider = this.getProvider(options.provider);
|
|
7036
|
+
if (!provider.unlinkAccount) {
|
|
7037
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking not supported for provider ${options.provider}`);
|
|
7038
|
+
}
|
|
5259
7039
|
try {
|
|
5260
7040
|
await provider.unlinkAccount(options);
|
|
5261
7041
|
}
|
|
@@ -5264,65 +7044,203 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5264
7044
|
throw AuthError.fromError(error, options.provider);
|
|
5265
7045
|
}
|
|
5266
7046
|
}
|
|
5267
|
-
async sendPasswordResetEmail(
|
|
7047
|
+
async sendPasswordResetEmail(options) {
|
|
5268
7048
|
this.validateInitialized();
|
|
5269
|
-
//
|
|
5270
|
-
|
|
7049
|
+
// Try email-password provider first
|
|
7050
|
+
const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
|
|
7051
|
+
if (emailPasswordProvider && 'sendPasswordReset' in emailPasswordProvider) {
|
|
7052
|
+
const provider = emailPasswordProvider;
|
|
7053
|
+
await provider.sendPasswordReset(options.email);
|
|
7054
|
+
return;
|
|
7055
|
+
}
|
|
7056
|
+
// Try phone-password provider
|
|
7057
|
+
const phonePasswordProvider = this.providers.get(exports.AuthProvider.PHONE_PASSWORD);
|
|
7058
|
+
if (phonePasswordProvider && 'sendPasswordReset' in phonePasswordProvider) {
|
|
7059
|
+
const provider = phonePasswordProvider;
|
|
7060
|
+
await provider.sendPasswordReset(options.email);
|
|
7061
|
+
return;
|
|
7062
|
+
}
|
|
7063
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Password reset requires email-password or phone-password provider to be configured');
|
|
5271
7064
|
}
|
|
5272
7065
|
async sendEmailVerification(_options) {
|
|
5273
7066
|
this.validateInitialized();
|
|
5274
|
-
//
|
|
5275
|
-
|
|
7067
|
+
// Email verification is typically handled by email-password provider
|
|
7068
|
+
const emailPasswordProvider = this.providers.get(exports.AuthProvider.EMAIL_PASSWORD);
|
|
7069
|
+
if (emailPasswordProvider && 'sendEmailVerification' in emailPasswordProvider) {
|
|
7070
|
+
const provider = emailPasswordProvider;
|
|
7071
|
+
await provider.sendEmailVerification();
|
|
7072
|
+
return;
|
|
7073
|
+
}
|
|
7074
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email verification requires email-password provider to be configured');
|
|
5276
7075
|
}
|
|
5277
|
-
async sendSmsCode(
|
|
7076
|
+
async sendSmsCode(options) {
|
|
5278
7077
|
this.validateInitialized();
|
|
5279
|
-
//
|
|
5280
|
-
|
|
7078
|
+
// Delegate to SMS provider
|
|
7079
|
+
const smsProvider = this.providers.get(exports.AuthProvider.SMS);
|
|
7080
|
+
if (smsProvider && 'sendCode' in smsProvider) {
|
|
7081
|
+
const provider = smsProvider;
|
|
7082
|
+
await provider.sendCode(options.phoneNumber);
|
|
7083
|
+
return;
|
|
7084
|
+
}
|
|
7085
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
|
|
5281
7086
|
}
|
|
5282
|
-
async verifySmsCode(
|
|
7087
|
+
async verifySmsCode(options) {
|
|
5283
7088
|
this.validateInitialized();
|
|
5284
|
-
//
|
|
5285
|
-
|
|
7089
|
+
// Delegate to SMS provider
|
|
7090
|
+
const smsProvider = this.providers.get(exports.AuthProvider.SMS);
|
|
7091
|
+
if (smsProvider && 'verifyCode' in smsProvider) {
|
|
7092
|
+
const provider = smsProvider;
|
|
7093
|
+
return await provider.verifyCode(options.phoneNumber, options.code);
|
|
7094
|
+
}
|
|
7095
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'SMS authentication requires SMS provider to be configured');
|
|
5286
7096
|
}
|
|
5287
|
-
async sendEmailCode(
|
|
7097
|
+
async sendEmailCode(options) {
|
|
5288
7098
|
this.validateInitialized();
|
|
5289
|
-
//
|
|
5290
|
-
|
|
7099
|
+
// Delegate to email-code provider
|
|
7100
|
+
const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
|
|
7101
|
+
if (emailCodeProvider) {
|
|
7102
|
+
// The email-code provider's signIn accepts { email } to send the code
|
|
7103
|
+
await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email } });
|
|
7104
|
+
return;
|
|
7105
|
+
}
|
|
7106
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
|
|
5291
7107
|
}
|
|
5292
|
-
async verifyEmailCode(
|
|
7108
|
+
async verifyEmailCode(options) {
|
|
5293
7109
|
this.validateInitialized();
|
|
5294
|
-
//
|
|
5295
|
-
|
|
7110
|
+
// Delegate to email-code provider
|
|
7111
|
+
const emailCodeProvider = this.providers.get(exports.AuthProvider.EMAIL_CODE);
|
|
7112
|
+
if (emailCodeProvider) {
|
|
7113
|
+
// The email-code provider's signIn accepts { email, code } to verify
|
|
7114
|
+
return await emailCodeProvider.signIn({ provider: exports.AuthProvider.EMAIL_CODE, credentials: { email: options.email, code: options.code } });
|
|
7115
|
+
}
|
|
7116
|
+
throw new AuthError(exports.AuthErrorCode.UNSUPPORTED_PROVIDER, 'Email code authentication requires email-code provider to be configured');
|
|
5296
7117
|
}
|
|
5297
|
-
async updateProfile(
|
|
7118
|
+
async updateProfile(options) {
|
|
5298
7119
|
this.validateInitialized();
|
|
5299
7120
|
if (!this.currentProvider) {
|
|
5300
|
-
throw new AuthError(exports.AuthErrorCode.
|
|
7121
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
|
|
7122
|
+
}
|
|
7123
|
+
const provider = this.providers.get(this.currentProvider);
|
|
7124
|
+
if (!provider) {
|
|
7125
|
+
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Current provider not found');
|
|
7126
|
+
}
|
|
7127
|
+
// Check if provider supports updateProfile
|
|
7128
|
+
if ('updateProfile' in provider && typeof provider.updateProfile === 'function') {
|
|
7129
|
+
const updateFn = provider.updateProfile;
|
|
7130
|
+
return await updateFn(options);
|
|
7131
|
+
}
|
|
7132
|
+
// Fallback: update cached user info locally
|
|
7133
|
+
const currentUser = await this.getCurrentUser();
|
|
7134
|
+
if (!currentUser) {
|
|
7135
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to update');
|
|
7136
|
+
}
|
|
7137
|
+
// Update local user data
|
|
7138
|
+
const updatedUser = Object.assign(Object.assign({}, currentUser), { displayName: options.displayName !== undefined ? options.displayName : currentUser.displayName, photoURL: options.photoURL !== undefined ? options.photoURL : currentUser.photoURL, phoneNumber: options.phoneNumber !== undefined ? options.phoneNumber : currentUser.phoneNumber });
|
|
7139
|
+
// Persist the updated user so it survives a reload — providers that extend BaseAuthProvider
|
|
7140
|
+
// read the cached user from `${provider}_current_user` on init (F-36). Without this the
|
|
7141
|
+
// fallback only emitted the change in-memory and it reverted on the next page load.
|
|
7142
|
+
await this.persistFallbackUser(updatedUser);
|
|
7143
|
+
this.authStateEmitter.emit(updatedUser);
|
|
7144
|
+
return updatedUser;
|
|
7145
|
+
}
|
|
7146
|
+
/**
|
|
7147
|
+
* Writes an updated user back to storage under the same key BaseAuthProvider uses
|
|
7148
|
+
* (`${provider}_current_user`) for the active provider, so the local profile change survives a
|
|
7149
|
+
* reload even when the provider has no native `updateProfile`. Best-effort: storage failures are
|
|
7150
|
+
* logged, not thrown, since the in-memory update already succeeded.
|
|
7151
|
+
*/
|
|
7152
|
+
async persistFallbackUser(user) {
|
|
7153
|
+
if (!this.currentProvider) {
|
|
7154
|
+
return;
|
|
7155
|
+
}
|
|
7156
|
+
try {
|
|
7157
|
+
await this.storage.set(`${this.currentProvider}_current_user`, user);
|
|
7158
|
+
}
|
|
7159
|
+
catch (error) {
|
|
7160
|
+
this.logger.error(`Failed to persist updated profile for ${this.currentProvider}`, error);
|
|
5301
7161
|
}
|
|
5302
|
-
// This would typically be implemented by specific providers
|
|
5303
|
-
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Profile update not implemented for current provider');
|
|
5304
7162
|
}
|
|
5305
|
-
async deleteAccount(
|
|
7163
|
+
async deleteAccount(options) {
|
|
5306
7164
|
this.validateInitialized();
|
|
5307
|
-
|
|
5308
|
-
|
|
7165
|
+
const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
|
|
7166
|
+
if (!providerId) {
|
|
7167
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user found');
|
|
7168
|
+
}
|
|
7169
|
+
const provider = this.providers.get(providerId);
|
|
7170
|
+
if (!provider) {
|
|
7171
|
+
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Provider not found');
|
|
5309
7172
|
}
|
|
5310
|
-
//
|
|
5311
|
-
|
|
7173
|
+
// Check if provider supports account deletion
|
|
7174
|
+
if ('deleteAccount' in provider && typeof provider.deleteAccount === 'function') {
|
|
7175
|
+
const deleteFn = provider.deleteAccount;
|
|
7176
|
+
await deleteFn();
|
|
7177
|
+
await this.signOut();
|
|
7178
|
+
return;
|
|
7179
|
+
}
|
|
7180
|
+
// If provider doesn't support deletion, revoke access and sign out
|
|
7181
|
+
if ('revokeAccess' in provider && typeof provider.revokeAccess === 'function') {
|
|
7182
|
+
const revokeFn = provider.revokeAccess;
|
|
7183
|
+
await revokeFn();
|
|
7184
|
+
}
|
|
7185
|
+
await this.signOut();
|
|
5312
7186
|
}
|
|
5313
7187
|
async getIdToken(options) {
|
|
7188
|
+
var _a;
|
|
5314
7189
|
this.validateInitialized();
|
|
5315
7190
|
const providerId = (options === null || options === void 0 ? void 0 : options.provider) || this.currentProvider;
|
|
5316
7191
|
if (!providerId) {
|
|
5317
7192
|
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for ID token');
|
|
5318
7193
|
}
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
|
|
7194
|
+
const provider = this.providers.get(providerId);
|
|
7195
|
+
if (!provider) {
|
|
7196
|
+
throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, `Provider ${providerId} not configured`);
|
|
7197
|
+
}
|
|
7198
|
+
// Check if provider has getIdToken method
|
|
7199
|
+
if ('getIdToken' in provider && typeof provider.getIdToken === 'function') {
|
|
7200
|
+
const getIdTokenFn = provider.getIdToken;
|
|
7201
|
+
return await getIdTokenFn((_a = options === null || options === void 0 ? void 0 : options.forceRefresh) !== null && _a !== void 0 ? _a : false);
|
|
7202
|
+
}
|
|
7203
|
+
// Try to get ID token from stored credential. The storage layer (WebStorage/
|
|
7204
|
+
// CapacitorPreferencesStorage) already JSON-parses on read, so the value is the
|
|
7205
|
+
// parsed credential object — do NOT JSON.parse it again.
|
|
7206
|
+
const parsed = (await this.storage.get(`${providerId}_credential`));
|
|
7207
|
+
if (parsed) {
|
|
7208
|
+
if (parsed.idToken) {
|
|
7209
|
+
// Check if token needs refresh
|
|
7210
|
+
if ((options === null || options === void 0 ? void 0 : options.forceRefresh) ||
|
|
7211
|
+
(parsed.expiresAt && parsed.expiresAt < Date.now())) {
|
|
7212
|
+
// Try to refresh
|
|
7213
|
+
if (provider.refreshToken) {
|
|
7214
|
+
const result = await provider.refreshToken({
|
|
7215
|
+
provider: providerId,
|
|
7216
|
+
forceRefresh: true,
|
|
7217
|
+
});
|
|
7218
|
+
if (result.credential.idToken) {
|
|
7219
|
+
return result.credential.idToken;
|
|
7220
|
+
}
|
|
7221
|
+
}
|
|
7222
|
+
}
|
|
7223
|
+
else {
|
|
7224
|
+
return parsed.idToken;
|
|
7225
|
+
}
|
|
7226
|
+
}
|
|
7227
|
+
}
|
|
7228
|
+
throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, `No ID token available for provider ${providerId}. Some providers (OAuth without OIDC) do not issue ID tokens.`);
|
|
7229
|
+
}
|
|
7230
|
+
/**
|
|
7231
|
+
* Persists provider-specific custom OAuth parameters.
|
|
7232
|
+
*
|
|
7233
|
+
* IMPORTANT (F-35): the underlying OAuth flow applies custom parameters that are passed directly
|
|
7234
|
+
* to {@link signIn} (`signIn({ provider, options: { customParameters } })`). The values stored
|
|
7235
|
+
* here are NOT automatically merged into a later `signIn` authorization URL — read them back and
|
|
7236
|
+
* pass them to `signIn` if you need them applied. The stored value is the raw parameters object
|
|
7237
|
+
* (the storage layer serializes it); it is not double JSON-encoded.
|
|
7238
|
+
*/
|
|
5322
7239
|
async setCustomParameters(options) {
|
|
5323
7240
|
this.validateInitialized();
|
|
5324
|
-
// Store
|
|
5325
|
-
|
|
7241
|
+
// Store the raw object — WebStorage/CapacitorPreferencesStorage serialize on write, so passing
|
|
7242
|
+
// a pre-stringified value here would double-encode it.
|
|
7243
|
+
await this.storage.set(`${options.provider}_custom_params`, options.parameters);
|
|
5326
7244
|
}
|
|
5327
7245
|
async revokeAccess(options) {
|
|
5328
7246
|
this.validateInitialized();
|
|
@@ -5331,6 +7249,9 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5331
7249
|
throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'No provider specified for access revocation');
|
|
5332
7250
|
}
|
|
5333
7251
|
const provider = this.getProvider(providerId);
|
|
7252
|
+
if (!provider.revokeAccess) {
|
|
7253
|
+
throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation not supported for provider ${providerId}`);
|
|
7254
|
+
}
|
|
5334
7255
|
try {
|
|
5335
7256
|
await provider.revokeAccess(options === null || options === void 0 ? void 0 : options.token);
|
|
5336
7257
|
}
|
|
@@ -5356,13 +7277,18 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5356
7277
|
// Dynamically import provider implementation
|
|
5357
7278
|
const provider = await this.createProvider(config);
|
|
5358
7279
|
if (provider) {
|
|
5359
|
-
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
7280
|
+
// Initialize if the provider supports it
|
|
7281
|
+
if (provider.initialize) {
|
|
7282
|
+
await provider.initialize(config.options);
|
|
7283
|
+
}
|
|
7284
|
+
// Forward auth state changes if provider supports it (BaseAuthProvider only)
|
|
7285
|
+
if ('addAuthStateListener' in provider && typeof provider.addAuthStateListener === 'function') {
|
|
7286
|
+
provider.addAuthStateListener((user) => {
|
|
7287
|
+
if (user) {
|
|
7288
|
+
this.authStateEmitter.emit(user);
|
|
7289
|
+
}
|
|
7290
|
+
});
|
|
7291
|
+
}
|
|
5366
7292
|
this.providers.set(config.provider, provider);
|
|
5367
7293
|
this.logger.info(`Provider ${config.provider} initialized`);
|
|
5368
7294
|
}
|
|
@@ -5385,16 +7311,34 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5385
7311
|
}
|
|
5386
7312
|
const refreshTime = credential.expiresAt - this.tokenRefreshBuffer - Date.now();
|
|
5387
7313
|
if (refreshTime > 0) {
|
|
5388
|
-
|
|
7314
|
+
this.scheduleRefresh(provider, refreshTime);
|
|
7315
|
+
}
|
|
7316
|
+
}
|
|
7317
|
+
/**
|
|
7318
|
+
* Schedules the refresh, clamping the delay to the 32-bit `setTimeout` ceiling
|
|
7319
|
+
* (2,147,483,647 ms ≈ 24.8 days). A far-future `expiresAt` would otherwise overflow the timer
|
|
7320
|
+
* and fire almost immediately (refresh storm). When clamped, the timer reschedules the remaining
|
|
7321
|
+
* wait on fire instead of refreshing early (F-17).
|
|
7322
|
+
*/
|
|
7323
|
+
scheduleRefresh(provider, delayMs) {
|
|
7324
|
+
const MAX_TIMEOUT = 2147483647;
|
|
7325
|
+
const clamped = Math.min(delayMs, MAX_TIMEOUT);
|
|
7326
|
+
const timer = setTimeout(() => {
|
|
7327
|
+
const remaining = delayMs - clamped;
|
|
7328
|
+
if (remaining > 0) {
|
|
7329
|
+
this.scheduleRefresh(provider, remaining);
|
|
7330
|
+
return;
|
|
7331
|
+
}
|
|
7332
|
+
void (async () => {
|
|
5389
7333
|
try {
|
|
5390
7334
|
await this.refreshToken({ provider });
|
|
5391
7335
|
}
|
|
5392
7336
|
catch (error) {
|
|
5393
7337
|
this.logger.error(`Auto token refresh failed for ${provider}`, error);
|
|
5394
7338
|
}
|
|
5395
|
-
}
|
|
5396
|
-
|
|
5397
|
-
|
|
7339
|
+
})();
|
|
7340
|
+
}, clamped);
|
|
7341
|
+
this.tokenRefreshTimers.set(provider, timer);
|
|
5398
7342
|
}
|
|
5399
7343
|
cancelTokenRefresh(provider) {
|
|
5400
7344
|
const timer = this.tokenRefreshTimers.get(provider);
|
|
@@ -5403,6 +7347,13 @@ class CapacitorAuthManagerWeb extends core.WebPlugin {
|
|
|
5403
7347
|
this.tokenRefreshTimers.delete(provider);
|
|
5404
7348
|
}
|
|
5405
7349
|
}
|
|
7350
|
+
/** Clears every active refresh timer (used on a global, untargeted sign-out). */
|
|
7351
|
+
cancelAllTokenRefresh() {
|
|
7352
|
+
for (const timer of this.tokenRefreshTimers.values()) {
|
|
7353
|
+
clearTimeout(timer);
|
|
7354
|
+
}
|
|
7355
|
+
this.tokenRefreshTimers.clear();
|
|
7356
|
+
}
|
|
5406
7357
|
}
|
|
5407
7358
|
|
|
5408
7359
|
var web = /*#__PURE__*/Object.freeze({
|
|
@@ -5412,7 +7363,11 @@ var web = /*#__PURE__*/Object.freeze({
|
|
|
5412
7363
|
|
|
5413
7364
|
exports.AuthError = AuthError;
|
|
5414
7365
|
exports.CapacitorAuthManager = CapacitorAuthManager;
|
|
7366
|
+
exports.CapacitorPreferencesStorage = CapacitorPreferencesStorage;
|
|
7367
|
+
exports.Logger = Logger;
|
|
5415
7368
|
exports.PlatformDetector = PlatformDetector;
|
|
7369
|
+
exports.WebStorage = WebStorage;
|
|
5416
7370
|
exports.auth = auth;
|
|
7371
|
+
exports.defaultLogger = defaultLogger;
|
|
5417
7372
|
exports.isAuthError = isAuthError;
|
|
5418
7373
|
//# sourceMappingURL=plugin.cjs.js.map
|