capacitor-auth-manager 2.4.3 → 3.0.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 (80) hide show
  1. package/AI-INTEGRATION-GUIDE.md +174 -0
  2. package/CHANGELOG.md +127 -0
  3. package/CapacitorAuthManager.podspec +3 -3
  4. package/README.md +91 -73
  5. package/android/build.gradle +17 -25
  6. package/android/consumer-rules.pro +2 -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/AuthErrorCodes.java +32 -0
  10. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthException.java +34 -0
  11. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +46 -25
  12. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +54 -38
  13. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +77 -54
  14. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +171 -41
  15. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +5 -0
  16. package/dist/angular.cjs.js +421 -3376
  17. package/dist/core.cjs.js +589 -149
  18. package/dist/esm/angular/auth.guard.d.ts +1 -1
  19. package/dist/esm/angular/auth.module.d.ts +1 -1
  20. package/dist/esm/angular/auth.module.js +1 -1
  21. package/dist/esm/angular/auth.service.d.ts +2 -2
  22. package/dist/esm/angular/auth.service.js +1 -1
  23. package/dist/esm/angular/index.d.ts +4 -4
  24. package/dist/esm/angular/index.js +4 -4
  25. package/dist/esm/capacitor-plugin.d.ts +2 -3
  26. package/dist/esm/capacitor-plugin.js +14 -4
  27. package/dist/esm/core/auth-manager.d.ts +20 -2
  28. package/dist/esm/core/auth-manager.js +68 -12
  29. package/dist/esm/core/index.d.ts +5 -4
  30. package/dist/esm/core/index.js +5 -4
  31. package/dist/esm/core/provider-manifests.d.ts +1 -1
  32. package/dist/esm/core/provider-manifests.js +12 -13
  33. package/dist/esm/core/provider-registry.d.ts +8 -5
  34. package/dist/esm/core/provider-registry.js +41 -10
  35. package/dist/esm/core/types.d.ts +2 -2
  36. package/dist/esm/definitions.d.ts +26 -0
  37. package/dist/esm/index.d.ts +12 -12
  38. package/dist/esm/index.js +7 -7
  39. package/dist/esm/package.json +1 -0
  40. package/dist/esm/providers/base-provider.d.ts +7 -8
  41. package/dist/esm/providers/base-provider.js +7 -8
  42. package/dist/esm/providers/native/google-native-provider.d.ts +13 -2
  43. package/dist/esm/providers/native/google-native-provider.js +50 -6
  44. package/dist/esm/providers/oauth-provider.d.ts +2 -2
  45. package/dist/esm/providers/oauth-provider.js +3 -3
  46. package/dist/esm/providers/provider-factory.d.ts +5 -5
  47. package/dist/esm/providers/provider-factory.js +2 -2
  48. package/dist/esm/providers/web/google-provider.d.ts +74 -18
  49. package/dist/esm/providers/web/google-provider.js +391 -117
  50. package/dist/esm/providers/web/index.d.ts +1 -1
  51. package/dist/esm/providers/web/index.js +1 -1
  52. package/dist/esm/react/hooks.d.ts +2 -2
  53. package/dist/esm/react/hooks.js +2 -2
  54. package/dist/esm/react/index.d.ts +3 -3
  55. package/dist/esm/react/index.js +3 -3
  56. package/dist/esm/react/types.d.ts +1 -1
  57. package/dist/esm/utils/auth-error.d.ts +1 -1
  58. package/dist/esm/utils/auth-error.js +1 -1
  59. package/dist/esm/utils/event-emitter.d.ts +1 -1
  60. package/dist/esm/utils/event-emitter.js +1 -1
  61. package/dist/esm/utils/pending-verification-store.js +1 -1
  62. package/dist/esm/utils/storage.d.ts +2 -2
  63. package/dist/esm/utils/storage.js +31 -7
  64. package/dist/esm/vue/composables.d.ts +2 -2
  65. package/dist/esm/vue/composables.js +1 -1
  66. package/dist/esm/vue/index.d.ts +2 -2
  67. package/dist/esm/vue/index.js +2 -2
  68. package/dist/esm/web.d.ts +1 -1
  69. package/dist/esm/web.js +6 -6
  70. package/dist/plugin.cjs.js +291 -2771
  71. package/dist/plugin.js +585 -147
  72. package/dist/providers-web.cjs.js +1317 -0
  73. package/dist/react.cjs.js +310 -3265
  74. package/dist/vue.cjs.js +266 -3221
  75. package/ios/Plugin/AuthStorage.swift +3 -1
  76. package/ios/Plugin/GoogleAuthProvider.swift +7 -4
  77. package/ios/Plugin/Models.swift +28 -0
  78. package/ios/Plugin/Plugin.swift +64 -40
  79. package/package.json +55 -33
  80. package/scripts/configure.js +71 -325
