capacitor-auth-manager 2.4.4 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI-INTEGRATION-GUIDE.md +176 -0
- package/CHANGELOG.md +143 -0
- package/CapacitorAuthManager.podspec +3 -3
- package/README.md +99 -76
- package/android/build.gradle +23 -25
- package/android/consumer-rules.pro +14 -0
- package/android/proguard-rules.pro +5 -30
- package/android/src/main/AndroidManifest.xml +4 -9
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ActivityLauncher.java +26 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthErrorCodes.java +32 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthException.java +34 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +46 -25
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +62 -40
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +124 -66
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +225 -374
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleCredentialManagerSignIn.java +175 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleLegacySignIn.java +133 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleProfileCallback.java +8 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleResultMapper.java +158 -0
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +11 -3
- package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/SigningDiagnostics.java +76 -0
- package/dist/angular.cjs.js +421 -3376
- package/dist/core.cjs.js +589 -149
- package/dist/esm/angular/auth.guard.d.ts +1 -1
- package/dist/esm/angular/auth.module.d.ts +1 -1
- package/dist/esm/angular/auth.module.js +1 -1
- package/dist/esm/angular/auth.service.d.ts +2 -2
- package/dist/esm/angular/auth.service.js +1 -1
- package/dist/esm/angular/index.d.ts +4 -4
- package/dist/esm/angular/index.js +4 -4
- package/dist/esm/capacitor-plugin.d.ts +2 -3
- package/dist/esm/capacitor-plugin.js +14 -4
- package/dist/esm/core/auth-manager.d.ts +20 -2
- package/dist/esm/core/auth-manager.js +68 -12
- package/dist/esm/core/index.d.ts +5 -4
- package/dist/esm/core/index.js +5 -4
- package/dist/esm/core/provider-manifests.d.ts +1 -1
- package/dist/esm/core/provider-manifests.js +12 -13
- package/dist/esm/core/provider-registry.d.ts +8 -5
- package/dist/esm/core/provider-registry.js +41 -10
- package/dist/esm/core/types.d.ts +2 -2
- package/dist/esm/definitions.d.ts +29 -0
- package/dist/esm/index.d.ts +12 -12
- package/dist/esm/index.js +7 -7
- package/dist/esm/package.json +1 -0
- package/dist/esm/providers/base-provider.d.ts +7 -8
- package/dist/esm/providers/base-provider.js +7 -8
- package/dist/esm/providers/native/google-native-provider.d.ts +13 -2
- package/dist/esm/providers/native/google-native-provider.js +50 -6
- package/dist/esm/providers/oauth-provider.d.ts +2 -2
- package/dist/esm/providers/oauth-provider.js +3 -3
- package/dist/esm/providers/provider-factory.d.ts +5 -5
- package/dist/esm/providers/provider-factory.js +2 -2
- package/dist/esm/providers/web/google-provider.d.ts +74 -18
- package/dist/esm/providers/web/google-provider.js +391 -117
- package/dist/esm/providers/web/index.d.ts +1 -1
- package/dist/esm/providers/web/index.js +1 -1
- package/dist/esm/react/hooks.d.ts +2 -2
- package/dist/esm/react/hooks.js +2 -2
- package/dist/esm/react/index.d.ts +3 -3
- package/dist/esm/react/index.js +3 -3
- package/dist/esm/react/types.d.ts +1 -1
- package/dist/esm/utils/auth-error.d.ts +1 -1
- package/dist/esm/utils/auth-error.js +1 -1
- package/dist/esm/utils/event-emitter.d.ts +1 -1
- package/dist/esm/utils/event-emitter.js +1 -1
- package/dist/esm/utils/pending-verification-store.js +1 -1
- package/dist/esm/utils/storage.d.ts +2 -2
- package/dist/esm/utils/storage.js +31 -7
- package/dist/esm/vue/composables.d.ts +2 -2
- package/dist/esm/vue/composables.js +1 -1
- package/dist/esm/vue/index.d.ts +2 -2
- package/dist/esm/vue/index.js +2 -2
- package/dist/esm/web.d.ts +1 -1
- package/dist/esm/web.js +6 -6
- package/dist/plugin.cjs.js +291 -2771
- package/dist/plugin.js +585 -147
- package/dist/providers-web.cjs.js +1317 -0
- package/dist/react.cjs.js +310 -3265
- package/dist/vue.cjs.js +266 -3221
- package/ios/Plugin/AuthStorage.swift +3 -1
- package/ios/Plugin/GoogleAuthProvider.swift +7 -4
- package/ios/Plugin/Models.swift +28 -0
- package/ios/Plugin/Plugin.swift +64 -40
- package/package.json +54 -32
- package/scripts/configure.js +71 -325
|
@@ -0,0 +1,1317 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
4
|
+
var AuthProvider;
|
|
5
|
+
(function (AuthProvider) {
|
|
6
|
+
AuthProvider["GOOGLE"] = "google";
|
|
7
|
+
AuthProvider["APPLE"] = "apple";
|
|
8
|
+
AuthProvider["MICROSOFT"] = "microsoft";
|
|
9
|
+
AuthProvider["FACEBOOK"] = "facebook";
|
|
10
|
+
AuthProvider["GITHUB"] = "github";
|
|
11
|
+
AuthProvider["SLACK"] = "slack";
|
|
12
|
+
AuthProvider["LINKEDIN"] = "linkedin";
|
|
13
|
+
AuthProvider["FIREBASE"] = "firebase";
|
|
14
|
+
AuthProvider["EMAIL_MAGIC_LINK"] = "email_magic_link";
|
|
15
|
+
AuthProvider["MAGIC_LINK"] = "magic-link";
|
|
16
|
+
AuthProvider["SMS"] = "sms";
|
|
17
|
+
AuthProvider["EMAIL_PASSWORD"] = "email-password";
|
|
18
|
+
AuthProvider["PHONE_PASSWORD"] = "phone_password";
|
|
19
|
+
AuthProvider["USERNAME_PASSWORD"] = "username_password";
|
|
20
|
+
AuthProvider["EMAIL_CODE"] = "email_code";
|
|
21
|
+
AuthProvider["BIOMETRIC"] = "biometric";
|
|
22
|
+
})(AuthProvider || (AuthProvider = {}));
|
|
23
|
+
// Additional provider values for backward compatibility
|
|
24
|
+
Object.assign(Object.assign({}, AuthProvider), { 'magic-link': AuthProvider.MAGIC_LINK, 'email-password': AuthProvider.EMAIL_PASSWORD, sms: AuthProvider.SMS, biometric: AuthProvider.BIOMETRIC });
|
|
25
|
+
var AppleAuthScope;
|
|
26
|
+
(function (AppleAuthScope) {
|
|
27
|
+
AppleAuthScope["EMAIL"] = "email";
|
|
28
|
+
AppleAuthScope["NAME"] = "name";
|
|
29
|
+
})(AppleAuthScope || (AppleAuthScope = {}));
|
|
30
|
+
var BiometricType;
|
|
31
|
+
(function (BiometricType) {
|
|
32
|
+
BiometricType["FINGERPRINT"] = "fingerprint";
|
|
33
|
+
BiometricType["FACE_ID"] = "faceId";
|
|
34
|
+
BiometricType["TOUCH_ID"] = "touchId";
|
|
35
|
+
BiometricType["IRIS"] = "iris";
|
|
36
|
+
BiometricType["VOICE"] = "voice";
|
|
37
|
+
})(BiometricType || (BiometricType = {}));
|
|
38
|
+
var AuthPersistence;
|
|
39
|
+
(function (AuthPersistence) {
|
|
40
|
+
AuthPersistence["LOCAL"] = "local";
|
|
41
|
+
AuthPersistence["SESSION"] = "session";
|
|
42
|
+
AuthPersistence["NONE"] = "none";
|
|
43
|
+
})(AuthPersistence || (AuthPersistence = {}));
|
|
44
|
+
var AuthErrorCode;
|
|
45
|
+
(function (AuthErrorCode) {
|
|
46
|
+
AuthErrorCode["INVALID_CREDENTIALS"] = "auth/invalid-credentials";
|
|
47
|
+
AuthErrorCode["USER_NOT_FOUND"] = "auth/user-not-found";
|
|
48
|
+
AuthErrorCode["WRONG_PASSWORD"] = "auth/wrong-password";
|
|
49
|
+
AuthErrorCode["EMAIL_ALREADY_IN_USE"] = "auth/email-already-in-use";
|
|
50
|
+
AuthErrorCode["WEAK_PASSWORD"] = "auth/weak-password";
|
|
51
|
+
AuthErrorCode["NETWORK_ERROR"] = "auth/network-error";
|
|
52
|
+
AuthErrorCode["TOO_MANY_REQUESTS"] = "auth/too-many-requests";
|
|
53
|
+
AuthErrorCode["USER_DISABLED"] = "auth/user-disabled";
|
|
54
|
+
AuthErrorCode["OPERATION_NOT_ALLOWED"] = "auth/operation-not-allowed";
|
|
55
|
+
AuthErrorCode["INVALID_EMAIL"] = "auth/invalid-email";
|
|
56
|
+
AuthErrorCode["INVALID_PHONE_NUMBER"] = "auth/invalid-phone-number";
|
|
57
|
+
AuthErrorCode["INVALID_VERIFICATION_CODE"] = "auth/invalid-verification-code";
|
|
58
|
+
AuthErrorCode["EXPIRED_ACTION_CODE"] = "auth/expired-action-code";
|
|
59
|
+
AuthErrorCode["CREDENTIAL_ALREADY_IN_USE"] = "auth/credential-already-in-use";
|
|
60
|
+
AuthErrorCode["ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"] = "auth/account-exists-with-different-credential";
|
|
61
|
+
AuthErrorCode["REQUIRES_RECENT_LOGIN"] = "auth/requires-recent-login";
|
|
62
|
+
AuthErrorCode["PROVIDER_ALREADY_LINKED"] = "auth/provider-already-linked";
|
|
63
|
+
AuthErrorCode["NO_SUCH_PROVIDER"] = "auth/no-such-provider";
|
|
64
|
+
AuthErrorCode["INVALID_USER_TOKEN"] = "auth/invalid-user-token";
|
|
65
|
+
AuthErrorCode["TOKEN_EXPIRED"] = "auth/token-expired";
|
|
66
|
+
AuthErrorCode["USER_TOKEN_EXPIRED"] = "auth/user-token-expired";
|
|
67
|
+
AuthErrorCode["INVALID_API_KEY"] = "auth/invalid-api-key";
|
|
68
|
+
AuthErrorCode["USER_CANCELLED"] = "auth/user-cancelled";
|
|
69
|
+
AuthErrorCode["APP_NOT_AUTHORIZED"] = "auth/app-not-authorized";
|
|
70
|
+
AuthErrorCode["KEYCHAIN_ERROR"] = "auth/keychain-error";
|
|
71
|
+
AuthErrorCode["INTERNAL_ERROR"] = "auth/internal-error";
|
|
72
|
+
AuthErrorCode["BIOMETRIC_NOT_AVAILABLE"] = "auth/biometric-not-available";
|
|
73
|
+
AuthErrorCode["BIOMETRIC_NOT_ENROLLED"] = "auth/biometric-not-enrolled";
|
|
74
|
+
AuthErrorCode["BIOMETRIC_AUTHENTICATION_FAILED"] = "auth/biometric-authentication-failed";
|
|
75
|
+
AuthErrorCode["UNSUPPORTED_PROVIDER"] = "auth/unsupported-provider";
|
|
76
|
+
AuthErrorCode["MISSING_CONFIGURATION"] = "auth/missing-configuration";
|
|
77
|
+
AuthErrorCode["POPUP_BLOCKED"] = "auth/popup-blocked";
|
|
78
|
+
AuthErrorCode["POPUP_CLOSED_BY_USER"] = "auth/popup-closed-by-user";
|
|
79
|
+
AuthErrorCode["REDIRECT_CANCELLED_BY_USER"] = "auth/redirect-cancelled-by-user";
|
|
80
|
+
AuthErrorCode["MISSING_REDIRECT_URL"] = "auth/missing-redirect-url";
|
|
81
|
+
AuthErrorCode["INVALID_STATE"] = "auth/invalid-state";
|
|
82
|
+
AuthErrorCode["MISSING_CODE_VERIFIER"] = "auth/missing-code-verifier";
|
|
83
|
+
AuthErrorCode["INVALID_CODE_VERIFIER"] = "auth/invalid-code-verifier";
|
|
84
|
+
AuthErrorCode["MISSING_NONCE"] = "auth/missing-nonce";
|
|
85
|
+
AuthErrorCode["INVALID_NONCE"] = "auth/invalid-nonce";
|
|
86
|
+
AuthErrorCode["UNAUTHORIZED_DOMAIN"] = "auth/unauthorized-domain";
|
|
87
|
+
AuthErrorCode["INVALID_CONTINUE_URL"] = "auth/invalid-continue-url";
|
|
88
|
+
AuthErrorCode["MISSING_CONTINUE_URL"] = "auth/missing-continue-url";
|
|
89
|
+
AuthErrorCode["INVALID_DYNAMIC_LINK_DOMAIN"] = "auth/invalid-dynamic-link-domain";
|
|
90
|
+
AuthErrorCode["REJECTED_CREDENTIAL"] = "auth/rejected-credential";
|
|
91
|
+
AuthErrorCode["PHONE_NUMBER_ALREADY_EXISTS"] = "auth/phone-number-already-exists";
|
|
92
|
+
AuthErrorCode["QUOTA_EXCEEDED"] = "auth/quota-exceeded";
|
|
93
|
+
AuthErrorCode["CAPTCHA_CHECK_FAILED"] = "auth/captcha-check-failed";
|
|
94
|
+
AuthErrorCode["MISSING_CAPTCHA_TOKEN"] = "auth/missing-captcha-token";
|
|
95
|
+
AuthErrorCode["INVALID_CAPTCHA_TOKEN"] = "auth/invalid-captcha-token";
|
|
96
|
+
AuthErrorCode["MISSING_CLIENT_IDENTIFIER"] = "auth/missing-client-identifier";
|
|
97
|
+
AuthErrorCode["MISSING_OR_INVALID_NONCE"] = "auth/missing-or-invalid-nonce";
|
|
98
|
+
AuthErrorCode["INTERACTION_REQUIRED"] = "auth/interaction-required";
|
|
99
|
+
AuthErrorCode["LOGIN_REQUIRED"] = "auth/login-required";
|
|
100
|
+
AuthErrorCode["CONSENT_REQUIRED"] = "auth/consent-required";
|
|
101
|
+
AuthErrorCode["INVALID_GRANT"] = "auth/invalid-grant";
|
|
102
|
+
AuthErrorCode["UNSUPPORTED_GRANT_TYPE"] = "auth/unsupported-grant-type";
|
|
103
|
+
AuthErrorCode["PROVIDER_INIT_FAILED"] = "auth/provider-init-failed";
|
|
104
|
+
AuthErrorCode["SIGN_IN_FAILED"] = "auth/sign-in-failed";
|
|
105
|
+
AuthErrorCode["SIGN_OUT_FAILED"] = "auth/sign-out-failed";
|
|
106
|
+
AuthErrorCode["NO_AUTH_SESSION"] = "auth/no-auth-session";
|
|
107
|
+
AuthErrorCode["TOKEN_REFRESH_FAILED"] = "auth/token-refresh-failed";
|
|
108
|
+
AuthErrorCode["ACCESS_DENIED"] = "auth/access-denied";
|
|
109
|
+
AuthErrorCode["SERVER_ERROR"] = "auth/server-error";
|
|
110
|
+
AuthErrorCode["TEMPORARILY_UNAVAILABLE"] = "auth/temporarily-unavailable";
|
|
111
|
+
AuthErrorCode["INVALID_REQUEST"] = "auth/invalid-request";
|
|
112
|
+
AuthErrorCode["INVALID_SCOPE"] = "auth/invalid-scope";
|
|
113
|
+
AuthErrorCode["CLIENT_NOT_FOUND"] = "auth/client-not-found";
|
|
114
|
+
AuthErrorCode["MISSING_CONFIG"] = "auth/missing-config";
|
|
115
|
+
AuthErrorCode["PROVIDER_NOT_INITIALIZED"] = "auth/provider-not-initialized";
|
|
116
|
+
// --- Added in 2.2.0 (additive, non-breaking) so standalone providers (sms / email-code /
|
|
117
|
+
// magic-link / biometric / email-password / username-password / phone-password) throw enum
|
|
118
|
+
// codes instead of bare string literals. Consumers can now switch on `error.code` reliably.
|
|
119
|
+
AuthErrorCode["CREDENTIALS_REQUIRED"] = "auth/credentials-required";
|
|
120
|
+
AuthErrorCode["EMAIL_REQUIRED"] = "auth/email-required";
|
|
121
|
+
AuthErrorCode["PHONE_REQUIRED"] = "auth/phone-required";
|
|
122
|
+
AuthErrorCode["USERNAME_REQUIRED"] = "auth/username-required";
|
|
123
|
+
AuthErrorCode["INVALID_USERNAME"] = "auth/invalid-username";
|
|
124
|
+
AuthErrorCode["USERNAME_ALREADY_EXISTS"] = "auth/username-already-exists";
|
|
125
|
+
AuthErrorCode["INVALID_CODE"] = "auth/invalid-code";
|
|
126
|
+
AuthErrorCode["CODE_EXPIRED"] = "auth/code-expired";
|
|
127
|
+
AuthErrorCode["INVALID_TOKEN"] = "auth/invalid-token";
|
|
128
|
+
AuthErrorCode["NO_PENDING_VERIFICATION"] = "auth/no-pending-verification";
|
|
129
|
+
AuthErrorCode["TOO_MANY_ATTEMPTS"] = "auth/too-many-attempts";
|
|
130
|
+
AuthErrorCode["RESEND_DELAY"] = "auth/resend-delay";
|
|
131
|
+
AuthErrorCode["SEND_CODE_FAILED"] = "auth/send-code-failed";
|
|
132
|
+
AuthErrorCode["SEND_LINK_FAILED"] = "auth/send-link-failed";
|
|
133
|
+
AuthErrorCode["VERIFICATION_FAILED"] = "auth/verification-failed";
|
|
134
|
+
AuthErrorCode["SIGN_UP_FAILED"] = "auth/sign-up-failed";
|
|
135
|
+
AuthErrorCode["SIGN_UP_DISABLED"] = "auth/sign-up-disabled";
|
|
136
|
+
AuthErrorCode["NO_REFRESH_TOKEN"] = "auth/no-refresh-token";
|
|
137
|
+
AuthErrorCode["NOT_AUTHENTICATED"] = "auth/not-authenticated";
|
|
138
|
+
AuthErrorCode["PHONE_NOT_VERIFIED"] = "auth/phone-not-verified";
|
|
139
|
+
AuthErrorCode["EMAIL_ALREADY_VERIFIED"] = "auth/email-already-verified";
|
|
140
|
+
AuthErrorCode["NO_STORED_CREDENTIALS"] = "auth/no-stored-credentials";
|
|
141
|
+
AuthErrorCode["STORAGE_ERROR"] = "auth/storage-error";
|
|
142
|
+
AuthErrorCode["BIOMETRIC_LOCKOUT"] = "auth/biometric-lockout";
|
|
143
|
+
AuthErrorCode["PROVIDER_UNSUPPORTED_OPERATION"] = "auth/provider-unsupported-operation";
|
|
144
|
+
// The active provider does not implement an optional capability (e.g. token refresh).
|
|
145
|
+
// Same string the manager previously threw as a bare literal — now an enum member so
|
|
146
|
+
// consumers can switch on `AuthErrorCode.OPERATION_NOT_SUPPORTED` reliably.
|
|
147
|
+
AuthErrorCode["OPERATION_NOT_SUPPORTED"] = "auth/operation-not-supported";
|
|
148
|
+
// The provider is recognized but not yet enabled in this release. As of 2.4.1 the package ships
|
|
149
|
+
// a hardened Google provider and re-enables the remaining providers one at a time. Switch on this
|
|
150
|
+
// to detect a "coming soon" provider distinctly from an unknown one.
|
|
151
|
+
AuthErrorCode["PROVIDER_NOT_ENABLED"] = "auth/provider-not-enabled";
|
|
152
|
+
})(AuthErrorCode || (AuthErrorCode = {}));
|
|
153
|
+
|
|
154
|
+
class AuthError extends Error {
|
|
155
|
+
constructor(code, message, provider, details) {
|
|
156
|
+
super(message);
|
|
157
|
+
this.name = 'AuthError';
|
|
158
|
+
this.code = code;
|
|
159
|
+
this.provider = provider;
|
|
160
|
+
this.details = AuthError.sanitizeDetails(details);
|
|
161
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8 engines:
|
|
162
|
+
// Node.js and Chromium). Typed locally so the package does not depend on @types/node globals.
|
|
163
|
+
const ErrorCtor = Error;
|
|
164
|
+
if (ErrorCtor.captureStackTrace) {
|
|
165
|
+
ErrorCtor.captureStackTrace(this, AuthError);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Produces a safe, shallow `details` object: redacts sensitive keys and keeps only JSON-safe
|
|
170
|
+
* primitives. Prevents tokens/PII embedded in a raw error or token-endpoint response body from
|
|
171
|
+
* being captured into AuthError.details (and thus logged or serialized via toJSON()).
|
|
172
|
+
*/
|
|
173
|
+
static sanitizeDetails(input) {
|
|
174
|
+
if (input === null || typeof input !== 'object') {
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
const out = {};
|
|
178
|
+
for (const [key, value] of Object.entries(input)) {
|
|
179
|
+
if (AuthError.SENSITIVE_KEY.test(key)) {
|
|
180
|
+
out[key] = '[redacted]';
|
|
181
|
+
}
|
|
182
|
+
else if (value === null ||
|
|
183
|
+
typeof value === 'string' ||
|
|
184
|
+
typeof value === 'number' ||
|
|
185
|
+
typeof value === 'boolean') {
|
|
186
|
+
out[key] = value;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
190
|
+
}
|
|
191
|
+
static fromError(error, provider) {
|
|
192
|
+
if (error instanceof AuthError) {
|
|
193
|
+
return error;
|
|
194
|
+
}
|
|
195
|
+
let code = AuthErrorCode.INTERNAL_ERROR;
|
|
196
|
+
let message = 'An unknown error occurred';
|
|
197
|
+
const details = error;
|
|
198
|
+
if (error instanceof Error) {
|
|
199
|
+
message = error.message;
|
|
200
|
+
// Try to map common error patterns to specific error codes
|
|
201
|
+
if (error.message.includes('network')) {
|
|
202
|
+
code = AuthErrorCode.NETWORK_ERROR;
|
|
203
|
+
}
|
|
204
|
+
else if (error.message.includes('cancelled') ||
|
|
205
|
+
error.message.includes('canceled')) {
|
|
206
|
+
code = AuthErrorCode.USER_CANCELLED;
|
|
207
|
+
}
|
|
208
|
+
else if (error.message.includes('timeout')) {
|
|
209
|
+
code = AuthErrorCode.NETWORK_ERROR;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// Handle provider-specific error codes
|
|
213
|
+
const errorObj = error;
|
|
214
|
+
if (errorObj === null || errorObj === void 0 ? void 0 : errorObj.code) {
|
|
215
|
+
// Check if the code is a valid AuthErrorCode
|
|
216
|
+
if (Object.values(AuthErrorCode).includes(errorObj.code)) {
|
|
217
|
+
code = errorObj.code;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return new AuthError(code, message, provider, details);
|
|
221
|
+
}
|
|
222
|
+
toJSON() {
|
|
223
|
+
return {
|
|
224
|
+
name: this.name,
|
|
225
|
+
code: this.code,
|
|
226
|
+
message: this.message,
|
|
227
|
+
provider: this.provider,
|
|
228
|
+
details: this.details,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
AuthError.SENSITIVE_KEY = /(token|secret|password|authorization|code_verifier|client_secret|credential|api[-_]?key|cookie)/i;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Reads a default log level from the build/runtime environment WITHOUT assuming a particular
|
|
236
|
+
* bundler or host. Checked defensively (each access wrapped) so it is safe in:
|
|
237
|
+
* - Vite / bundlers that define `import.meta.env`
|
|
238
|
+
* - Node / SSR where `globalThis.process.env` exists
|
|
239
|
+
* - Plain browsers where neither is present (falls back to 'warn')
|
|
240
|
+
*
|
|
241
|
+
* Intentional omissions for a PUBLISHED LIBRARY (see F-42):
|
|
242
|
+
* - We do NOT patch the host application's global `console.*`. A library silencing the host's
|
|
243
|
+
* console would be hostile and surprising.
|
|
244
|
+
* - We do NOT read the host's `localStorage` for a log-level switch. The host owns its storage;
|
|
245
|
+
* the consumer configures logging explicitly via `auth.configure({ logLevel })` or
|
|
246
|
+
* `logger.setLevel()`.
|
|
247
|
+
*/
|
|
248
|
+
function readEnvLogLevel() {
|
|
249
|
+
var _a;
|
|
250
|
+
const candidates = [];
|
|
251
|
+
try {
|
|
252
|
+
// import.meta.env may not exist (CJS) — guard the whole access.
|
|
253
|
+
const metaEnv = (_a = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('providers-web.cjs.js', document.baseURI).href)) })) === null || _a === void 0 ? void 0 : _a.env;
|
|
254
|
+
if (metaEnv) {
|
|
255
|
+
candidates.push(metaEnv.VITE_LOG_LEVEL, metaEnv.LOG_LEVEL);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch (_b) {
|
|
259
|
+
// import.meta unsupported in this environment — ignore.
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const proc = globalThis.process;
|
|
263
|
+
if (proc === null || proc === void 0 ? void 0 : proc.env) {
|
|
264
|
+
candidates.push(proc.env.VITE_LOG_LEVEL, proc.env.LOG_LEVEL);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
catch (_c) {
|
|
268
|
+
// process not available — ignore.
|
|
269
|
+
}
|
|
270
|
+
for (const value of candidates) {
|
|
271
|
+
if (value === 'debug' ||
|
|
272
|
+
value === 'info' ||
|
|
273
|
+
value === 'warn' ||
|
|
274
|
+
value === 'error' ||
|
|
275
|
+
value === 'silent') {
|
|
276
|
+
return value;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
class Logger {
|
|
282
|
+
constructor(config) {
|
|
283
|
+
var _a, _b;
|
|
284
|
+
this.logLevels = {
|
|
285
|
+
debug: 0,
|
|
286
|
+
info: 1,
|
|
287
|
+
warn: 2,
|
|
288
|
+
error: 3,
|
|
289
|
+
silent: 4,
|
|
290
|
+
};
|
|
291
|
+
// An explicit logLevel from the caller wins; otherwise fall back to the env default, then 'warn'.
|
|
292
|
+
this.config = Object.assign(Object.assign({}, config), { logLevel: (_b = (_a = config.logLevel) !== null && _a !== void 0 ? _a : readEnvLogLevel()) !== null && _b !== void 0 ? _b : 'warn' });
|
|
293
|
+
}
|
|
294
|
+
shouldLog(level) {
|
|
295
|
+
if (!this.config.enableLogging)
|
|
296
|
+
return false;
|
|
297
|
+
return this.logLevels[level] >= this.logLevels[this.config.logLevel];
|
|
298
|
+
}
|
|
299
|
+
formatMessage(level, message) {
|
|
300
|
+
const timestamp = new Date().toISOString();
|
|
301
|
+
const prefix = this.config.prefix || 'CapacitorAuthManager';
|
|
302
|
+
return `[${timestamp}] [${prefix}] [${level.toUpperCase()}] ${message}`;
|
|
303
|
+
}
|
|
304
|
+
debug(message, ...args) {
|
|
305
|
+
if (this.shouldLog('debug')) {
|
|
306
|
+
console.debug(this.formatMessage('debug', message), ...args);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
info(message, ...args) {
|
|
310
|
+
if (this.shouldLog('info')) {
|
|
311
|
+
console.info(this.formatMessage('info', message), ...args);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
warn(message, ...args) {
|
|
315
|
+
if (this.shouldLog('warn')) {
|
|
316
|
+
console.warn(this.formatMessage('warn', message), ...args);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
error(message, error) {
|
|
320
|
+
if (this.shouldLog('error')) {
|
|
321
|
+
console.error(this.formatMessage('error', message), error);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/** Verbose tracing — gated at `debug` level like {@link debug}. */
|
|
325
|
+
trace(message, ...args) {
|
|
326
|
+
if (this.shouldLog('debug')) {
|
|
327
|
+
console.trace(this.formatMessage('trace', message), ...args);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** Tabular output — gated at `debug` level. Falls back to `debug` when `console.table` is absent. */
|
|
331
|
+
table(data, columns) {
|
|
332
|
+
if (this.shouldLog('debug')) {
|
|
333
|
+
if (typeof console.table === 'function') {
|
|
334
|
+
console.table(data, columns);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
console.debug(this.formatMessage('table', ''), data);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/** Opens a console group — gated at `debug` level. No-ops if `console.group` is absent. */
|
|
342
|
+
group(label) {
|
|
343
|
+
if (this.shouldLog('debug') && typeof console.group === 'function') {
|
|
344
|
+
console.group(label ? this.formatMessage('group', label) : undefined);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** Closes a console group opened by {@link group}. */
|
|
348
|
+
groupEnd() {
|
|
349
|
+
if (this.shouldLog('debug') && typeof console.groupEnd === 'function') {
|
|
350
|
+
console.groupEnd();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** Starts a timer — gated at `debug` level. No-ops if `console.time` is absent. */
|
|
354
|
+
time(label) {
|
|
355
|
+
if (this.shouldLog('debug') && typeof console.time === 'function') {
|
|
356
|
+
console.time(label);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** Stops a timer started by {@link time} and logs the elapsed duration. */
|
|
360
|
+
timeEnd(label) {
|
|
361
|
+
if (this.shouldLog('debug') && typeof console.timeEnd === 'function') {
|
|
362
|
+
console.timeEnd(label);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
setLogLevel(level) {
|
|
366
|
+
this.config.logLevel = level;
|
|
367
|
+
}
|
|
368
|
+
/** Alias for {@link setLogLevel} matching the workspace logger convention. */
|
|
369
|
+
setLevel(level) {
|
|
370
|
+
this.config.logLevel = level;
|
|
371
|
+
}
|
|
372
|
+
getLevel() {
|
|
373
|
+
return this.config.logLevel;
|
|
374
|
+
}
|
|
375
|
+
setEnabled(enabled) {
|
|
376
|
+
this.config.enableLogging = enabled;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Shared default logger instance used by package internals that don't receive a logger via
|
|
381
|
+
* dependency injection (e.g. {@link EventEmitter}, {@link WebStorage} defaults, the biometric
|
|
382
|
+
* provider). Enabled by default at `warn` level so only warnings + errors surface unless the
|
|
383
|
+
* consumer raises the level. Consumers can adjust it programmatically:
|
|
384
|
+
*
|
|
385
|
+
* ```ts
|
|
386
|
+
* import { defaultLogger } from 'capacitor-auth-manager';
|
|
387
|
+
* defaultLogger.setLevel('debug');
|
|
388
|
+
* ```
|
|
389
|
+
*/
|
|
390
|
+
const defaultLogger = new Logger({
|
|
391
|
+
enableLogging: true,
|
|
392
|
+
logLevel: 'warn',
|
|
393
|
+
prefix: 'CapacitorAuthManager',
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
class EventEmitter {
|
|
397
|
+
/**
|
|
398
|
+
* @param logger Optional logger for listener errors. Defaults to the shared {@link defaultLogger}
|
|
399
|
+
* so emitter errors honour the package log level instead of writing to `console` directly.
|
|
400
|
+
*/
|
|
401
|
+
constructor(logger = defaultLogger) {
|
|
402
|
+
this.listeners = new Set();
|
|
403
|
+
this.logger = logger;
|
|
404
|
+
}
|
|
405
|
+
emit(data) {
|
|
406
|
+
this.listeners.forEach((listener) => {
|
|
407
|
+
try {
|
|
408
|
+
listener(data);
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
this.logger.error('Error in event listener:', error);
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
subscribe(listener) {
|
|
416
|
+
this.listeners.add(listener);
|
|
417
|
+
return () => {
|
|
418
|
+
this.listeners.delete(listener);
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
clear() {
|
|
422
|
+
this.listeners.clear();
|
|
423
|
+
}
|
|
424
|
+
get listenerCount() {
|
|
425
|
+
return this.listeners.size;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
class WebStorage {
|
|
430
|
+
/**
|
|
431
|
+
* @param persistence Where to persist values (local / session / in-memory).
|
|
432
|
+
* @param prefix Key prefix to namespace this package's storage.
|
|
433
|
+
* @param logger Optional logger for storage errors. Defaults to the shared {@link defaultLogger}
|
|
434
|
+
* so storage failures honour the package log level instead of writing to `console` directly.
|
|
435
|
+
*/
|
|
436
|
+
constructor(persistence = AuthPersistence.LOCAL, prefix = 'cap_auth_', logger = defaultLogger) {
|
|
437
|
+
this.prefix = prefix;
|
|
438
|
+
this.logger = logger;
|
|
439
|
+
switch (persistence) {
|
|
440
|
+
case AuthPersistence.SESSION:
|
|
441
|
+
this.storage = resolveBrowserStorage('sessionStorage');
|
|
442
|
+
break;
|
|
443
|
+
case AuthPersistence.NONE:
|
|
444
|
+
// Use in-memory storage
|
|
445
|
+
this.storage = new InMemoryStorage();
|
|
446
|
+
break;
|
|
447
|
+
case AuthPersistence.LOCAL:
|
|
448
|
+
default:
|
|
449
|
+
this.storage = resolveBrowserStorage('localStorage');
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async get(key) {
|
|
453
|
+
try {
|
|
454
|
+
const value = this.storage.getItem(this.prefix + key);
|
|
455
|
+
if (value) {
|
|
456
|
+
try {
|
|
457
|
+
return JSON.parse(value);
|
|
458
|
+
}
|
|
459
|
+
catch (_a) {
|
|
460
|
+
return value;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
this.logger.error('Storage get error:', error);
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
async set(key, value) {
|
|
471
|
+
try {
|
|
472
|
+
const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
|
|
473
|
+
this.storage.setItem(this.prefix + key, stringValue);
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
this.logger.error('Storage set error:', error);
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async remove(key) {
|
|
481
|
+
try {
|
|
482
|
+
this.storage.removeItem(this.prefix + key);
|
|
483
|
+
}
|
|
484
|
+
catch (error) {
|
|
485
|
+
this.logger.error('Storage remove error:', error);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
async clear() {
|
|
489
|
+
try {
|
|
490
|
+
const keys = [];
|
|
491
|
+
for (let i = 0; i < this.storage.length; i++) {
|
|
492
|
+
const key = this.storage.key(i);
|
|
493
|
+
if (key && key.startsWith(this.prefix)) {
|
|
494
|
+
keys.push(key);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
keys.forEach((key) => this.storage.removeItem(key));
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
this.logger.error('Storage clear error:', error);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Returns the requested browser storage when it exists AND is usable, otherwise an in-memory
|
|
506
|
+
* fallback. Two environments make the fallback necessary:
|
|
507
|
+
* - Node / SSR / test runners: `window` is undefined, so the old unguarded `window.localStorage`
|
|
508
|
+
* read threw `ReferenceError: window is not defined` at import time (ISSUE-002).
|
|
509
|
+
* - Browsers that expose the API but refuse it (Safari private mode, cookies disabled, sandboxed
|
|
510
|
+
* iframes): `getItem`/`setItem` throw, so the probe below catches that and degrades gracefully.
|
|
511
|
+
*/
|
|
512
|
+
function resolveBrowserStorage(kind) {
|
|
513
|
+
if (typeof window === 'undefined') {
|
|
514
|
+
return new InMemoryStorage();
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
const candidate = window[kind];
|
|
518
|
+
if (!candidate) {
|
|
519
|
+
return new InMemoryStorage();
|
|
520
|
+
}
|
|
521
|
+
const probeKey = '__cap_auth_probe__';
|
|
522
|
+
candidate.setItem(probeKey, '1');
|
|
523
|
+
candidate.removeItem(probeKey);
|
|
524
|
+
return candidate;
|
|
525
|
+
}
|
|
526
|
+
catch (_a) {
|
|
527
|
+
return new InMemoryStorage();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
class InMemoryStorage {
|
|
531
|
+
constructor() {
|
|
532
|
+
this.data = new Map();
|
|
533
|
+
}
|
|
534
|
+
get length() {
|
|
535
|
+
return this.data.size;
|
|
536
|
+
}
|
|
537
|
+
clear() {
|
|
538
|
+
this.data.clear();
|
|
539
|
+
}
|
|
540
|
+
getItem(key) {
|
|
541
|
+
return this.data.get(key) || null;
|
|
542
|
+
}
|
|
543
|
+
key(index) {
|
|
544
|
+
const keys = Array.from(this.data.keys());
|
|
545
|
+
return keys[index] || null;
|
|
546
|
+
}
|
|
547
|
+
removeItem(key) {
|
|
548
|
+
this.data.delete(key);
|
|
549
|
+
}
|
|
550
|
+
setItem(key, value) {
|
|
551
|
+
this.data.set(key, value);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Normalize a provider constructor argument into a full {@link BaseProviderConfig}.
|
|
557
|
+
*
|
|
558
|
+
* The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
|
|
559
|
+
* get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
|
|
560
|
+
* tests and direct consumers pass the provider's own bare options object. This helper accepts
|
|
561
|
+
* either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`) plus the
|
|
562
|
+
* shared {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
|
|
563
|
+
*/
|
|
564
|
+
function resolveProviderConfig(provider, input) {
|
|
565
|
+
if (typeof input === 'object' &&
|
|
566
|
+
input !== null &&
|
|
567
|
+
'storage' in input &&
|
|
568
|
+
'logger' in input &&
|
|
569
|
+
'options' in input) {
|
|
570
|
+
return input;
|
|
571
|
+
}
|
|
572
|
+
return {
|
|
573
|
+
provider,
|
|
574
|
+
options: (input !== null && input !== void 0 ? input : {}),
|
|
575
|
+
storage: new WebStorage(AuthPersistence.NONE),
|
|
576
|
+
logger: defaultLogger,
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
class BaseAuthProvider {
|
|
580
|
+
get name() {
|
|
581
|
+
return this.provider;
|
|
582
|
+
}
|
|
583
|
+
constructor(config) {
|
|
584
|
+
this.currentUser = null;
|
|
585
|
+
this.isInitialized = false;
|
|
586
|
+
this.provider = config.provider;
|
|
587
|
+
this.options = config.options;
|
|
588
|
+
this.storage = config.storage;
|
|
589
|
+
this.logger = config.logger;
|
|
590
|
+
this.persistence = config.persistence || AuthPersistence.LOCAL;
|
|
591
|
+
this.authStateEmitter = new EventEmitter();
|
|
592
|
+
}
|
|
593
|
+
// Capability methods with concrete defaults: providers that support these operations override
|
|
594
|
+
// them; the rest inherit a uniform "not allowed" signal so capability detection is consistent
|
|
595
|
+
// across every provider (see AuthProviderInterface, where they are optional). Marking them
|
|
596
|
+
// abstract previously forced every subclass to re-implement them just to throw.
|
|
597
|
+
async linkAccount(_options) {
|
|
598
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Account linking is not supported by provider ${this.provider}`, this.provider);
|
|
599
|
+
}
|
|
600
|
+
async unlinkAccount(_options) {
|
|
601
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Account unlinking is not supported by provider ${this.provider}`, this.provider);
|
|
602
|
+
}
|
|
603
|
+
async revokeAccess(_token) {
|
|
604
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `Access revocation is not supported by provider ${this.provider}`, this.provider);
|
|
605
|
+
}
|
|
606
|
+
async getCurrentUser() {
|
|
607
|
+
if (!this.isInitialized) {
|
|
608
|
+
await this.initialize();
|
|
609
|
+
}
|
|
610
|
+
return this.currentUser;
|
|
611
|
+
}
|
|
612
|
+
addAuthStateListener(callback) {
|
|
613
|
+
return this.authStateEmitter.subscribe(callback);
|
|
614
|
+
}
|
|
615
|
+
async setCurrentUser(user) {
|
|
616
|
+
this.currentUser = user;
|
|
617
|
+
// Persist user to storage
|
|
618
|
+
const storageKey = `${this.provider}_current_user`;
|
|
619
|
+
if (user) {
|
|
620
|
+
await this.storage.set(storageKey, user);
|
|
621
|
+
}
|
|
622
|
+
else {
|
|
623
|
+
await this.storage.remove(storageKey);
|
|
624
|
+
}
|
|
625
|
+
// Emit auth state change
|
|
626
|
+
this.authStateEmitter.emit(user);
|
|
627
|
+
}
|
|
628
|
+
async loadCurrentUser() {
|
|
629
|
+
try {
|
|
630
|
+
const storageKey = `${this.provider}_current_user`;
|
|
631
|
+
const userData = await this.storage.get(storageKey);
|
|
632
|
+
if (userData) {
|
|
633
|
+
this.currentUser = userData;
|
|
634
|
+
this.logger.debug(`Loaded user from storage for provider ${this.provider}`);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
this.logger.error('Failed to load user from storage', error);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
async saveCredential(credential) {
|
|
642
|
+
const storageKey = `${this.provider}_credential`;
|
|
643
|
+
await this.storage.set(storageKey, credential);
|
|
644
|
+
}
|
|
645
|
+
async loadCredential() {
|
|
646
|
+
try {
|
|
647
|
+
const storageKey = `${this.provider}_credential`;
|
|
648
|
+
const credentialData = await this.storage.get(storageKey);
|
|
649
|
+
if (credentialData) {
|
|
650
|
+
return credentialData;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
this.logger.error('Failed to load credential from storage', error);
|
|
655
|
+
}
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
async clearStoredData() {
|
|
659
|
+
const userKey = `${this.provider}_current_user`;
|
|
660
|
+
const credentialKey = `${this.provider}_credential`;
|
|
661
|
+
await Promise.all([
|
|
662
|
+
this.storage.remove(userKey),
|
|
663
|
+
this.storage.remove(credentialKey),
|
|
664
|
+
]);
|
|
665
|
+
}
|
|
666
|
+
validateInitialized() {
|
|
667
|
+
if (!this.isInitialized) {
|
|
668
|
+
throw new AuthError(AuthErrorCode.INTERNAL_ERROR, `Provider ${this.provider} is not initialized`, this.provider);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
createAuthResult(user, credential, isNewUser = false, operationType = 'signIn') {
|
|
672
|
+
return {
|
|
673
|
+
user,
|
|
674
|
+
credential,
|
|
675
|
+
additionalUserInfo: {
|
|
676
|
+
isNewUser,
|
|
677
|
+
providerId: this.provider,
|
|
678
|
+
},
|
|
679
|
+
operationType,
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
generateUniqueId() {
|
|
683
|
+
// Cryptographically-strong identifier (uid fallback when a provider returns no stable sub).
|
|
684
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
685
|
+
return crypto.randomUUID();
|
|
686
|
+
}
|
|
687
|
+
const bytes = new Uint8Array(16);
|
|
688
|
+
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
|
|
689
|
+
crypto.getRandomValues(bytes);
|
|
690
|
+
}
|
|
691
|
+
let hex = '';
|
|
692
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
693
|
+
hex += bytes[i].toString(16).padStart(2, '0');
|
|
694
|
+
}
|
|
695
|
+
return `${Date.now()}-${hex}`;
|
|
696
|
+
}
|
|
697
|
+
isTokenExpired(expiresAt) {
|
|
698
|
+
if (!expiresAt)
|
|
699
|
+
return false;
|
|
700
|
+
return Date.now() >= expiresAt;
|
|
701
|
+
}
|
|
702
|
+
calculateTokenExpiry(expiresIn) {
|
|
703
|
+
if (!expiresIn) {
|
|
704
|
+
// Default to 1 hour
|
|
705
|
+
expiresIn = 3600;
|
|
706
|
+
}
|
|
707
|
+
return Date.now() + expiresIn * 1000;
|
|
708
|
+
}
|
|
709
|
+
dispose() {
|
|
710
|
+
this.authStateEmitter.clear();
|
|
711
|
+
this.currentUser = null;
|
|
712
|
+
this.isInitialized = false;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const GSI_SRC = 'https://accounts.google.com/gsi/client';
|
|
717
|
+
const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/userinfo';
|
|
718
|
+
const DEFAULT_SCOPES = ['openid', 'email', 'profile'];
|
|
719
|
+
/**
|
|
720
|
+
* Web Google provider — the implementation the registry loads on **web / electron**.
|
|
721
|
+
*
|
|
722
|
+
* Two Google Identity Services flows are available, selected by {@link GoogleAuthOptions.webFlow}
|
|
723
|
+
* (default `'auto'`):
|
|
724
|
+
*
|
|
725
|
+
* 1. **One-Tap / FedCM id-token flow** (`google.accounts.id`): returns a Google **ID token** (JWT) as
|
|
726
|
+
* `result.credential.idToken` — the same field the native providers populate.
|
|
727
|
+
* 2. **OAuth2 popup flow** (`google.accounts.oauth2.initTokenClient`): a deterministic popup that works
|
|
728
|
+
* from any click handler and returns an **access token** as `result.credential.accessToken`; the user
|
|
729
|
+
* profile is read from Google's `userinfo` endpoint. `'auto'` falls back to this whenever the browser
|
|
730
|
+
* does not display One-Tap (cooldown, FedCM opt-out, third-party-cookie settings).
|
|
731
|
+
*
|
|
732
|
+
* Either credential is accepted by Firebase — the handoff is identical on every platform:
|
|
733
|
+
*
|
|
734
|
+
* const { idToken, accessToken } = result.credential;
|
|
735
|
+
* await signInWithCredential(getAuth(), GoogleAuthProvider.credential(idToken ?? null, accessToken));
|
|
736
|
+
*
|
|
737
|
+
* Neither flow needs a client secret or a backend. For Google's official button call
|
|
738
|
+
* {@link renderButton}; it shares the One-Tap credential callback.
|
|
739
|
+
*/
|
|
740
|
+
class GoogleAuthProviderWeb extends BaseAuthProvider {
|
|
741
|
+
constructor(config) {
|
|
742
|
+
super(resolveProviderConfig(AuthProvider.GOOGLE, config));
|
|
743
|
+
this.loadPromise = null;
|
|
744
|
+
/** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
|
|
745
|
+
this.pendingResolve = null;
|
|
746
|
+
this.pendingReject = null;
|
|
747
|
+
/** Last credential issued in this page session (tokens are deliberately not persisted). */
|
|
748
|
+
this.lastCredential = null;
|
|
749
|
+
this.signingIn = false;
|
|
750
|
+
this.pendingTimer = null;
|
|
751
|
+
this.requestRevision = 0;
|
|
752
|
+
this.pendingPopupReject = null;
|
|
753
|
+
}
|
|
754
|
+
get name() {
|
|
755
|
+
return AuthProvider.GOOGLE;
|
|
756
|
+
}
|
|
757
|
+
async initialize() {
|
|
758
|
+
if (this.isInitialized) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
try {
|
|
762
|
+
this.requireClientId();
|
|
763
|
+
await this.loadGsi();
|
|
764
|
+
this.configureIdClient();
|
|
765
|
+
await this.loadCurrentUser();
|
|
766
|
+
this.isInitialized = true;
|
|
767
|
+
this.logger.info('Google (web) provider initialized');
|
|
768
|
+
}
|
|
769
|
+
catch (error) {
|
|
770
|
+
throw AuthError.fromError(error, AuthProvider.GOOGLE);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
async signIn(options) {
|
|
774
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
775
|
+
if (this.signingIn) {
|
|
776
|
+
throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'A Google sign-in is already in progress', AuthProvider.GOOGLE);
|
|
777
|
+
}
|
|
778
|
+
this.signingIn = true;
|
|
779
|
+
try {
|
|
780
|
+
if (!this.isInitialized) {
|
|
781
|
+
await this.initialize();
|
|
782
|
+
}
|
|
783
|
+
// AuthManagerCore spreads per-call options to the top level; direct callers nest them under
|
|
784
|
+
// `options`. Read both shapes.
|
|
785
|
+
const perCall = (options !== null && options !== void 0 ? options : {});
|
|
786
|
+
const flow = (_d = (_c = (_b = (_a = perCall.options) === null || _a === void 0 ? void 0 : _a.webFlow) !== null && _b !== void 0 ? _b : perCall.webFlow) !== null && _c !== void 0 ? _c : this.options.webFlow) !== null && _d !== void 0 ? _d : 'auto';
|
|
787
|
+
const loginHint = (_g = (_f = (_e = perCall.options) === null || _e === void 0 ? void 0 : _e.loginHint) !== null && _f !== void 0 ? _f : perCall.loginHint) !== null && _g !== void 0 ? _g : this.options.loginHint;
|
|
788
|
+
if (flow === 'popup') {
|
|
789
|
+
return await this.signInWithPopup(loginHint);
|
|
790
|
+
}
|
|
791
|
+
return await this.signInWithOneTap(flow === 'auto', loginHint);
|
|
792
|
+
}
|
|
793
|
+
finally {
|
|
794
|
+
this.signingIn = false;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Renders Google's official "Sign in with Google" button into `parent`. Use this when you want
|
|
799
|
+
* Google's branded button rather than your own. It uses the SAME credential callback, so a click
|
|
800
|
+
* resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
|
|
801
|
+
*/
|
|
802
|
+
async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
|
|
803
|
+
if (!this.isInitialized) {
|
|
804
|
+
await this.initialize();
|
|
805
|
+
}
|
|
806
|
+
this.configureIdClient();
|
|
807
|
+
this.requireIdApi().renderButton(parent, options);
|
|
808
|
+
}
|
|
809
|
+
async signOut(_options) {
|
|
810
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
811
|
+
this.requestRevision++;
|
|
812
|
+
(_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
|
|
813
|
+
if (this.pendingReject) {
|
|
814
|
+
this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled by sign-out', AuthProvider.GOOGLE));
|
|
815
|
+
(_d = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.id) === null || _d === void 0 ? void 0 : _d.cancel();
|
|
816
|
+
}
|
|
817
|
+
try {
|
|
818
|
+
(_g = (_f = (_e = window.google) === null || _e === void 0 ? void 0 : _e.accounts) === null || _f === void 0 ? void 0 : _f.id) === null || _g === void 0 ? void 0 : _g.disableAutoSelect();
|
|
819
|
+
}
|
|
820
|
+
catch (error) {
|
|
821
|
+
this.logger.warn('Google disableAutoSelect failed', error);
|
|
822
|
+
}
|
|
823
|
+
this.lastCredential = null;
|
|
824
|
+
await this.clearStoredData();
|
|
825
|
+
await this.setCurrentUser(null);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Web tokens cannot be refreshed silently without a backend — re-running the configured flow
|
|
829
|
+
* (One-Tap auto-select for a returning user, or the popup) re-issues a fresh credential.
|
|
830
|
+
*/
|
|
831
|
+
async refreshToken(_options) {
|
|
832
|
+
return this.signIn();
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Returns the ID token from the current page session. `forceRefresh` (or an expired token) re-runs
|
|
836
|
+
* One-Tap. Throws `NO_AUTH_SESSION` when the last sign-in was the popup flow, which issues no ID token.
|
|
837
|
+
*/
|
|
838
|
+
async getIdToken(forceRefresh = false) {
|
|
839
|
+
const cached = this.lastCredential;
|
|
840
|
+
const expired = typeof (cached === null || cached === void 0 ? void 0 : cached.expiresAt) === 'number' && cached.expiresAt <= Date.now();
|
|
841
|
+
if ((cached === null || cached === void 0 ? void 0 : cached.idToken) && !forceRefresh && !expired) {
|
|
842
|
+
return cached.idToken;
|
|
843
|
+
}
|
|
844
|
+
if (cached && !cached.idToken && !forceRefresh) {
|
|
845
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'The popup flow issues an access token, not an ID token. Use result.credential.accessToken, or sign in with webFlow "one-tap".', AuthProvider.GOOGLE);
|
|
846
|
+
}
|
|
847
|
+
const result = await this.signIn({
|
|
848
|
+
provider: AuthProvider.GOOGLE,
|
|
849
|
+
options: { webFlow: 'one-tap' },
|
|
850
|
+
});
|
|
851
|
+
if (!result.credential.idToken) {
|
|
852
|
+
throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available', AuthProvider.GOOGLE);
|
|
853
|
+
}
|
|
854
|
+
return result.credential.idToken;
|
|
855
|
+
}
|
|
856
|
+
async revokeAccess(token) {
|
|
857
|
+
var _a, _b, _c, _d, _e;
|
|
858
|
+
const accessToken = token !== null && token !== void 0 ? token : (_a = this.lastCredential) === null || _a === void 0 ? void 0 : _a.accessToken;
|
|
859
|
+
const oauth2 = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.oauth2;
|
|
860
|
+
if (accessToken && oauth2) {
|
|
861
|
+
await new Promise((resolve) => {
|
|
862
|
+
try {
|
|
863
|
+
oauth2.revoke(accessToken, () => resolve());
|
|
864
|
+
}
|
|
865
|
+
catch (_a) {
|
|
866
|
+
resolve();
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
await this.signOut();
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
const user = (_d = this.currentUser) !== null && _d !== void 0 ? _d : (await this.getCurrentUser());
|
|
873
|
+
const hint = (_e = user === null || user === void 0 ? void 0 : user.email) !== null && _e !== void 0 ? _e : token;
|
|
874
|
+
if (hint) {
|
|
875
|
+
await new Promise((resolve) => {
|
|
876
|
+
try {
|
|
877
|
+
this.requireIdApi().revoke(hint, () => resolve());
|
|
878
|
+
}
|
|
879
|
+
catch (_a) {
|
|
880
|
+
resolve();
|
|
881
|
+
}
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
await this.signOut();
|
|
885
|
+
}
|
|
886
|
+
async isSupported() {
|
|
887
|
+
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
888
|
+
return false;
|
|
889
|
+
}
|
|
890
|
+
try {
|
|
891
|
+
await this.loadGsi();
|
|
892
|
+
return true;
|
|
893
|
+
}
|
|
894
|
+
catch (_a) {
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
// --- One-Tap flow --------------------------------------------------------------------------------
|
|
899
|
+
signInWithOneTap(fallbackToPopup, loginHint) {
|
|
900
|
+
this.configureIdClient(loginHint);
|
|
901
|
+
return new Promise((resolve, reject) => {
|
|
902
|
+
this.pendingResolve = resolve;
|
|
903
|
+
this.pendingReject = (e) => reject(e);
|
|
904
|
+
this.pendingTimer = setTimeout(() => {
|
|
905
|
+
var _a, _b, _c;
|
|
906
|
+
this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, 'Google One-Tap did not return a credential. Retry from a click with webFlow "popup", or use the Google button.', AuthProvider.GOOGLE));
|
|
907
|
+
(_c = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) === null || _c === void 0 ? void 0 : _c.cancel();
|
|
908
|
+
}, 120000);
|
|
909
|
+
const fallback = (reason) => {
|
|
910
|
+
this.logger.info(`Google One-Tap not shown (${reason}); using the popup flow`);
|
|
911
|
+
// Drop the One-Tap resolvers so a late credential callback cannot double-resolve.
|
|
912
|
+
this.pendingResolve = null;
|
|
913
|
+
this.pendingReject = null;
|
|
914
|
+
this.clearPendingTimer();
|
|
915
|
+
this.signInWithPopup(loginHint).then(resolve, reject);
|
|
916
|
+
};
|
|
917
|
+
try {
|
|
918
|
+
this.requireIdApi().prompt((notification) => {
|
|
919
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
|
|
920
|
+
// These moment methods are deprecated under FedCM and may throw — guard every call.
|
|
921
|
+
try {
|
|
922
|
+
const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
|
|
923
|
+
const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
|
|
924
|
+
if (notDisplayed || skipped) {
|
|
925
|
+
const reason = (_h = (_f = (_e = notification.getNotDisplayedReason) === null || _e === void 0 ? void 0 : _e.call(notification)) !== null && _f !== void 0 ? _f : (_g = notification.getSkippedReason) === null || _g === void 0 ? void 0 : _g.call(notification)) !== null && _h !== void 0 ? _h : 'suppressed';
|
|
926
|
+
if (fallbackToPopup) {
|
|
927
|
+
fallback(reason);
|
|
928
|
+
}
|
|
929
|
+
else {
|
|
930
|
+
this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Use webFlow 'popup' or 'auto', or ` +
|
|
931
|
+
`render Google's button via provider.renderButton(element).`, AuthProvider.GOOGLE));
|
|
932
|
+
}
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const dismissed = (_k = (_j = notification.isDismissedMoment) === null || _j === void 0 ? void 0 : _j.call(notification)) !== null && _k !== void 0 ? _k : false;
|
|
936
|
+
if (dismissed) {
|
|
937
|
+
const reason = (_m = (_l = notification.getDismissedReason) === null || _l === void 0 ? void 0 : _l.call(notification)) !== null && _m !== void 0 ? _m : '';
|
|
938
|
+
// 'credential_returned' is the success path — the credential callback resolves it.
|
|
939
|
+
if (reason !== 'credential_returned') {
|
|
940
|
+
this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, `Google One-Tap was dismissed (${reason || 'cancelled'})`, AuthProvider.GOOGLE));
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
catch (_o) {
|
|
945
|
+
// FedCM: moment methods unavailable — wait for the credential callback instead.
|
|
946
|
+
}
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
catch (error) {
|
|
950
|
+
if (fallbackToPopup) {
|
|
951
|
+
fallback(error instanceof Error ? error.message : 'prompt failed');
|
|
952
|
+
}
|
|
953
|
+
else {
|
|
954
|
+
this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
async handleCredential(response) {
|
|
960
|
+
// Ignore a late callback after cancellation, timeout, or popup fallback.
|
|
961
|
+
if (!this.pendingResolve)
|
|
962
|
+
return;
|
|
963
|
+
if (response.error || !response.credential) {
|
|
964
|
+
this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
|
|
965
|
+
response.error ||
|
|
966
|
+
'No Google ID token returned', AuthProvider.GOOGLE));
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
try {
|
|
970
|
+
const idToken = response.credential;
|
|
971
|
+
const claims = this.validateIdToken(idToken);
|
|
972
|
+
const user = this.buildUser(claims);
|
|
973
|
+
const credential = {
|
|
974
|
+
providerId: 'google.com',
|
|
975
|
+
signInMethod: 'google.com',
|
|
976
|
+
idToken,
|
|
977
|
+
expiresAt: typeof claims.exp === 'number' ? claims.exp * 1000 : undefined,
|
|
978
|
+
tokenType: 'Bearer',
|
|
979
|
+
scope: DEFAULT_SCOPES.join(' '),
|
|
980
|
+
};
|
|
981
|
+
this.lastCredential = credential;
|
|
982
|
+
await this.setCurrentUser(user);
|
|
983
|
+
this.resolvePending(this.createAuthResult(user, credential, false));
|
|
984
|
+
}
|
|
985
|
+
catch (error) {
|
|
986
|
+
this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
// --- OAuth2 popup flow ---------------------------------------------------------------------------
|
|
990
|
+
async signInWithPopup(loginHint) {
|
|
991
|
+
var _a, _b, _c;
|
|
992
|
+
const revision = this.requestRevision;
|
|
993
|
+
const options = this.options;
|
|
994
|
+
const clientId = this.requireClientId();
|
|
995
|
+
await this.loadGsi();
|
|
996
|
+
const oauth2 = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2;
|
|
997
|
+
if (!oauth2) {
|
|
998
|
+
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services OAuth2 client not loaded', AuthProvider.GOOGLE);
|
|
999
|
+
}
|
|
1000
|
+
const scopes = Array.from(new Set([...DEFAULT_SCOPES, ...((_c = options.scopes) !== null && _c !== void 0 ? _c : [])]));
|
|
1001
|
+
const tokenResponse = await new Promise((resolve, reject) => {
|
|
1002
|
+
var _a;
|
|
1003
|
+
let settled = false;
|
|
1004
|
+
const cleanup = () => {
|
|
1005
|
+
settled = true;
|
|
1006
|
+
clearTimeout(timer);
|
|
1007
|
+
this.pendingPopupReject = null;
|
|
1008
|
+
};
|
|
1009
|
+
const resolveToken = (response) => {
|
|
1010
|
+
if (settled)
|
|
1011
|
+
return;
|
|
1012
|
+
cleanup();
|
|
1013
|
+
resolve(response);
|
|
1014
|
+
};
|
|
1015
|
+
const rejectToken = (error) => {
|
|
1016
|
+
if (settled)
|
|
1017
|
+
return;
|
|
1018
|
+
cleanup();
|
|
1019
|
+
reject(error);
|
|
1020
|
+
};
|
|
1021
|
+
const timer = setTimeout(() => rejectToken(new AuthError(AuthErrorCode.POPUP_BLOCKED, 'Google sign-in popup did not return a credential. Retry from a click.', AuthProvider.GOOGLE)), 120000);
|
|
1022
|
+
this.pendingPopupReject = rejectToken;
|
|
1023
|
+
try {
|
|
1024
|
+
const client = oauth2.initTokenClient({
|
|
1025
|
+
client_id: clientId,
|
|
1026
|
+
scope: scopes.join(' '),
|
|
1027
|
+
hint: loginHint,
|
|
1028
|
+
hosted_domain: options.hostedDomain,
|
|
1029
|
+
include_granted_scopes: (_a = options.includeGrantedScopes) !== null && _a !== void 0 ? _a : true,
|
|
1030
|
+
callback: (response) => {
|
|
1031
|
+
if (response.error) {
|
|
1032
|
+
rejectToken(new AuthError(response.error === 'access_denied'
|
|
1033
|
+
? AuthErrorCode.USER_CANCELLED
|
|
1034
|
+
: AuthErrorCode.SIGN_IN_FAILED, response.error_description || response.error, AuthProvider.GOOGLE));
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
resolveToken(response);
|
|
1038
|
+
},
|
|
1039
|
+
error_callback: (error) => {
|
|
1040
|
+
var _a;
|
|
1041
|
+
const type = (_a = error === null || error === void 0 ? void 0 : error.type) !== null && _a !== void 0 ? _a : 'unknown';
|
|
1042
|
+
rejectToken(new AuthError(type === 'popup_closed'
|
|
1043
|
+
? AuthErrorCode.POPUP_CLOSED_BY_USER
|
|
1044
|
+
: type === 'popup_failed_to_open'
|
|
1045
|
+
? AuthErrorCode.POPUP_BLOCKED
|
|
1046
|
+
: AuthErrorCode.SIGN_IN_FAILED, (error === null || error === void 0 ? void 0 : error.message) || `Google sign-in popup failed (${type})`, AuthProvider.GOOGLE));
|
|
1047
|
+
},
|
|
1048
|
+
});
|
|
1049
|
+
client.requestAccessToken({
|
|
1050
|
+
prompt: options.autoSelectEnabled ? '' : 'select_account',
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
catch (error) {
|
|
1054
|
+
rejectToken(AuthError.fromError(error, AuthProvider.GOOGLE));
|
|
1055
|
+
}
|
|
1056
|
+
});
|
|
1057
|
+
const accessToken = tokenResponse.access_token;
|
|
1058
|
+
if (!accessToken) {
|
|
1059
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, 'Google returned no access token', AuthProvider.GOOGLE);
|
|
1060
|
+
}
|
|
1061
|
+
const profile = await this.fetchUserInfo(accessToken);
|
|
1062
|
+
if (revision !== this.requestRevision) {
|
|
1063
|
+
throw new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE);
|
|
1064
|
+
}
|
|
1065
|
+
if (typeof profile.sub !== 'string' || !profile.sub) {
|
|
1066
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google userinfo is missing a subject', AuthProvider.GOOGLE);
|
|
1067
|
+
}
|
|
1068
|
+
if (options.hostedDomain && profile.hd !== options.hostedDomain) {
|
|
1069
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Account is not in the required Google Workspace domain (${options.hostedDomain})`, AuthProvider.GOOGLE);
|
|
1070
|
+
}
|
|
1071
|
+
const user = this.buildUser(profile);
|
|
1072
|
+
const expiresIn = Number(tokenResponse.expires_in);
|
|
1073
|
+
const credential = {
|
|
1074
|
+
providerId: 'google.com',
|
|
1075
|
+
signInMethod: 'google.com',
|
|
1076
|
+
accessToken,
|
|
1077
|
+
expiresAt: this.calculateTokenExpiry(Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined),
|
|
1078
|
+
tokenType: tokenResponse.token_type || 'Bearer',
|
|
1079
|
+
scope: tokenResponse.scope || scopes.join(' '),
|
|
1080
|
+
};
|
|
1081
|
+
this.lastCredential = credential;
|
|
1082
|
+
await this.setCurrentUser(user);
|
|
1083
|
+
return this.createAuthResult(user, credential, false);
|
|
1084
|
+
}
|
|
1085
|
+
async fetchUserInfo(accessToken) {
|
|
1086
|
+
let response;
|
|
1087
|
+
try {
|
|
1088
|
+
response = await fetch(USERINFO_ENDPOINT, {
|
|
1089
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
1090
|
+
signal: AbortSignal.timeout(15000),
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
catch (error) {
|
|
1094
|
+
throw new AuthError(AuthErrorCode.NETWORK_ERROR, `Could not reach Google userinfo: ${error instanceof Error ? error.message : String(error)}`, AuthProvider.GOOGLE);
|
|
1095
|
+
}
|
|
1096
|
+
if (!response.ok) {
|
|
1097
|
+
throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Google userinfo request failed (${response.status})`, AuthProvider.GOOGLE);
|
|
1098
|
+
}
|
|
1099
|
+
return (await response.json());
|
|
1100
|
+
}
|
|
1101
|
+
// --- internals -----------------------------------------------------------------------------------
|
|
1102
|
+
requireClientId() {
|
|
1103
|
+
const options = this.options;
|
|
1104
|
+
if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
|
|
1105
|
+
throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
|
|
1106
|
+
}
|
|
1107
|
+
return options.clientId;
|
|
1108
|
+
}
|
|
1109
|
+
requireIdApi() {
|
|
1110
|
+
var _a, _b;
|
|
1111
|
+
const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
|
|
1112
|
+
if (!api) {
|
|
1113
|
+
throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services not loaded', AuthProvider.GOOGLE);
|
|
1114
|
+
}
|
|
1115
|
+
return api;
|
|
1116
|
+
}
|
|
1117
|
+
configureIdClient(loginHint) {
|
|
1118
|
+
var _a;
|
|
1119
|
+
const options = this.options;
|
|
1120
|
+
const clientId = this.requireClientId();
|
|
1121
|
+
this.currentNonce = options.nonce;
|
|
1122
|
+
const config = {
|
|
1123
|
+
client_id: clientId,
|
|
1124
|
+
callback: (response) => this.handleCredential(response),
|
|
1125
|
+
auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
|
|
1126
|
+
cancel_on_tap_outside: false,
|
|
1127
|
+
context: 'signin',
|
|
1128
|
+
use_fedcm_for_prompt: true,
|
|
1129
|
+
itp_support: true,
|
|
1130
|
+
};
|
|
1131
|
+
if (options.nonce) {
|
|
1132
|
+
config.nonce = options.nonce;
|
|
1133
|
+
}
|
|
1134
|
+
const hint = loginHint !== null && loginHint !== void 0 ? loginHint : options.loginHint;
|
|
1135
|
+
if (hint) {
|
|
1136
|
+
config.login_hint = hint;
|
|
1137
|
+
}
|
|
1138
|
+
if (options.hostedDomain) {
|
|
1139
|
+
config.hd = options.hostedDomain;
|
|
1140
|
+
}
|
|
1141
|
+
this.requireIdApi().initialize(config);
|
|
1142
|
+
}
|
|
1143
|
+
validateIdToken(idToken) {
|
|
1144
|
+
let claims;
|
|
1145
|
+
try {
|
|
1146
|
+
claims = decodeJwtPayload(idToken);
|
|
1147
|
+
if (!claims || typeof claims !== 'object' || Array.isArray(claims))
|
|
1148
|
+
throw new Error('Invalid claims');
|
|
1149
|
+
}
|
|
1150
|
+
catch (_a) {
|
|
1151
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
|
|
1152
|
+
}
|
|
1153
|
+
const options = this.options;
|
|
1154
|
+
const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
|
|
1155
|
+
if (!claims.iss || !validIssuers.includes(claims.iss)) {
|
|
1156
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, `Unexpected ID token issuer: ${claims.iss}`, AuthProvider.GOOGLE);
|
|
1157
|
+
}
|
|
1158
|
+
if (claims.aud !== options.clientId) {
|
|
1159
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', AuthProvider.GOOGLE);
|
|
1160
|
+
}
|
|
1161
|
+
if (typeof claims.exp !== 'number' ||
|
|
1162
|
+
!Number.isFinite(claims.exp) ||
|
|
1163
|
+
typeof claims.sub !== 'string' ||
|
|
1164
|
+
!claims.sub) {
|
|
1165
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token is missing required exp or sub claims', AuthProvider.GOOGLE);
|
|
1166
|
+
}
|
|
1167
|
+
if (claims.exp * 1000 <= Date.now()) {
|
|
1168
|
+
throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', AuthProvider.GOOGLE);
|
|
1169
|
+
}
|
|
1170
|
+
// Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
|
|
1171
|
+
if (this.currentNonce && claims.nonce !== this.currentNonce) {
|
|
1172
|
+
throw new AuthError(AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', AuthProvider.GOOGLE);
|
|
1173
|
+
}
|
|
1174
|
+
if (options.hostedDomain && claims.hd !== options.hostedDomain) {
|
|
1175
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token does not match the required Workspace domain', AuthProvider.GOOGLE);
|
|
1176
|
+
}
|
|
1177
|
+
return claims;
|
|
1178
|
+
}
|
|
1179
|
+
buildUser(claims) {
|
|
1180
|
+
var _a, _b;
|
|
1181
|
+
const uid = claims.sub || this.generateUniqueId();
|
|
1182
|
+
const email = (_a = claims.email) !== null && _a !== void 0 ? _a : null;
|
|
1183
|
+
const emailVerified = claims.email_verified === true || claims.email_verified === 'true';
|
|
1184
|
+
const displayName = claims.name ||
|
|
1185
|
+
[claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
|
|
1186
|
+
null;
|
|
1187
|
+
const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
|
|
1188
|
+
const now = new Date().toISOString();
|
|
1189
|
+
return {
|
|
1190
|
+
uid,
|
|
1191
|
+
email,
|
|
1192
|
+
emailVerified,
|
|
1193
|
+
displayName,
|
|
1194
|
+
photoURL,
|
|
1195
|
+
phoneNumber: null,
|
|
1196
|
+
isAnonymous: false,
|
|
1197
|
+
tenantId: null,
|
|
1198
|
+
providerData: [
|
|
1199
|
+
{
|
|
1200
|
+
providerId: 'google.com',
|
|
1201
|
+
uid,
|
|
1202
|
+
displayName,
|
|
1203
|
+
email,
|
|
1204
|
+
phoneNumber: null,
|
|
1205
|
+
photoURL,
|
|
1206
|
+
},
|
|
1207
|
+
],
|
|
1208
|
+
metadata: {
|
|
1209
|
+
creationTime: now,
|
|
1210
|
+
lastSignInTime: now,
|
|
1211
|
+
},
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
resolvePending(result) {
|
|
1215
|
+
this.clearPendingTimer();
|
|
1216
|
+
const resolve = this.pendingResolve;
|
|
1217
|
+
this.pendingResolve = null;
|
|
1218
|
+
this.pendingReject = null;
|
|
1219
|
+
resolve === null || resolve === void 0 ? void 0 : resolve(result);
|
|
1220
|
+
}
|
|
1221
|
+
rejectPending(error) {
|
|
1222
|
+
this.clearPendingTimer();
|
|
1223
|
+
const reject = this.pendingReject;
|
|
1224
|
+
this.pendingResolve = null;
|
|
1225
|
+
this.pendingReject = null;
|
|
1226
|
+
if (reject) {
|
|
1227
|
+
reject(error);
|
|
1228
|
+
}
|
|
1229
|
+
else {
|
|
1230
|
+
this.logger.error('Google sign-in error with no pending request', error);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
clearPendingTimer() {
|
|
1234
|
+
if (this.pendingTimer !== null)
|
|
1235
|
+
clearTimeout(this.pendingTimer);
|
|
1236
|
+
this.pendingTimer = null;
|
|
1237
|
+
}
|
|
1238
|
+
dispose() {
|
|
1239
|
+
var _a, _b, _c, _d;
|
|
1240
|
+
this.requestRevision++;
|
|
1241
|
+
(_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
|
|
1242
|
+
if (this.pendingReject) {
|
|
1243
|
+
this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was disposed', AuthProvider.GOOGLE));
|
|
1244
|
+
(_d = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.id) === null || _d === void 0 ? void 0 : _d.cancel();
|
|
1245
|
+
}
|
|
1246
|
+
this.lastCredential = null;
|
|
1247
|
+
super.dispose();
|
|
1248
|
+
}
|
|
1249
|
+
loadGsi() {
|
|
1250
|
+
var _a, _b;
|
|
1251
|
+
if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
|
|
1252
|
+
return Promise.resolve();
|
|
1253
|
+
}
|
|
1254
|
+
if (this.loadPromise) {
|
|
1255
|
+
return this.loadPromise;
|
|
1256
|
+
}
|
|
1257
|
+
this.loadPromise = new Promise((resolve, reject) => {
|
|
1258
|
+
const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
|
|
1259
|
+
const script = existing !== null && existing !== void 0 ? existing : document.createElement('script');
|
|
1260
|
+
const cleanup = () => {
|
|
1261
|
+
clearTimeout(timer);
|
|
1262
|
+
script.removeEventListener('load', onReady);
|
|
1263
|
+
script.removeEventListener('error', onError);
|
|
1264
|
+
};
|
|
1265
|
+
const onReady = () => {
|
|
1266
|
+
var _a, _b;
|
|
1267
|
+
cleanup();
|
|
1268
|
+
if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
|
|
1269
|
+
resolve();
|
|
1270
|
+
else {
|
|
1271
|
+
if (!existing)
|
|
1272
|
+
script.remove();
|
|
1273
|
+
reject(new Error('Google Identity Services failed to load'));
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
const onError = () => {
|
|
1277
|
+
cleanup();
|
|
1278
|
+
if (!existing)
|
|
1279
|
+
script.remove();
|
|
1280
|
+
reject(new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to load Google Identity Services', AuthProvider.GOOGLE));
|
|
1281
|
+
};
|
|
1282
|
+
const timer = setTimeout(onError, 15000);
|
|
1283
|
+
script.addEventListener('load', onReady, { once: true });
|
|
1284
|
+
script.addEventListener('error', onError, { once: true });
|
|
1285
|
+
if (!existing) {
|
|
1286
|
+
script.src = GSI_SRC;
|
|
1287
|
+
script.async = true;
|
|
1288
|
+
script.defer = true;
|
|
1289
|
+
document.head.appendChild(script);
|
|
1290
|
+
}
|
|
1291
|
+
}).finally(() => {
|
|
1292
|
+
this.loadPromise = null;
|
|
1293
|
+
});
|
|
1294
|
+
return this.loadPromise;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
/** Decodes a JWT payload (no signature verification — Google issues the token directly to this origin). */
|
|
1298
|
+
function decodeJwtPayload(jwt) {
|
|
1299
|
+
const parts = jwt.split('.');
|
|
1300
|
+
if (parts.length !== 3) {
|
|
1301
|
+
throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
|
|
1302
|
+
}
|
|
1303
|
+
if (typeof atob !== 'function') {
|
|
1304
|
+
throw new AuthError(AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', AuthProvider.GOOGLE);
|
|
1305
|
+
}
|
|
1306
|
+
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
1307
|
+
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
1308
|
+
const binary = atob(padded);
|
|
1309
|
+
const bytes = new Uint8Array(binary.length);
|
|
1310
|
+
for (let i = 0; i < binary.length; i++) {
|
|
1311
|
+
bytes[i] = binary.charCodeAt(i);
|
|
1312
|
+
}
|
|
1313
|
+
const json = new TextDecoder().decode(bytes);
|
|
1314
|
+
return JSON.parse(json);
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
exports.GoogleAuthProviderWeb = GoogleAuthProviderWeb;
|