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.
Files changed (86) hide show
  1. package/AI-INTEGRATION-GUIDE.md +176 -0
  2. package/CHANGELOG.md +143 -0
  3. package/CapacitorAuthManager.podspec +3 -3
  4. package/README.md +99 -76
  5. package/android/build.gradle +23 -25
  6. package/android/consumer-rules.pro +14 -0
  7. package/android/proguard-rules.pro +5 -30
  8. package/android/src/main/AndroidManifest.xml +4 -9
  9. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ActivityLauncher.java +26 -0
  10. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthErrorCodes.java +32 -0
  11. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthException.java +34 -0
  12. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +46 -25
  13. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +62 -40
  14. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +124 -66
  15. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +225 -374
  16. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleCredentialManagerSignIn.java +175 -0
  17. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleLegacySignIn.java +133 -0
  18. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleProfileCallback.java +8 -0
  19. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleResultMapper.java +158 -0
  20. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +11 -3
  21. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/SigningDiagnostics.java +76 -0
  22. package/dist/angular.cjs.js +421 -3376
  23. package/dist/core.cjs.js +589 -149
  24. package/dist/esm/angular/auth.guard.d.ts +1 -1
  25. package/dist/esm/angular/auth.module.d.ts +1 -1
  26. package/dist/esm/angular/auth.module.js +1 -1
  27. package/dist/esm/angular/auth.service.d.ts +2 -2
  28. package/dist/esm/angular/auth.service.js +1 -1
  29. package/dist/esm/angular/index.d.ts +4 -4
  30. package/dist/esm/angular/index.js +4 -4
  31. package/dist/esm/capacitor-plugin.d.ts +2 -3
  32. package/dist/esm/capacitor-plugin.js +14 -4
  33. package/dist/esm/core/auth-manager.d.ts +20 -2
  34. package/dist/esm/core/auth-manager.js +68 -12
  35. package/dist/esm/core/index.d.ts +5 -4
  36. package/dist/esm/core/index.js +5 -4
  37. package/dist/esm/core/provider-manifests.d.ts +1 -1
  38. package/dist/esm/core/provider-manifests.js +12 -13
  39. package/dist/esm/core/provider-registry.d.ts +8 -5
  40. package/dist/esm/core/provider-registry.js +41 -10
  41. package/dist/esm/core/types.d.ts +2 -2
  42. package/dist/esm/definitions.d.ts +29 -0
  43. package/dist/esm/index.d.ts +12 -12
  44. package/dist/esm/index.js +7 -7
  45. package/dist/esm/package.json +1 -0
  46. package/dist/esm/providers/base-provider.d.ts +7 -8
  47. package/dist/esm/providers/base-provider.js +7 -8
  48. package/dist/esm/providers/native/google-native-provider.d.ts +13 -2
  49. package/dist/esm/providers/native/google-native-provider.js +50 -6
  50. package/dist/esm/providers/oauth-provider.d.ts +2 -2
  51. package/dist/esm/providers/oauth-provider.js +3 -3
  52. package/dist/esm/providers/provider-factory.d.ts +5 -5
  53. package/dist/esm/providers/provider-factory.js +2 -2
  54. package/dist/esm/providers/web/google-provider.d.ts +74 -18
  55. package/dist/esm/providers/web/google-provider.js +391 -117
  56. package/dist/esm/providers/web/index.d.ts +1 -1
  57. package/dist/esm/providers/web/index.js +1 -1
  58. package/dist/esm/react/hooks.d.ts +2 -2
  59. package/dist/esm/react/hooks.js +2 -2
  60. package/dist/esm/react/index.d.ts +3 -3
  61. package/dist/esm/react/index.js +3 -3
  62. package/dist/esm/react/types.d.ts +1 -1
  63. package/dist/esm/utils/auth-error.d.ts +1 -1
  64. package/dist/esm/utils/auth-error.js +1 -1
  65. package/dist/esm/utils/event-emitter.d.ts +1 -1
  66. package/dist/esm/utils/event-emitter.js +1 -1
  67. package/dist/esm/utils/pending-verification-store.js +1 -1
  68. package/dist/esm/utils/storage.d.ts +2 -2
  69. package/dist/esm/utils/storage.js +31 -7
  70. package/dist/esm/vue/composables.d.ts +2 -2
  71. package/dist/esm/vue/composables.js +1 -1
  72. package/dist/esm/vue/index.d.ts +2 -2
  73. package/dist/esm/vue/index.js +2 -2
  74. package/dist/esm/web.d.ts +1 -1
  75. package/dist/esm/web.js +6 -6
  76. package/dist/plugin.cjs.js +291 -2771
  77. package/dist/plugin.js +585 -147
  78. package/dist/providers-web.cjs.js +1317 -0
  79. package/dist/react.cjs.js +310 -3265
  80. package/dist/vue.cjs.js +266 -3221
  81. package/ios/Plugin/AuthStorage.swift +3 -1
  82. package/ios/Plugin/GoogleAuthProvider.swift +7 -4
  83. package/ios/Plugin/Models.swift +28 -0
  84. package/ios/Plugin/Plugin.swift +64 -40
  85. package/package.json +54 -32
  86. package/scripts/configure.js +71 -325