package/dist/plugin.js CHANGED
@@ -359,17 +359,15 @@ var CapacitorAuthManager = (function (exports, core) {
359
359
  this.logger = logger;
360
360
  switch (persistence) {
361
361
  case exports.AuthPersistence.SESSION:
362
- this.storage = window.sessionStorage;
363
- break;
364
- case exports.AuthPersistence.LOCAL:
365
- this.storage = window.localStorage;
362
+ this.storage = resolveBrowserStorage('sessionStorage');
366
363
  break;
367
364
  case exports.AuthPersistence.NONE:
368
365
  // Use in-memory storage
369
366
  this.storage = new InMemoryStorage();
370
367
  break;
368
+ case exports.AuthPersistence.LOCAL:
371
369
  default:
372
- this.storage = window.localStorage;
370
+ this.storage = resolveBrowserStorage('localStorage');
373
371
  }
374
372
  }
375
373
  async get(key) {
@@ -477,6 +475,32 @@ var CapacitorAuthManager = (function (exports, core) {
477
475
  .map((k) => prefs.remove({ key: k })));
478
476
  }
479
477
  }
478
+ /**
479
+ * Returns the requested browser storage when it exists AND is usable, otherwise an in-memory
480
+ * fallback. Two environments make the fallback necessary:
481
+ * - Node / SSR / test runners: `window` is undefined, so the old unguarded `window.localStorage`
482
+ * read threw `ReferenceError: window is not defined` at import time (ISSUE-002).
483
+ * - Browsers that expose the API but refuse it (Safari private mode, cookies disabled, sandboxed
484
+ * iframes): `getItem`/`setItem` throw, so the probe below catches that and degrades gracefully.
485
+ */
486
+ function resolveBrowserStorage(kind) {
487
+ if (typeof window === 'undefined') {
488
+ return new InMemoryStorage();
489
+ }
490
+ try {
491
+ const candidate = window[kind];
492
+ if (!candidate) {
493
+ return new InMemoryStorage();
494
+ }
495
+ const probeKey = '__cap_auth_probe__';
496
+ candidate.setItem(probeKey, '1');
497
+ candidate.removeItem(probeKey);
498
+ return candidate;
499
+ }
500
+ catch (_a) {
501
+ return new InMemoryStorage();
502
+ }
503
+ }
480
504
  class InMemoryStorage {
481
505
  constructor() {
482
506
  this.data = new Map();
@@ -721,28 +745,27 @@ var CapacitorAuthManager = (function (exports, core) {
721
745
  {
722
746
  name: 'google',
723
747
  displayName: 'Google',
724
- packageName: '@google/gsi',
725
748
  setupInstructions: `
726
- To use Google authentication, you need to:
749
+ To use Google authentication:
727
750
 
728
- 1. Install the Google Sign-In SDK:
729
- npm install @google/gsi
751
+ 1. Create (or reuse) an OAuth 2.0 **Web** client in Google Cloud Console — Firebase creates one for you
752
+ when you enable the Google sign-in provider. Add your site origins (including your dev server, e.g.
753
+ http://localhost:5931) under "Authorized JavaScript origins".
730
754
 
731
- 2. Configure your Google OAuth client:
732
- - Go to https://console.cloud.google.com/
733
- - Create or select a project
734
- - Enable Google Sign-In API
735
- - Create OAuth 2.0 credentials
736
- - Add authorized JavaScript origins
737
-
738
- 3. Configure the provider:
755
+ 2. Configure the provider (no extra npm package is needed — the Google Identity Services script is
756
+ loaded on demand on web; the native SDKs ship with the plugin):
739
757
  auth.configure({
740
758
  providers: {
741
759
  google: {
742
- clientId: 'YOUR_CLIENT_ID'
760
+ clientId: 'YOUR_WEB_CLIENT_ID', // web + Android serverClientId fallback
761
+ serverClientId: 'YOUR_WEB_CLIENT_ID', // Android
762
+ iosClientId: 'YOUR_IOS_CLIENT_ID', // iOS (or GIDClientID in Info.plist)
743
763
  }
744
764
  }
745
765
  })
766
+
767
+ 3. Android: register your signing key's SHA-1 in Firebase / Google Cloud. iOS: add the reversed
768
+ client id as a URL scheme.
746
769
  `,
747
770
  platforms: ['web', 'ios', 'android'],
748
771
  configSchema: {
@@ -1197,7 +1220,26 @@ Note: This provider requires a backend service to handle authentication.
1197
1220
  return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
1198
1221
  }
1199
1222
  static async getProvider(name, options, deps) {
1200
- var _b, _c;
1223
+ const key = this.canonicalName(name);
1224
+ const existing = this.providers.get(key);
1225
+ if (existing)
1226
+ return existing;
1227
+ const pending = this.pending.get(key);
1228
+ if (pending)
1229
+ return pending;
1230
+ const promise = this.createProvider(name, options, deps);
1231
+ this.pending.set(key, promise);
1232
+ try {
1233
+ return await promise;
1234
+ }
1235
+ finally {
1236
+ if (this.pending.get(key) === promise)
1237
+ this.pending.delete(key);
1238
+ }
1239
+ }
1240
+ static async createProvider(name, options, deps) {
1241
+ var _b, _c, _d;
1242
+ const generation = this.generation;
1201
1243
  const key = this.canonicalName(name);
1202
1244
  // Check if already loaded
1203
1245
  const existing = this.providers.get(key);
@@ -1255,6 +1297,10 @@ Note: This provider requires a backend service to handle authentication.
1255
1297
  if (provider.initialize) {
1256
1298
  await provider.initialize();
1257
1299
  }
1300
+ if (generation !== this.generation) {
1301
+ (_d = provider.dispose) === null || _d === void 0 ? void 0 : _d.call(provider);
1302
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'Provider configuration changed during initialization');
1303
+ }
1258
1304
  // Cache the provider under its canonical key
1259
1305
  this.providers.set(key, provider);
1260
1306
  return provider;
@@ -1276,7 +1322,9 @@ Note: This provider requires a backend service to handle authentication.
1276
1322
  }
1277
1323
  }
1278
1324
  static clearProvider(name) {
1325
+ this.generation++;
1279
1326
  const key = this.canonicalName(name);
1327
+ this.pending.delete(key);
1280
1328
  const provider = this.providers.get(key);
1281
1329
  if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
1282
1330
  provider.dispose();
@@ -1284,6 +1332,8 @@ Note: This provider requires a backend service to handle authentication.
1284
1332
  this.providers.delete(key);
1285
1333
  }
1286
1334
  static clearAll() {
1335
+ this.generation++;
1336
+ this.pending.clear();
1287
1337
  for (const [, provider] of this.providers) {
1288
1338
  if (provider.dispose) {
1289
1339
  provider.dispose();
@@ -1298,6 +1348,8 @@ Note: This provider requires a backend service to handle authentication.
1298
1348
  const platform = PlatformDetector.getPlatform();
1299
1349
  const supported = [];
1300
1350
  for (const [name, manifest] of this.manifests) {
1351
+ if (!this.loaders.has(name))
1352
+ continue;
1301
1353
  if (!manifest.platforms ||
1302
1354
  manifest.platforms.includes(platform.platform)) {
1303
1355
  supported.push(name);
@@ -1308,6 +1360,8 @@ Note: This provider requires a backend service to handle authentication.
1308
1360
  }
1309
1361
  _a = ProviderRegistry;
1310
1362
  ProviderRegistry.providers = new Map();
1363
+ ProviderRegistry.pending = new Map();
1364
+ ProviderRegistry.generation = 0;
1311
1365
  ProviderRegistry.loaders = new Map();
1312
1366
  ProviderRegistry.manifests = new Map();
1313
1367
  /** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
@@ -1408,6 +1462,7 @@ Note: This provider requires a backend service to handle authentication.
1408
1462
  this.isInitialized = false;
1409
1463
  this.tokenRefreshTimers = new Map();
1410
1464
  this.initPromise = null;
1465
+ this.sessionRevision = 0;
1411
1466
  this.logger = new Logger({
1412
1467
  enableLogging: false,
1413
1468
  logLevel: 'info',
@@ -1485,6 +1540,8 @@ Note: This provider requires a backend service to handle authentication.
1485
1540
  async signIn(providerOrOptions) {
1486
1541
  var _a, _b, _c;
1487
1542
  await this.ensureInitialized();
1543
+ this.assertIdle();
1544
+ this.sessionRevision++;
1488
1545
  let providerName;
1489
1546
  let signInOptions = {};
1490
1547
  if (typeof providerOrOptions === 'string') {
@@ -1547,9 +1604,16 @@ Note: This provider requires a backend service to handle authentication.
1547
1604
  throw AuthError.fromError(error);
1548
1605
  }
1549
1606
  }
1607
+ /** Load the provider SDK before a user gesture, without opening a sign-in prompt. */
1608
+ async prepare(provider) {
1609
+ await this.ensureInitialized();
1610
+ await this.resolveProvider(provider);
1611
+ }
1550
1612
  async signOut(options) {
1551
1613
  var _a;
1552
1614
  await this.ensureInitialized();
1615
+ this.assertIdle();
1616
+ this.sessionRevision++;
1553
1617
  const provider = (options === null || options === void 0 ? void 0 : options.provider) || this.state.provider;
1554
1618
  if (!provider) {
1555
1619
  this.logger.warn('No active auth session to sign out from');
@@ -1765,7 +1829,8 @@ Note: This provider requires a backend service to handle authentication.
1765
1829
  throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
1766
1830
  }
1767
1831
  const provider = await this.resolveProvider(targetProvider);
1768
- const deleteFn = provider.deleteAccount;
1832
+ const deleteFn = provider
1833
+ .deleteAccount;
1769
1834
  if (typeof deleteFn !== 'function') {
1770
1835
  throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
1771
1836
  }
@@ -1819,7 +1884,11 @@ Note: This provider requires a backend service to handle authentication.
1819
1884
  }
1820
1885
  }
1821
1886
  getProviderDeps() {
1822
- return { storage: this.storage, logger: this.logger };
1887
+ return {
1888
+ storage: this.storage,
1889
+ logger: this.logger,
1890
+ persistence: toAuthPersistence(this.config.persistence),
1891
+ };
1823
1892
  }
1824
1893
  /**
1825
1894
  * Resolves a provider instance through the registry, threading the configured options and the
@@ -1853,6 +1922,7 @@ Note: This provider requires a backend service to handle authentication.
1853
1922
  }
1854
1923
  async restoreAuthState() {
1855
1924
  var _a, _b;
1925
+ const revision = this.sessionRevision;
1856
1926
  try {
1857
1927
  const stored = await this.storage.get('auth_state');
1858
1928
  if ((stored === null || stored === void 0 ? void 0 : stored.user) && (stored === null || stored === void 0 ? void 0 : stored.provider)) {
@@ -1862,7 +1932,7 @@ Note: This provider requires a backend service to handle authentication.
1862
1932
  try {
1863
1933
  const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
1864
1934
  const currentUser = await provider.getCurrentUser();
1865
- if (currentUser) {
1935
+ if (currentUser && revision === this.sessionRevision) {
1866
1936
  this.updateState({
1867
1937
  user: currentUser,
1868
1938
  isAuthenticated: true,
@@ -1877,7 +1947,8 @@ Note: This provider requires a backend service to handle authentication.
1877
1947
  }
1878
1948
  catch (error) {
1879
1949
  this.logger.warn('Failed to restore auth session:', error);
1880
- await this.storage.remove('auth_state');
1950
+ if (revision === this.sessionRevision)
1951
+ await this.storage.remove('auth_state');
1881
1952
  }
1882
1953
  }
1883
1954
  }
@@ -1886,6 +1957,11 @@ Note: This provider requires a backend service to handle authentication.
1886
1957
  this.logger.error('Failed to restore auth state:', error);
1887
1958
  }
1888
1959
  }
1960
+ assertIdle() {
1961
+ if (this.state.isLoading) {
1962
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'An authentication operation is already in progress');
1963
+ }
1964
+ }
1889
1965
  setupTokenRefresh(provider, credential) {
1890
1966
  this.clearTokenRefresh(provider);
1891
1967
  if (!credential.expiresAt || !credential.refreshToken) {
@@ -1939,6 +2015,7 @@ Note: This provider requires a backend service to handle authentication.
1939
2015
  this.tokenRefreshTimers.clear();
1940
2016
  }
1941
2017
  dispose() {
2018
+ this.sessionRevision++;
1942
2019
  // Clear all timers
1943
2020
  for (const timer of this.tokenRefreshTimers.values()) {
1944
2021
  clearTimeout(timer);
@@ -1950,12 +2027,56 @@ Note: This provider requires a backend service to handle authentication.
1950
2027
  this.stateEmitter.clear();
1951
2028
  }
1952
2029
  }
1953
- // Create singleton instance
1954
- const auth = new AuthManagerCore();
2030
+ let instance = null;
2031
+ /**
2032
+ * Returns the process-wide auth manager, constructing it on first call.
2033
+ *
2034
+ * The singleton is created lazily on purpose (ISSUE-002): constructing it eagerly at module scope
2035
+ * built a `WebStorage` that read `window.localStorage` while the module was being evaluated, which
2036
+ * crashed any import under Node / SSR and made `"sideEffects": false` untrue. Nothing touches the
2037
+ * browser until the first real use.
2038
+ */
2039
+ function getAuth() {
2040
+ if (!instance) {
2041
+ instance = new AuthManagerCore();
2042
+ }
2043
+ return instance;
2044
+ }
2045
+ /**
2046
+ * The shared auth manager. Every property access is forwarded to the lazily-created instance, so
2047
+ * `import { auth } from 'capacitor-auth-manager'` keeps working unchanged while importing the
2048
+ * package has no side effects.
2049
+ */
2050
+ const auth = new Proxy({}, {
2051
+ get(_target, property) {
2052
+ const target = getAuth();
2053
+ const value = Reflect.get(target, property, target);
2054
+ return typeof value === 'function'
2055
+ ? value.bind(target)
2056
+ : value;
2057
+ },
2058
+ set(_target, property, value) {
2059
+ return Reflect.set(getAuth(), property, value);
2060
+ },
2061
+ has(_target, property) {
2062
+ return Reflect.has(getAuth(), property);
2063
+ },
2064
+ });
1955
2065
 
1956
- // This provides backward compatibility for users who still want to use the Capacitor plugin interface
1957
- const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
1958
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
2066
+ let plugin = null;
2067
+ function getPlugin() {
2068
+ plugin !== null && plugin !== void 0 ? plugin : (plugin = core.registerPlugin('CapacitorAuthManager', {
2069
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
2070
+ }));
2071
+ return plugin;
2072
+ }
2073
+ // Importing the package never registers a native plugin or touches a browser global.
2074
+ const CapacitorAuthManager = new Proxy({}, {
2075
+ get(_target, property) {
2076
+ const target = getPlugin();
2077
+ const value = Reflect.get(target, property, target);
2078
+ return typeof value === 'function' ? value.bind(target) : value;
2079
+ },
1959
2080
  });
1960
2081
 
1961
2082
  /**
@@ -1964,9 +2085,8 @@ Note: This provider requires a backend service to handle authentication.
1964
2085
  * The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
1965
2086
  * get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
1966
2087
  * tests and direct consumers pass the provider's own bare options object. This helper accepts
1967
- * either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`, so it never
1968
- * touches `window` and stays safe under SSR / Node test environments) plus the shared
1969
- * {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
2088
+ * either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`) plus the
2089
+ * shared {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
1970
2090
  */
1971
2091
  function resolveProviderConfig(provider, input) {
1972
2092
  if (typeof input === 'object' &&
@@ -2148,6 +2268,7 @@ Note: This provider requires a backend service to handle authentication.
2148
2268
  // Hand the Google config (clientId / serverClientId / iosClientId / scopes) to the native side
2149
2269
  // once; subsequent signIn() calls only pass per-request SignInProviderOptions.
2150
2270
  await CapacitorAuthManager.initialize({
2271
+ persistence: this.persistence,
2151
2272
  providers: [
2152
2273
  {
2153
2274
  provider: exports.AuthProvider.GOOGLE,
@@ -2167,9 +2288,16 @@ Note: This provider requires a backend service to handle authentication.
2167
2288
  await this.initialize();
2168
2289
  }
2169
2290
  try {
2291
+ // AuthManagerCore spreads the per-call `options` to the top level before calling us, so read
2292
+ // both shapes: a nested `options` object (direct plugin-style callers) or the flattened one.
2293
+ const source = (options !== null && options !== void 0 ? options : {});
2294
+ const { credentials, options: nested } = source;
2295
+ const flat = Object.fromEntries(Object.entries(source).filter(([key]) => !['provider', 'credentials', 'options'].includes(key)));
2296
+ const perCall = Object.assign(Object.assign({}, flat), (nested !== null && nested !== void 0 ? nested : {}));
2170
2297
  const result = await CapacitorAuthManager.signIn({
2171
2298
  provider: exports.AuthProvider.GOOGLE,
2172
- options: options === null || options === void 0 ? void 0 : options.options,
2299
+ credentials,
2300
+ options: perCall,
2173
2301
  });
2174
2302
  await this.setCurrentUser(result.user);
2175
2303
  return result;
@@ -2203,9 +2331,45 @@ Note: This provider requires a backend service to handle authentication.
2203
2331
  throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2204
2332
  }
2205
2333
  }
2334
+ /**
2335
+ * The current Google ID token, refreshed through the platform SDK when `forceRefresh` is set.
2336
+ *
2337
+ * `AuthManagerCore.getIdToken` looks for this method on the resolved provider and throws
2338
+ * `OPERATION_NOT_ALLOWED` when it is missing, so without it `auth.getIdToken()` failed on iOS and
2339
+ * Android even though both native layers implement it — while the same call worked on web.
2340
+ *
2341
+ * Capacitor cannot resolve a bare string, so the native side answers `{ token }`; the web
2342
+ * fallback in `src/web.ts` resolves the string itself. Read both shapes.
2343
+ */
2344
+ async getIdToken(forceRefresh = false) {
2345
+ var _a;
2346
+ if (!this.isInitialized) {
2347
+ await this.initialize();
2348
+ }
2349
+ try {
2350
+ const raw = (await CapacitorAuthManager.getIdToken({
2351
+ provider: exports.AuthProvider.GOOGLE,
2352
+ forceRefresh,
2353
+ }));
2354
+ const token = typeof raw === 'string' ? raw : ((_a = raw === null || raw === void 0 ? void 0 : raw.token) !== null && _a !== void 0 ? _a : '');
2355
+ if (!token) {
2356
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available. Sign in again.', exports.AuthProvider.GOOGLE);
2357
+ }
2358
+ return token;
2359
+ }
2360
+ catch (error) {
2361
+ throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2362
+ }
2363
+ }
2206
2364
  async getCurrentUser() {
2207
2365
  try {
2208
- const user = await CapacitorAuthManager.getCurrentUser();
2366
+ const raw = (await CapacitorAuthManager.getCurrentUser());
2367
+ // A Capacitor call cannot resolve `null`; the native side answers `{}` when nobody is signed
2368
+ // in. Treat anything without a string `uid` as "no user" — otherwise the empty object was
2369
+ // taken as a user and the app restored an authenticated state with no account behind it.
2370
+ const user = raw && typeof raw.uid === 'string' && raw.uid.length > 0
2371
+ ? raw
2372
+ : null;
2209
2373
  this.currentUser = user;
2210
2374
  return user;
2211
2375
  }
@@ -2237,27 +2401,42 @@ Note: This provider requires a backend service to handle authentication.
2237
2401
  });
2238
2402
 
2239
2403
  const GSI_SRC = 'https://accounts.google.com/gsi/client';
2404
+ const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/userinfo';
2405
+ const DEFAULT_SCOPES = ['openid', 'email', 'profile'];
2240
2406
  /**
2241
2407
  * Web Google provider — the implementation the registry loads on **web / electron**.
2242
2408
  *
2243
- * Uses the **Google Identity Services ID-token flow** (`google.accounts.id`): no client secret, no
2244
- * backend, no popup-blocker problems. The browser returns a Google **ID token** (JWT) which is
2245
- * surfaced as `result.credential.idToken` — the SAME field the native providers populate — so the
2246
- * Firebase handoff is identical on every platform:
2409
+ * Two Google Identity Services flows are available, selected by {@link GoogleAuthOptions.webFlow}
2410
+ * (default `'auto'`):
2411
+ *
2412
+ * 1. **One-Tap / FedCM id-token flow** (`google.accounts.id`): returns a Google **ID token** (JWT) as
2413
+ * `result.credential.idToken` — the same field the native providers populate.
2414
+ * 2. **OAuth2 popup flow** (`google.accounts.oauth2.initTokenClient`): a deterministic popup that works
2415
+ * from any click handler and returns an **access token** as `result.credential.accessToken`; the user
2416
+ * profile is read from Google's `userinfo` endpoint. `'auto'` falls back to this whenever the browser
2417
+ * does not display One-Tap (cooldown, FedCM opt-out, third-party-cookie settings).
2418
+ *
2419
+ * Either credential is accepted by Firebase — the handoff is identical on every platform:
2247
2420
  *
2248
- * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(result.credential.idToken));
2421
+ * const { idToken, accessToken } = result.credential;
2422
+ * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(idToken ?? null, accessToken));
2249
2423
  *
2250
- * The id-token flow does NOT return an OAuth `accessToken` (use the GIS token client separately if you
2251
- * need to call Google APIs from the browser). Sign-in is triggered via One-Tap / FedCM `prompt()`; for a
2252
- * guaranteed button UX call {@link renderButton} to render Google's official button (same callback).
2424
+ * Neither flow needs a client secret or a backend. For Google's official button call
2425
+ * {@link renderButton}; it shares the One-Tap credential callback.
2253
2426
  */
2254
2427
  class GoogleAuthProviderWeb extends BaseAuthProvider {
2255
2428
  constructor(config) {
2256
- super(config);
2429
+ super(resolveProviderConfig(exports.AuthProvider.GOOGLE, config));
2257
2430
  this.loadPromise = null;
2258
2431
  /** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
2259
2432
  this.pendingResolve = null;
2260
2433
  this.pendingReject = null;
2434
+ /** Last credential issued in this page session (tokens are deliberately not persisted). */
2435
+ this.lastCredential = null;
2436
+ this.signingIn = false;
2437
+ this.pendingTimer = null;
2438
+ this.requestRevision = 0;
2439
+ this.pendingPopupReject = null;
2261
2440
  }
2262
2441
  get name() {
2263
2442
  return exports.AuthProvider.GOOGLE;
@@ -2267,6 +2446,7 @@ Note: This provider requires a backend service to handle authentication.
2267
2446
  return;
2268
2447
  }
2269
2448
  try {
2449
+ this.requireClientId();
2270
2450
  await this.loadGsi();
2271
2451
  this.configureIdClient();
2272
2452
  await this.loadCurrentUser();
@@ -2277,45 +2457,34 @@ Note: This provider requires a backend service to handle authentication.
2277
2457
  throw AuthError.fromError(error, exports.AuthProvider.GOOGLE);
2278
2458
  }
2279
2459
  }
2280
- async signIn(_options) {
2281
- if (!this.isInitialized) {
2282
- await this.initialize();
2460
+ async signIn(options) {
2461
+ var _a, _b, _c, _d, _e, _f, _g;
2462
+ if (this.signingIn) {
2463
+ throw new AuthError(exports.AuthErrorCode.OPERATION_NOT_ALLOWED, 'A Google sign-in is already in progress', exports.AuthProvider.GOOGLE);
2283
2464
  }
2284
- this.configureIdClient();
2285
- return new Promise((resolve, reject) => {
2286
- this.pendingResolve = resolve;
2287
- this.pendingReject = (e) => reject(e);
2288
- const api = this.requireIdApi();
2289
- try {
2290
- api.prompt((notification) => {
2291
- var _a, _b, _c, _d, _e, _f, _g, _h;
2292
- // One-Tap was suppressed (cooldown / dismissed / FedCM opt-out): fail clearly so the
2293
- // consumer can fall back to renderButton(). Wrapped in try/catch because these moment
2294
- // methods are deprecated under FedCM and may throw.
2295
- try {
2296
- const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
2297
- const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
2298
- if (notDisplayed || skipped) {
2299
- 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';
2300
- this.rejectPending(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Render the Google button via ` +
2301
- `provider.renderButton(element) for a guaranteed sign-in UI, or sign in on web ` +
2302
- `with your own Firebase popup.`, exports.AuthProvider.GOOGLE));
2303
- }
2304
- }
2305
- catch (_j) {
2306
- // FedCM: moment methods unavailable — wait for the credential callback instead.
2307
- }
2308
- });
2465
+ this.signingIn = true;
2466
+ try {
2467
+ if (!this.isInitialized) {
2468
+ await this.initialize();
2309
2469
  }
2310
- catch (error) {
2311
- this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2470
+ // AuthManagerCore spreads per-call options to the top level; direct callers nest them under
2471
+ // `options`. Read both shapes.
2472
+ const perCall = (options !== null && options !== void 0 ? options : {});
2473
+ 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';
2474
+ 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;
2475
+ if (flow === 'popup') {
2476
+ return await this.signInWithPopup(loginHint);
2312
2477
  }
2313
- });
2478
+ return await this.signInWithOneTap(flow === 'auto', loginHint);
2479
+ }
2480
+ finally {
2481
+ this.signingIn = false;
2482
+ }
2314
2483
  }
2315
2484
  /**
2316
- * Renders Google's official "Sign in with Google" button into `parent`. Use this when One-Tap is
2317
- * suppressed or you want a deterministic button. The button uses the SAME credential callback, so a
2318
- * click resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
2485
+ * Renders Google's official "Sign in with Google" button into `parent`. Use this when you want
2486
+ * Google's branded button rather than your own. It uses the SAME credential callback, so a click
2487
+ * resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
2319
2488
  */
2320
2489
  async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
2321
2490
  if (!this.isInitialized) {
@@ -2325,39 +2494,80 @@ Note: This provider requires a backend service to handle authentication.
2325
2494
  this.requireIdApi().renderButton(parent, options);
2326
2495
  }
2327
2496
  async signOut(_options) {
2328
- var _a, _b, _c;
2497
+ var _a, _b, _c, _d, _e, _f, _g;
2498
+ this.requestRevision++;
2499
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', exports.AuthProvider.GOOGLE));
2500
+ if (this.pendingReject) {
2501
+ this.rejectPending(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled by sign-out', exports.AuthProvider.GOOGLE));
2502
+ (_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();
2503
+ }
2329
2504
  try {
2330
- (_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();
2505
+ (_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();
2331
2506
  }
2332
2507
  catch (error) {
2333
2508
  this.logger.warn('Google disableAutoSelect failed', error);
2334
2509
  }
2510
+ this.lastCredential = null;
2335
2511
  await this.clearStoredData();
2336
2512
  await this.setCurrentUser(null);
2337
2513
  }
2338
2514
  /**
2339
- * Web ID tokens cannot be refreshed silently — re-running One-Tap (with auto-select) re-issues a
2340
- * fresh ID token for a returning user. Falls back to a normal prompt if auto-select can't.
2515
+ * Web tokens cannot be refreshed silently without a backend — re-running the configured flow
2516
+ * (One-Tap auto-select for a returning user, or the popup) re-issues a fresh credential.
2341
2517
  */
2342
2518
  async refreshToken(_options) {
2343
2519
  return this.signIn();
2344
2520
  }
2521
+ /**
2522
+ * Returns the ID token from the current page session. `forceRefresh` (or an expired token) re-runs
2523
+ * One-Tap. Throws `NO_AUTH_SESSION` when the last sign-in was the popup flow, which issues no ID token.
2524
+ */
2525
+ async getIdToken(forceRefresh = false) {
2526
+ const cached = this.lastCredential;
2527
+ const expired = typeof (cached === null || cached === void 0 ? void 0 : cached.expiresAt) === 'number' && cached.expiresAt <= Date.now();
2528
+ if ((cached === null || cached === void 0 ? void 0 : cached.idToken) && !forceRefresh && !expired) {
2529
+ return cached.idToken;
2530
+ }
2531
+ if (cached && !cached.idToken && !forceRefresh) {
2532
+ throw new AuthError(exports.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".', exports.AuthProvider.GOOGLE);
2533
+ }
2534
+ const result = await this.signIn({
2535
+ provider: exports.AuthProvider.GOOGLE,
2536
+ options: { webFlow: 'one-tap' },
2537
+ });
2538
+ if (!result.credential.idToken) {
2539
+ throw new AuthError(exports.AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available', exports.AuthProvider.GOOGLE);
2540
+ }
2541
+ return result.credential.idToken;
2542
+ }
2345
2543
  async revokeAccess(token) {
2346
- var _a, _b;
2347
- const user = (_a = this.currentUser) !== null && _a !== void 0 ? _a : (await this.getCurrentUser());
2348
- const hint = (_b = user === null || user === void 0 ? void 0 : user.email) !== null && _b !== void 0 ? _b : token;
2349
- if (!hint) {
2544
+ var _a, _b, _c, _d, _e;
2545
+ const accessToken = token !== null && token !== void 0 ? token : (_a = this.lastCredential) === null || _a === void 0 ? void 0 : _a.accessToken;
2546
+ const oauth2 = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.oauth2;
2547
+ if (accessToken && oauth2) {
2548
+ await new Promise((resolve) => {
2549
+ try {
2550
+ oauth2.revoke(accessToken, () => resolve());
2551
+ }
2552
+ catch (_a) {
2553
+ resolve();
2554
+ }
2555
+ });
2350
2556
  await this.signOut();
2351
2557
  return;
2352
2558
  }
2353
- await new Promise((resolve) => {
2354
- try {
2355
- this.requireIdApi().revoke(hint, () => resolve());
2356
- }
2357
- catch (_a) {
2358
- resolve();
2359
- }
2360
- });
2559
+ const user = (_d = this.currentUser) !== null && _d !== void 0 ? _d : (await this.getCurrentUser());
2560
+ const hint = (_e = user === null || user === void 0 ? void 0 : user.email) !== null && _e !== void 0 ? _e : token;
2561
+ if (hint) {
2562
+ await new Promise((resolve) => {
2563
+ try {
2564
+ this.requireIdApi().revoke(hint, () => resolve());
2565
+ }
2566
+ catch (_a) {
2567
+ resolve();
2568
+ }
2569
+ });
2570
+ }
2361
2571
  await this.signOut();
2362
2572
  }
2363
2573
  async isSupported() {
@@ -2372,7 +2582,217 @@ Note: This provider requires a backend service to handle authentication.
2372
2582
  return false;
2373
2583
  }
2374
2584
  }
2375
- // --- internals --------------------------------------------------------------------------------
2585
+ // --- One-Tap flow --------------------------------------------------------------------------------
2586
+ signInWithOneTap(fallbackToPopup, loginHint) {
2587
+ this.configureIdClient(loginHint);
2588
+ return new Promise((resolve, reject) => {
2589
+ this.pendingResolve = resolve;
2590
+ this.pendingReject = (e) => reject(e);
2591
+ this.pendingTimer = setTimeout(() => {
2592
+ var _a, _b, _c;
2593
+ this.rejectPending(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, 'Google One-Tap did not return a credential. Retry from a click with webFlow "popup", or use the Google button.', exports.AuthProvider.GOOGLE));
2594
+ (_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();
2595
+ }, 120000);
2596
+ const fallback = (reason) => {
2597
+ this.logger.info(`Google One-Tap not shown (${reason}); using the popup flow`);
2598
+ // Drop the One-Tap resolvers so a late credential callback cannot double-resolve.
2599
+ this.pendingResolve = null;
2600
+ this.pendingReject = null;
2601
+ this.clearPendingTimer();
2602
+ this.signInWithPopup(loginHint).then(resolve, reject);
2603
+ };
2604
+ try {
2605
+ this.requireIdApi().prompt((notification) => {
2606
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
2607
+ // These moment methods are deprecated under FedCM and may throw — guard every call.
2608
+ try {
2609
+ const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
2610
+ const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
2611
+ if (notDisplayed || skipped) {
2612
+ 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';
2613
+ if (fallbackToPopup) {
2614
+ fallback(reason);
2615
+ }
2616
+ else {
2617
+ this.rejectPending(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Use webFlow 'popup' or 'auto', or ` +
2618
+ `render Google's button via provider.renderButton(element).`, exports.AuthProvider.GOOGLE));
2619
+ }
2620
+ return;
2621
+ }
2622
+ const dismissed = (_k = (_j = notification.isDismissedMoment) === null || _j === void 0 ? void 0 : _j.call(notification)) !== null && _k !== void 0 ? _k : false;
2623
+ if (dismissed) {
2624
+ const reason = (_m = (_l = notification.getDismissedReason) === null || _l === void 0 ? void 0 : _l.call(notification)) !== null && _m !== void 0 ? _m : '';
2625
+ // 'credential_returned' is the success path — the credential callback resolves it.
2626
+ if (reason !== 'credential_returned') {
2627
+ this.rejectPending(new AuthError(exports.AuthErrorCode.USER_CANCELLED, `Google One-Tap was dismissed (${reason || 'cancelled'})`, exports.AuthProvider.GOOGLE));
2628
+ }
2629
+ }
2630
+ }
2631
+ catch (_o) {
2632
+ // FedCM: moment methods unavailable — wait for the credential callback instead.
2633
+ }
2634
+ });
2635
+ }
2636
+ catch (error) {
2637
+ if (fallbackToPopup) {
2638
+ fallback(error instanceof Error ? error.message : 'prompt failed');
2639
+ }
2640
+ else {
2641
+ this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2642
+ }
2643
+ }
2644
+ });
2645
+ }
2646
+ async handleCredential(response) {
2647
+ // Ignore a late callback after cancellation, timeout, or popup fallback.
2648
+ if (!this.pendingResolve)
2649
+ return;
2650
+ if (response.error || !response.credential) {
2651
+ this.rejectPending(new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
2652
+ response.error ||
2653
+ 'No Google ID token returned', exports.AuthProvider.GOOGLE));
2654
+ return;
2655
+ }
2656
+ try {
2657
+ const idToken = response.credential;
2658
+ const claims = this.validateIdToken(idToken);
2659
+ const user = this.buildUser(claims);
2660
+ const credential = {
2661
+ providerId: 'google.com',
2662
+ signInMethod: 'google.com',
2663
+ idToken,
2664
+ expiresAt: typeof claims.exp === 'number' ? claims.exp * 1000 : undefined,
2665
+ tokenType: 'Bearer',
2666
+ scope: DEFAULT_SCOPES.join(' '),
2667
+ };
2668
+ this.lastCredential = credential;
2669
+ await this.setCurrentUser(user);
2670
+ this.resolvePending(this.createAuthResult(user, credential, false));
2671
+ }
2672
+ catch (error) {
2673
+ this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2674
+ }
2675
+ }
2676
+ // --- OAuth2 popup flow ---------------------------------------------------------------------------
2677
+ async signInWithPopup(loginHint) {
2678
+ var _a, _b, _c;
2679
+ const revision = this.requestRevision;
2680
+ const options = this.options;
2681
+ const clientId = this.requireClientId();
2682
+ await this.loadGsi();
2683
+ const oauth2 = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2;
2684
+ if (!oauth2) {
2685
+ throw new AuthError(exports.AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services OAuth2 client not loaded', exports.AuthProvider.GOOGLE);
2686
+ }
2687
+ const scopes = Array.from(new Set([...DEFAULT_SCOPES, ...((_c = options.scopes) !== null && _c !== void 0 ? _c : [])]));
2688
+ const tokenResponse = await new Promise((resolve, reject) => {
2689
+ var _a;
2690
+ let settled = false;
2691
+ const cleanup = () => {
2692
+ settled = true;
2693
+ clearTimeout(timer);
2694
+ this.pendingPopupReject = null;
2695
+ };
2696
+ const resolveToken = (response) => {
2697
+ if (settled)
2698
+ return;
2699
+ cleanup();
2700
+ resolve(response);
2701
+ };
2702
+ const rejectToken = (error) => {
2703
+ if (settled)
2704
+ return;
2705
+ cleanup();
2706
+ reject(error);
2707
+ };
2708
+ const timer = setTimeout(() => rejectToken(new AuthError(exports.AuthErrorCode.POPUP_BLOCKED, 'Google sign-in popup did not return a credential. Retry from a click.', exports.AuthProvider.GOOGLE)), 120000);
2709
+ this.pendingPopupReject = rejectToken;
2710
+ try {
2711
+ const client = oauth2.initTokenClient({
2712
+ client_id: clientId,
2713
+ scope: scopes.join(' '),
2714
+ hint: loginHint,
2715
+ hosted_domain: options.hostedDomain,
2716
+ include_granted_scopes: (_a = options.includeGrantedScopes) !== null && _a !== void 0 ? _a : true,
2717
+ callback: (response) => {
2718
+ if (response.error) {
2719
+ rejectToken(new AuthError(response.error === 'access_denied'
2720
+ ? exports.AuthErrorCode.USER_CANCELLED
2721
+ : exports.AuthErrorCode.SIGN_IN_FAILED, response.error_description || response.error, exports.AuthProvider.GOOGLE));
2722
+ return;
2723
+ }
2724
+ resolveToken(response);
2725
+ },
2726
+ error_callback: (error) => {
2727
+ var _a;
2728
+ const type = (_a = error === null || error === void 0 ? void 0 : error.type) !== null && _a !== void 0 ? _a : 'unknown';
2729
+ rejectToken(new AuthError(type === 'popup_closed'
2730
+ ? exports.AuthErrorCode.POPUP_CLOSED_BY_USER
2731
+ : type === 'popup_failed_to_open'
2732
+ ? exports.AuthErrorCode.POPUP_BLOCKED
2733
+ : exports.AuthErrorCode.SIGN_IN_FAILED, (error === null || error === void 0 ? void 0 : error.message) || `Google sign-in popup failed (${type})`, exports.AuthProvider.GOOGLE));
2734
+ },
2735
+ });
2736
+ client.requestAccessToken({
2737
+ prompt: options.autoSelectEnabled ? '' : 'select_account',
2738
+ });
2739
+ }
2740
+ catch (error) {
2741
+ rejectToken(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2742
+ }
2743
+ });
2744
+ const accessToken = tokenResponse.access_token;
2745
+ if (!accessToken) {
2746
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, 'Google returned no access token', exports.AuthProvider.GOOGLE);
2747
+ }
2748
+ const profile = await this.fetchUserInfo(accessToken);
2749
+ if (revision !== this.requestRevision) {
2750
+ throw new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', exports.AuthProvider.GOOGLE);
2751
+ }
2752
+ if (typeof profile.sub !== 'string' || !profile.sub) {
2753
+ throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Google userinfo is missing a subject', exports.AuthProvider.GOOGLE);
2754
+ }
2755
+ if (options.hostedDomain && profile.hd !== options.hostedDomain) {
2756
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Account is not in the required Google Workspace domain (${options.hostedDomain})`, exports.AuthProvider.GOOGLE);
2757
+ }
2758
+ const user = this.buildUser(profile);
2759
+ const expiresIn = Number(tokenResponse.expires_in);
2760
+ const credential = {
2761
+ providerId: 'google.com',
2762
+ signInMethod: 'google.com',
2763
+ accessToken,
2764
+ expiresAt: this.calculateTokenExpiry(Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined),
2765
+ tokenType: tokenResponse.token_type || 'Bearer',
2766
+ scope: tokenResponse.scope || scopes.join(' '),
2767
+ };
2768
+ this.lastCredential = credential;
2769
+ await this.setCurrentUser(user);
2770
+ return this.createAuthResult(user, credential, false);
2771
+ }
2772
+ async fetchUserInfo(accessToken) {
2773
+ let response;
2774
+ try {
2775
+ response = await fetch(USERINFO_ENDPOINT, {
2776
+ headers: { Authorization: `Bearer ${accessToken}` },
2777
+ signal: AbortSignal.timeout(15000),
2778
+ });
2779
+ }
2780
+ catch (error) {
2781
+ throw new AuthError(exports.AuthErrorCode.NETWORK_ERROR, `Could not reach Google userinfo: ${error instanceof Error ? error.message : String(error)}`, exports.AuthProvider.GOOGLE);
2782
+ }
2783
+ if (!response.ok) {
2784
+ throw new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, `Google userinfo request failed (${response.status})`, exports.AuthProvider.GOOGLE);
2785
+ }
2786
+ return (await response.json());
2787
+ }
2788
+ // --- internals -----------------------------------------------------------------------------------
2789
+ requireClientId() {
2790
+ const options = this.options;
2791
+ if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
2792
+ throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', exports.AuthProvider.GOOGLE);
2793
+ }
2794
+ return options.clientId;
2795
+ }
2376
2796
  requireIdApi() {
2377
2797
  var _a, _b;
2378
2798
  const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
@@ -2381,15 +2801,13 @@ Note: This provider requires a backend service to handle authentication.
2381
2801
  }
2382
2802
  return api;
2383
2803
  }
2384
- configureIdClient() {
2804
+ configureIdClient(loginHint) {
2385
2805
  var _a;
2386
2806
  const options = this.options;
2387
- if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
2388
- throw new AuthError(exports.AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', exports.AuthProvider.GOOGLE);
2389
- }
2807
+ const clientId = this.requireClientId();
2390
2808
  this.currentNonce = options.nonce;
2391
2809
  const config = {
2392
- client_id: options.clientId,
2810
+ client_id: clientId,
2393
2811
  callback: (response) => this.handleCredential(response),
2394
2812
  auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
2395
2813
  cancel_on_tap_outside: false,
@@ -2400,41 +2818,25 @@ Note: This provider requires a backend service to handle authentication.
2400
2818
  if (options.nonce) {
2401
2819
  config.nonce = options.nonce;
2402
2820
  }
2403
- if (options.loginHint) {
2404
- config.login_hint = options.loginHint;
2821
+ const hint = loginHint !== null && loginHint !== void 0 ? loginHint : options.loginHint;
2822
+ if (hint) {
2823
+ config.login_hint = hint;
2405
2824
  }
2406
2825
  if (options.hostedDomain) {
2407
2826
  config.hd = options.hostedDomain;
2408
2827
  }
2409
2828
  this.requireIdApi().initialize(config);
2410
2829
  }
2411
- async handleCredential(response) {
2412
- if (response.error || !response.credential) {
2413
- this.rejectPending(new AuthError(exports.AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
2414
- response.error ||
2415
- 'No Google ID token returned', exports.AuthProvider.GOOGLE));
2416
- return;
2417
- }
2830
+ validateIdToken(idToken) {
2831
+ let claims;
2418
2832
  try {
2419
- const idToken = response.credential;
2420
- const claims = this.validateIdToken(idToken);
2421
- const user = this.buildUser(claims);
2422
- const credential = {
2423
- providerId: 'google.com',
2424
- signInMethod: 'google.com',
2425
- idToken,
2426
- tokenType: 'Bearer',
2427
- scope: 'openid email profile',
2428
- };
2429
- await this.setCurrentUser(user);
2430
- this.resolvePending(this.createAuthResult(user, credential, false));
2833
+ claims = decodeJwtPayload(idToken);
2834
+ if (!claims || typeof claims !== 'object' || Array.isArray(claims))
2835
+ throw new Error('Invalid claims');
2431
2836
  }
2432
- catch (error) {
2433
- this.rejectPending(AuthError.fromError(error, exports.AuthProvider.GOOGLE));
2837
+ catch (_a) {
2838
+ throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', exports.AuthProvider.GOOGLE);
2434
2839
  }
2435
- }
2436
- validateIdToken(idToken) {
2437
- const claims = decodeJwtPayload(idToken);
2438
2840
  const options = this.options;
2439
2841
  const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
2440
2842
  if (!claims.iss || !validIssuers.includes(claims.iss)) {
@@ -2443,13 +2845,22 @@ Note: This provider requires a backend service to handle authentication.
2443
2845
  if (claims.aud !== options.clientId) {
2444
2846
  throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', exports.AuthProvider.GOOGLE);
2445
2847
  }
2446
- if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
2848
+ if (typeof claims.exp !== 'number' ||
2849
+ !Number.isFinite(claims.exp) ||
2850
+ typeof claims.sub !== 'string' ||
2851
+ !claims.sub) {
2852
+ throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Google ID token is missing required exp or sub claims', exports.AuthProvider.GOOGLE);
2853
+ }
2854
+ if (claims.exp * 1000 <= Date.now()) {
2447
2855
  throw new AuthError(exports.AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', exports.AuthProvider.GOOGLE);
2448
2856
  }
2449
2857
  // Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
2450
- if (this.currentNonce && claims.nonce && claims.nonce !== this.currentNonce) {
2858
+ if (this.currentNonce && claims.nonce !== this.currentNonce) {
2451
2859
  throw new AuthError(exports.AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', exports.AuthProvider.GOOGLE);
2452
2860
  }
2861
+ if (options.hostedDomain && claims.hd !== options.hostedDomain) {
2862
+ throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Google ID token does not match the required Workspace domain', exports.AuthProvider.GOOGLE);
2863
+ }
2453
2864
  return claims;
2454
2865
  }
2455
2866
  buildUser(claims) {
@@ -2461,6 +2872,7 @@ Note: This provider requires a backend service to handle authentication.
2461
2872
  [claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
2462
2873
  null;
2463
2874
  const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
2875
+ const now = new Date().toISOString();
2464
2876
  return {
2465
2877
  uid,
2466
2878
  email,
@@ -2481,18 +2893,20 @@ Note: This provider requires a backend service to handle authentication.
2481
2893
  },
2482
2894
  ],
2483
2895
  metadata: {
2484
- creationTime: new Date().toISOString(),
2485
- lastSignInTime: new Date().toISOString(),
2896
+ creationTime: now,
2897
+ lastSignInTime: now,
2486
2898
  },
2487
2899
  };
2488
2900
  }
2489
2901
  resolvePending(result) {
2902
+ this.clearPendingTimer();
2490
2903
  const resolve = this.pendingResolve;
2491
2904
  this.pendingResolve = null;
2492
2905
  this.pendingReject = null;
2493
2906
  resolve === null || resolve === void 0 ? void 0 : resolve(result);
2494
2907
  }
2495
2908
  rejectPending(error) {
2909
+ this.clearPendingTimer();
2496
2910
  const reject = this.pendingReject;
2497
2911
  this.pendingResolve = null;
2498
2912
  this.pendingReject = null;
@@ -2503,6 +2917,22 @@ Note: This provider requires a backend service to handle authentication.
2503
2917
  this.logger.error('Google sign-in error with no pending request', error);
2504
2918
  }
2505
2919
  }
2920
+ clearPendingTimer() {
2921
+ if (this.pendingTimer !== null)
2922
+ clearTimeout(this.pendingTimer);
2923
+ this.pendingTimer = null;
2924
+ }
2925
+ dispose() {
2926
+ var _a, _b, _c, _d;
2927
+ this.requestRevision++;
2928
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', exports.AuthProvider.GOOGLE));
2929
+ if (this.pendingReject) {
2930
+ this.rejectPending(new AuthError(exports.AuthErrorCode.USER_CANCELLED, 'Google sign-in was disposed', exports.AuthProvider.GOOGLE));
2931
+ (_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();
2932
+ }
2933
+ this.lastCredential = null;
2934
+ super.dispose();
2935
+ }
2506
2936
  loadGsi() {
2507
2937
  var _a, _b;
2508
2938
  if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
@@ -2512,29 +2942,39 @@ Note: This provider requires a backend service to handle authentication.
2512
2942
  return this.loadPromise;
2513
2943
  }
2514
2944
  this.loadPromise = new Promise((resolve, reject) => {
2515
- var _a, _b;
2516
2945
  const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
2946
+ const script = existing !== null && existing !== void 0 ? existing : document.createElement('script');
2947
+ const cleanup = () => {
2948
+ clearTimeout(timer);
2949
+ script.removeEventListener('load', onReady);
2950
+ script.removeEventListener('error', onError);
2951
+ };
2517
2952
  const onReady = () => {
2518
2953
  var _a, _b;
2519
- return ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
2520
- ? resolve()
2521
- : reject(new Error('Google Identity Services failed to load'));
2522
- };
2523
- if (existing) {
2524
- existing.addEventListener('load', onReady, { once: true });
2525
- existing.addEventListener('error', () => reject(new Error('Failed to load Google Identity Services')), { once: true });
2526
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
2954
+ cleanup();
2955
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
2527
2956
  resolve();
2957
+ else {
2958
+ if (!existing)
2959
+ script.remove();
2960
+ reject(new Error('Google Identity Services failed to load'));
2528
2961
  }
2529
- return;
2962
+ };
2963
+ const onError = () => {
2964
+ cleanup();
2965
+ if (!existing)
2966
+ script.remove();
2967
+ reject(new AuthError(exports.AuthErrorCode.NETWORK_ERROR, 'Failed to load Google Identity Services', exports.AuthProvider.GOOGLE));
2968
+ };
2969
+ const timer = setTimeout(onError, 15000);
2970
+ script.addEventListener('load', onReady, { once: true });
2971
+ script.addEventListener('error', onError, { once: true });
2972
+ if (!existing) {
2973
+ script.src = GSI_SRC;
2974
+ script.async = true;
2975
+ script.defer = true;
2976
+ document.head.appendChild(script);
2530
2977
  }
2531
- const script = document.createElement('script');
2532
- script.src = GSI_SRC;
2533
- script.async = true;
2534
- script.defer = true;
2535
- script.onload = onReady;
2536
- script.onerror = () => reject(new Error('Failed to load Google Identity Services'));
2537
- document.head.appendChild(script);
2538
2978
  }).finally(() => {
2539
2979
  this.loadPromise = null;
2540
2980
  });
@@ -2548,8 +2988,6 @@ Note: This provider requires a backend service to handle authentication.
2548
2988
  throw new AuthError(exports.AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', exports.AuthProvider.GOOGLE);
2549
2989
  }
2550
2990
  if (typeof atob !== 'function') {
2551
- // This provider only runs in the browser (the registry routes native platforms to the native
2552
- // bridge); `atob` is always present there.
2553
2991
  throw new AuthError(exports.AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', exports.AuthProvider.GOOGLE);
2554
2992
  }
2555
2993
  const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');