@@ -1,28 +1,43 @@
1
- import { AuthProvider, AuthErrorCode, } from '../../definitions';
2
- import { BaseAuthProvider } from '../base-provider';
3
- import { AuthError } from '../../utils/auth-error';
1
+ import { AuthProvider, AuthErrorCode, } from '../../definitions.js';
2
+ import { BaseAuthProvider, resolveProviderConfig } from '../base-provider.js';
3
+ import { AuthError } from '../../utils/auth-error.js';
4
4
  const GSI_SRC = 'https://accounts.google.com/gsi/client';
5
+ const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/userinfo';
6
+ const DEFAULT_SCOPES = ['openid', 'email', 'profile'];
5
7
  /**
6
8
  * Web Google provider — the implementation the registry loads on **web / electron**.
7
9
  *
8
- * Uses the **Google Identity Services ID-token flow** (`google.accounts.id`): no client secret, no
9
- * backend, no popup-blocker problems. The browser returns a Google **ID token** (JWT) which is
10
- * surfaced as `result.credential.idToken` — the SAME field the native providers populate — so the
11
- * Firebase handoff is identical on every platform:
10
+ * Two Google Identity Services flows are available, selected by {@link GoogleAuthOptions.webFlow}
11
+ * (default `'auto'`):
12
12
  *
13
- * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(result.credential.idToken));
13
+ * 1. **One-Tap / FedCM id-token flow** (`google.accounts.id`): returns a Google **ID token** (JWT) as
14
+ * `result.credential.idToken` — the same field the native providers populate.
15
+ * 2. **OAuth2 popup flow** (`google.accounts.oauth2.initTokenClient`): a deterministic popup that works
16
+ * from any click handler and returns an **access token** as `result.credential.accessToken`; the user
17
+ * profile is read from Google's `userinfo` endpoint. `'auto'` falls back to this whenever the browser
18
+ * does not display One-Tap (cooldown, FedCM opt-out, third-party-cookie settings).
14
19
  *
15
- * The id-token flow does NOT return an OAuth `accessToken` (use the GIS token client separately if you
16
- * need to call Google APIs from the browser). Sign-in is triggered via One-Tap / FedCM `prompt()`; for a
17
- * guaranteed button UX call {@link renderButton} to render Google's official button (same callback).
20
+ * Either credential is accepted by Firebase — the handoff is identical on every platform:
21
+ *
22
+ * const { idToken, accessToken } = result.credential;
23
+ * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(idToken ?? null, accessToken));
24
+ *
25
+ * Neither flow needs a client secret or a backend. For Google's official button call
26
+ * {@link renderButton}; it shares the One-Tap credential callback.
18
27
  */
19
28
  export class GoogleAuthProviderWeb extends BaseAuthProvider {
20
29
  constructor(config) {
21
- super(config);
30
+ super(resolveProviderConfig(AuthProvider.GOOGLE, config));
22
31
  this.loadPromise = null;
23
32
  /** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
24
33
  this.pendingResolve = null;
25
34
  this.pendingReject = null;
35
+ /** Last credential issued in this page session (tokens are deliberately not persisted). */
36
+ this.lastCredential = null;
37
+ this.signingIn = false;
38
+ this.pendingTimer = null;
39
+ this.requestRevision = 0;
40
+ this.pendingPopupReject = null;
26
41
  }
27
42
  get name() {
28
43
  return AuthProvider.GOOGLE;
@@ -32,6 +47,7 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
32
47
  return;
33
48
  }
34
49
  try {
50
+ this.requireClientId();
35
51
  await this.loadGsi();
36
52
  this.configureIdClient();
37
53
  await this.loadCurrentUser();
@@ -42,45 +58,34 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
42
58
  throw AuthError.fromError(error, AuthProvider.GOOGLE);
43
59
  }
44
60
  }
45
- async signIn(_options) {
46
- if (!this.isInitialized) {
47
- await this.initialize();
61
+ async signIn(options) {
62
+ var _a, _b, _c, _d, _e, _f, _g;
63
+ if (this.signingIn) {
64
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'A Google sign-in is already in progress', AuthProvider.GOOGLE);
48
65
  }
49
- this.configureIdClient();
50
- return new Promise((resolve, reject) => {
51
- this.pendingResolve = resolve;
52
- this.pendingReject = (e) => reject(e);
53
- const api = this.requireIdApi();
54
- try {
55
- api.prompt((notification) => {
56
- var _a, _b, _c, _d, _e, _f, _g, _h;
57
- // One-Tap was suppressed (cooldown / dismissed / FedCM opt-out): fail clearly so the
58
- // consumer can fall back to renderButton(). Wrapped in try/catch because these moment
59
- // methods are deprecated under FedCM and may throw.
60
- try {
61
- const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
62
- const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
63
- if (notDisplayed || skipped) {
64
- 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';
65
- this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Render the Google button via ` +
66
- `provider.renderButton(element) for a guaranteed sign-in UI, or sign in on web ` +
67
- `with your own Firebase popup.`, AuthProvider.GOOGLE));
68
- }
69
- }
70
- catch (_j) {
71
- // FedCM: moment methods unavailable — wait for the credential callback instead.
72
- }
73
- });
66
+ this.signingIn = true;
67
+ try {
68
+ if (!this.isInitialized) {
69
+ await this.initialize();
74
70
  }
75
- catch (error) {
76
- this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
71
+ // AuthManagerCore spreads per-call options to the top level; direct callers nest them under
72
+ // `options`. Read both shapes.
73
+ const perCall = (options !== null && options !== void 0 ? options : {});
74
+ 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';
75
+ 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;
76
+ if (flow === 'popup') {
77
+ return await this.signInWithPopup(loginHint);
77
78
  }
78
- });
79
+ return await this.signInWithOneTap(flow === 'auto', loginHint);
80
+ }
81
+ finally {
82
+ this.signingIn = false;
83
+ }
79
84
  }
80
85
  /**
81
- * Renders Google's official "Sign in with Google" button into `parent`. Use this when One-Tap is
82
- * suppressed or you want a deterministic button. The button uses the SAME credential callback, so a
83
- * click resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
86
+ * Renders Google's official "Sign in with Google" button into `parent`. Use this when you want
87
+ * Google's branded button rather than your own. It uses the SAME credential callback, so a click
88
+ * resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
84
89
  */
85
90
  async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
86
91
  if (!this.isInitialized) {
@@ -90,39 +95,80 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
90
95
  this.requireIdApi().renderButton(parent, options);
91
96
  }
92
97
  async signOut(_options) {
93
- var _a, _b, _c;
98
+ var _a, _b, _c, _d, _e, _f, _g;
99
+ this.requestRevision++;
100
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
101
+ if (this.pendingReject) {
102
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled by sign-out', AuthProvider.GOOGLE));
103
+ (_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();
104
+ }
94
105
  try {
95
- (_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.disableAutoSelect();
106
+ (_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();
96
107
  }
97
108
  catch (error) {
98
109
  this.logger.warn('Google disableAutoSelect failed', error);
99
110
  }
111
+ this.lastCredential = null;
100
112
  await this.clearStoredData();
101
113
  await this.setCurrentUser(null);
102
114
  }
103
115
  /**
104
- * Web ID tokens cannot be refreshed silently — re-running One-Tap (with auto-select) re-issues a
105
- * fresh ID token for a returning user. Falls back to a normal prompt if auto-select can't.
116
+ * Web tokens cannot be refreshed silently without a backend — re-running the configured flow
117
+ * (One-Tap auto-select for a returning user, or the popup) re-issues a fresh credential.
106
118
  */
107
119
  async refreshToken(_options) {
108
120
  return this.signIn();
109
121
  }
122
+ /**
123
+ * Returns the ID token from the current page session. `forceRefresh` (or an expired token) re-runs
124
+ * One-Tap. Throws `NO_AUTH_SESSION` when the last sign-in was the popup flow, which issues no ID token.
125
+ */
126
+ async getIdToken(forceRefresh = false) {
127
+ const cached = this.lastCredential;
128
+ const expired = typeof (cached === null || cached === void 0 ? void 0 : cached.expiresAt) === 'number' && cached.expiresAt <= Date.now();
129
+ if ((cached === null || cached === void 0 ? void 0 : cached.idToken) && !forceRefresh && !expired) {
130
+ return cached.idToken;
131
+ }
132
+ if (cached && !cached.idToken && !forceRefresh) {
133
+ 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);
134
+ }
135
+ const result = await this.signIn({
136
+ provider: AuthProvider.GOOGLE,
137
+ options: { webFlow: 'one-tap' },
138
+ });
139
+ if (!result.credential.idToken) {
140
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available', AuthProvider.GOOGLE);
141
+ }
142
+ return result.credential.idToken;
143
+ }
110
144
  async revokeAccess(token) {
111
- var _a, _b;
112
- const user = (_a = this.currentUser) !== null && _a !== void 0 ? _a : (await this.getCurrentUser());
113
- const hint = (_b = user === null || user === void 0 ? void 0 : user.email) !== null && _b !== void 0 ? _b : token;
114
- if (!hint) {
145
+ var _a, _b, _c, _d, _e;
146
+ const accessToken = token !== null && token !== void 0 ? token : (_a = this.lastCredential) === null || _a === void 0 ? void 0 : _a.accessToken;
147
+ const oauth2 = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.oauth2;
148
+ if (accessToken && oauth2) {
149
+ await new Promise((resolve) => {
150
+ try {
151
+ oauth2.revoke(accessToken, () => resolve());
152
+ }
153
+ catch (_a) {
154
+ resolve();
155
+ }
156
+ });
115
157
  await this.signOut();
116
158
  return;
117
159
  }
118
- await new Promise((resolve) => {
119
- try {
120
- this.requireIdApi().revoke(hint, () => resolve());
121
- }
122
- catch (_a) {
123
- resolve();
124
- }
125
- });
160
+ const user = (_d = this.currentUser) !== null && _d !== void 0 ? _d : (await this.getCurrentUser());
161
+ const hint = (_e = user === null || user === void 0 ? void 0 : user.email) !== null && _e !== void 0 ? _e : token;
162
+ if (hint) {
163
+ await new Promise((resolve) => {
164
+ try {
165
+ this.requireIdApi().revoke(hint, () => resolve());
166
+ }
167
+ catch (_a) {
168
+ resolve();
169
+ }
170
+ });
171
+ }
126
172
  await this.signOut();
127
173
  }
128
174
  async isSupported() {
@@ -137,7 +183,217 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
137
183
  return false;
138
184
  }
139
185
  }
140
- // --- internals --------------------------------------------------------------------------------
186
+ // --- One-Tap flow --------------------------------------------------------------------------------
187
+ signInWithOneTap(fallbackToPopup, loginHint) {
188
+ this.configureIdClient(loginHint);
189
+ return new Promise((resolve, reject) => {
190
+ this.pendingResolve = resolve;
191
+ this.pendingReject = (e) => reject(e);
192
+ this.pendingTimer = setTimeout(() => {
193
+ var _a, _b, _c;
194
+ 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));
195
+ (_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();
196
+ }, 120000);
197
+ const fallback = (reason) => {
198
+ this.logger.info(`Google One-Tap not shown (${reason}); using the popup flow`);
199
+ // Drop the One-Tap resolvers so a late credential callback cannot double-resolve.
200
+ this.pendingResolve = null;
201
+ this.pendingReject = null;
202
+ this.clearPendingTimer();
203
+ this.signInWithPopup(loginHint).then(resolve, reject);
204
+ };
205
+ try {
206
+ this.requireIdApi().prompt((notification) => {
207
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
208
+ // These moment methods are deprecated under FedCM and may throw — guard every call.
209
+ try {
210
+ const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
211
+ const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
212
+ if (notDisplayed || skipped) {
213
+ 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';
214
+ if (fallbackToPopup) {
215
+ fallback(reason);
216
+ }
217
+ else {
218
+ this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Use webFlow 'popup' or 'auto', or ` +
219
+ `render Google's button via provider.renderButton(element).`, AuthProvider.GOOGLE));
220
+ }
221
+ return;
222
+ }
223
+ const dismissed = (_k = (_j = notification.isDismissedMoment) === null || _j === void 0 ? void 0 : _j.call(notification)) !== null && _k !== void 0 ? _k : false;
224
+ if (dismissed) {
225
+ const reason = (_m = (_l = notification.getDismissedReason) === null || _l === void 0 ? void 0 : _l.call(notification)) !== null && _m !== void 0 ? _m : '';
226
+ // 'credential_returned' is the success path — the credential callback resolves it.
227
+ if (reason !== 'credential_returned') {
228
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, `Google One-Tap was dismissed (${reason || 'cancelled'})`, AuthProvider.GOOGLE));
229
+ }
230
+ }
231
+ }
232
+ catch (_o) {
233
+ // FedCM: moment methods unavailable — wait for the credential callback instead.
234
+ }
235
+ });
236
+ }
237
+ catch (error) {
238
+ if (fallbackToPopup) {
239
+ fallback(error instanceof Error ? error.message : 'prompt failed');
240
+ }
241
+ else {
242
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
243
+ }
244
+ }
245
+ });
246
+ }
247
+ async handleCredential(response) {
248
+ // Ignore a late callback after cancellation, timeout, or popup fallback.
249
+ if (!this.pendingResolve)
250
+ return;
251
+ if (response.error || !response.credential) {
252
+ this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
253
+ response.error ||
254
+ 'No Google ID token returned', AuthProvider.GOOGLE));
255
+ return;
256
+ }
257
+ try {
258
+ const idToken = response.credential;
259
+ const claims = this.validateIdToken(idToken);
260
+ const user = this.buildUser(claims);
261
+ const credential = {
262
+ providerId: 'google.com',
263
+ signInMethod: 'google.com',
264
+ idToken,
265
+ expiresAt: typeof claims.exp === 'number' ? claims.exp * 1000 : undefined,
266
+ tokenType: 'Bearer',
267
+ scope: DEFAULT_SCOPES.join(' '),
268
+ };
269
+ this.lastCredential = credential;
270
+ await this.setCurrentUser(user);
271
+ this.resolvePending(this.createAuthResult(user, credential, false));
272
+ }
273
+ catch (error) {
274
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
275
+ }
276
+ }
277
+ // --- OAuth2 popup flow ---------------------------------------------------------------------------
278
+ async signInWithPopup(loginHint) {
279
+ var _a, _b, _c;
280
+ const revision = this.requestRevision;
281
+ const options = this.options;
282
+ const clientId = this.requireClientId();
283
+ await this.loadGsi();
284
+ const oauth2 = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2;
285
+ if (!oauth2) {
286
+ throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services OAuth2 client not loaded', AuthProvider.GOOGLE);
287
+ }
288
+ const scopes = Array.from(new Set([...DEFAULT_SCOPES, ...((_c = options.scopes) !== null && _c !== void 0 ? _c : [])]));
289
+ const tokenResponse = await new Promise((resolve, reject) => {
290
+ var _a;
291
+ let settled = false;
292
+ const cleanup = () => {
293
+ settled = true;
294
+ clearTimeout(timer);
295
+ this.pendingPopupReject = null;
296
+ };
297
+ const resolveToken = (response) => {
298
+ if (settled)
299
+ return;
300
+ cleanup();
301
+ resolve(response);
302
+ };
303
+ const rejectToken = (error) => {
304
+ if (settled)
305
+ return;
306
+ cleanup();
307
+ reject(error);
308
+ };
309
+ 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);
310
+ this.pendingPopupReject = rejectToken;
311
+ try {
312
+ const client = oauth2.initTokenClient({
313
+ client_id: clientId,
314
+ scope: scopes.join(' '),
315
+ hint: loginHint,
316
+ hosted_domain: options.hostedDomain,
317
+ include_granted_scopes: (_a = options.includeGrantedScopes) !== null && _a !== void 0 ? _a : true,
318
+ callback: (response) => {
319
+ if (response.error) {
320
+ rejectToken(new AuthError(response.error === 'access_denied'
321
+ ? AuthErrorCode.USER_CANCELLED
322
+ : AuthErrorCode.SIGN_IN_FAILED, response.error_description || response.error, AuthProvider.GOOGLE));
323
+ return;
324
+ }
325
+ resolveToken(response);
326
+ },
327
+ error_callback: (error) => {
328
+ var _a;
329
+ const type = (_a = error === null || error === void 0 ? void 0 : error.type) !== null && _a !== void 0 ? _a : 'unknown';
330
+ rejectToken(new AuthError(type === 'popup_closed'
331
+ ? AuthErrorCode.POPUP_CLOSED_BY_USER
332
+ : type === 'popup_failed_to_open'
333
+ ? AuthErrorCode.POPUP_BLOCKED
334
+ : AuthErrorCode.SIGN_IN_FAILED, (error === null || error === void 0 ? void 0 : error.message) || `Google sign-in popup failed (${type})`, AuthProvider.GOOGLE));
335
+ },
336
+ });
337
+ client.requestAccessToken({
338
+ prompt: options.autoSelectEnabled ? '' : 'select_account',
339
+ });
340
+ }
341
+ catch (error) {
342
+ rejectToken(AuthError.fromError(error, AuthProvider.GOOGLE));
343
+ }
344
+ });
345
+ const accessToken = tokenResponse.access_token;
346
+ if (!accessToken) {
347
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, 'Google returned no access token', AuthProvider.GOOGLE);
348
+ }
349
+ const profile = await this.fetchUserInfo(accessToken);
350
+ if (revision !== this.requestRevision) {
351
+ throw new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE);
352
+ }
353
+ if (typeof profile.sub !== 'string' || !profile.sub) {
354
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google userinfo is missing a subject', AuthProvider.GOOGLE);
355
+ }
356
+ if (options.hostedDomain && profile.hd !== options.hostedDomain) {
357
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Account is not in the required Google Workspace domain (${options.hostedDomain})`, AuthProvider.GOOGLE);
358
+ }
359
+ const user = this.buildUser(profile);
360
+ const expiresIn = Number(tokenResponse.expires_in);
361
+ const credential = {
362
+ providerId: 'google.com',
363
+ signInMethod: 'google.com',
364
+ accessToken,
365
+ expiresAt: this.calculateTokenExpiry(Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined),
366
+ tokenType: tokenResponse.token_type || 'Bearer',
367
+ scope: tokenResponse.scope || scopes.join(' '),
368
+ };
369
+ this.lastCredential = credential;
370
+ await this.setCurrentUser(user);
371
+ return this.createAuthResult(user, credential, false);
372
+ }
373
+ async fetchUserInfo(accessToken) {
374
+ let response;
375
+ try {
376
+ response = await fetch(USERINFO_ENDPOINT, {
377
+ headers: { Authorization: `Bearer ${accessToken}` },
378
+ signal: AbortSignal.timeout(15000),
379
+ });
380
+ }
381
+ catch (error) {
382
+ throw new AuthError(AuthErrorCode.NETWORK_ERROR, `Could not reach Google userinfo: ${error instanceof Error ? error.message : String(error)}`, AuthProvider.GOOGLE);
383
+ }
384
+ if (!response.ok) {
385
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Google userinfo request failed (${response.status})`, AuthProvider.GOOGLE);
386
+ }
387
+ return (await response.json());
388
+ }
389
+ // --- internals -----------------------------------------------------------------------------------
390
+ requireClientId() {
391
+ const options = this.options;
392
+ if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
393
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
394
+ }
395
+ return options.clientId;
396
+ }
141
397
  requireIdApi() {
142
398
  var _a, _b;
143
399
  const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
@@ -146,15 +402,13 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
146
402
  }
147
403
  return api;
148
404
  }
149
- configureIdClient() {
405
+ configureIdClient(loginHint) {
150
406
  var _a;
151
407
  const options = this.options;
152
- if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
153
- throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
154
- }
408
+ const clientId = this.requireClientId();
155
409
  this.currentNonce = options.nonce;
156
410
  const config = {
157
- client_id: options.clientId,
411
+ client_id: clientId,
158
412
  callback: (response) => this.handleCredential(response),
159
413
  auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
160
414
  cancel_on_tap_outside: false,
@@ -165,41 +419,25 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
165
419
  if (options.nonce) {
166
420
  config.nonce = options.nonce;
167
421
  }
168
- if (options.loginHint) {
169
- config.login_hint = options.loginHint;
422
+ const hint = loginHint !== null && loginHint !== void 0 ? loginHint : options.loginHint;
423
+ if (hint) {
424
+ config.login_hint = hint;
170
425
  }
171
426
  if (options.hostedDomain) {
172
427
  config.hd = options.hostedDomain;
173
428
  }
174
429
  this.requireIdApi().initialize(config);
175
430
  }
176
- async handleCredential(response) {
177
- if (response.error || !response.credential) {
178
- this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
179
- response.error ||
180
- 'No Google ID token returned', AuthProvider.GOOGLE));
181
- return;
182
- }
431
+ validateIdToken(idToken) {
432
+ let claims;
183
433
  try {
184
- const idToken = response.credential;
185
- const claims = this.validateIdToken(idToken);
186
- const user = this.buildUser(claims);
187
- const credential = {
188
- providerId: 'google.com',
189
- signInMethod: 'google.com',
190
- idToken,
191
- tokenType: 'Bearer',
192
- scope: 'openid email profile',
193
- };
194
- await this.setCurrentUser(user);
195
- this.resolvePending(this.createAuthResult(user, credential, false));
434
+ claims = decodeJwtPayload(idToken);
435
+ if (!claims || typeof claims !== 'object' || Array.isArray(claims))
436
+ throw new Error('Invalid claims');
196
437
  }
197
- catch (error) {
198
- this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
438
+ catch (_a) {
439
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
199
440
  }
200
- }
201
- validateIdToken(idToken) {
202
- const claims = decodeJwtPayload(idToken);
203
441
  const options = this.options;
204
442
  const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
205
443
  if (!claims.iss || !validIssuers.includes(claims.iss)) {
@@ -208,13 +446,22 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
208
446
  if (claims.aud !== options.clientId) {
209
447
  throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', AuthProvider.GOOGLE);
210
448
  }
211
- if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
449
+ if (typeof claims.exp !== 'number' ||
450
+ !Number.isFinite(claims.exp) ||
451
+ typeof claims.sub !== 'string' ||
452
+ !claims.sub) {
453
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token is missing required exp or sub claims', AuthProvider.GOOGLE);
454
+ }
455
+ if (claims.exp * 1000 <= Date.now()) {
212
456
  throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', AuthProvider.GOOGLE);
213
457
  }
214
458
  // Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
215
- if (this.currentNonce && claims.nonce && claims.nonce !== this.currentNonce) {
459
+ if (this.currentNonce && claims.nonce !== this.currentNonce) {
216
460
  throw new AuthError(AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', AuthProvider.GOOGLE);
217
461
  }
462
+ if (options.hostedDomain && claims.hd !== options.hostedDomain) {
463
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token does not match the required Workspace domain', AuthProvider.GOOGLE);
464
+ }
218
465
  return claims;
219
466
  }
220
467
  buildUser(claims) {
@@ -226,6 +473,7 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
226
473
  [claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
227
474
  null;
228
475
  const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
476
+ const now = new Date().toISOString();
229
477
  return {
230
478
  uid,
231
479
  email,
@@ -246,18 +494,20 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
246
494
  },
247
495
  ],
248
496
  metadata: {
249
- creationTime: new Date().toISOString(),
250
- lastSignInTime: new Date().toISOString(),
497
+ creationTime: now,
498
+ lastSignInTime: now,
251
499
  },
252
500
  };
253
501
  }
254
502
  resolvePending(result) {
503
+ this.clearPendingTimer();
255
504
  const resolve = this.pendingResolve;
256
505
  this.pendingResolve = null;
257
506
  this.pendingReject = null;
258
507
  resolve === null || resolve === void 0 ? void 0 : resolve(result);
259
508
  }
260
509
  rejectPending(error) {
510
+ this.clearPendingTimer();
261
511
  const reject = this.pendingReject;
262
512
  this.pendingResolve = null;
263
513
  this.pendingReject = null;
@@ -268,6 +518,22 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
268
518
  this.logger.error('Google sign-in error with no pending request', error);
269
519
  }
270
520
  }
521
+ clearPendingTimer() {
522
+ if (this.pendingTimer !== null)
523
+ clearTimeout(this.pendingTimer);
524
+ this.pendingTimer = null;
525
+ }
526
+ dispose() {
527
+ var _a, _b, _c, _d;
528
+ this.requestRevision++;
529
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
530
+ if (this.pendingReject) {
531
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was disposed', AuthProvider.GOOGLE));
532
+ (_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();
533
+ }
534
+ this.lastCredential = null;
535
+ super.dispose();
536
+ }
271
537
  loadGsi() {
272
538
  var _a, _b;
273
539
  if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
@@ -277,29 +543,39 @@ export class GoogleAuthProviderWeb extends BaseAuthProvider {
277
543
  return this.loadPromise;
278
544
  }
279
545
  this.loadPromise = new Promise((resolve, reject) => {
280
- var _a, _b;
281
546
  const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
547
+ const script = existing !== null && existing !== void 0 ? existing : document.createElement('script');
548
+ const cleanup = () => {
549
+ clearTimeout(timer);
550
+ script.removeEventListener('load', onReady);
551
+ script.removeEventListener('error', onError);
552
+ };
282
553
  const onReady = () => {
283
554
  var _a, _b;
284
- return ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
285
- ? resolve()
286
- : reject(new Error('Google Identity Services failed to load'));
287
- };
288
- if (existing) {
289
- existing.addEventListener('load', onReady, { once: true });
290
- existing.addEventListener('error', () => reject(new Error('Failed to load Google Identity Services')), { once: true });
291
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
555
+ cleanup();
556
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
292
557
  resolve();
558
+ else {
559
+ if (!existing)
560
+ script.remove();
561
+ reject(new Error('Google Identity Services failed to load'));
293
562
  }
294
- return;
563
+ };
564
+ const onError = () => {
565
+ cleanup();
566
+ if (!existing)
567
+ script.remove();
568
+ reject(new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to load Google Identity Services', AuthProvider.GOOGLE));
569
+ };
570
+ const timer = setTimeout(onError, 15000);
571
+ script.addEventListener('load', onReady, { once: true });
572
+ script.addEventListener('error', onError, { once: true });
573
+ if (!existing) {
574
+ script.src = GSI_SRC;
575
+ script.async = true;
576
+ script.defer = true;
577
+ document.head.appendChild(script);
295
578
  }
296
- const script = document.createElement('script');
297
- script.src = GSI_SRC;
298
- script.async = true;
299
- script.defer = true;
300
- script.onload = onReady;
301
- script.onerror = () => reject(new Error('Failed to load Google Identity Services'));
302
- document.head.appendChild(script);
303
579
  }).finally(() => {
304
580
  this.loadPromise = null;
305
581
  });
@@ -313,8 +589,6 @@ function decodeJwtPayload(jwt) {
313
589
  throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
314
590
  }
315
591
  if (typeof atob !== 'function') {
316
- // This provider only runs in the browser (the registry routes native platforms to the native
317
- // bridge); `atob` is always present there.
318
592
  throw new AuthError(AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', AuthProvider.GOOGLE);
319
593
  }
320
594
  const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');