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/core.cjs.js CHANGED
@@ -360,17 +360,15 @@ class WebStorage {
360
360
  this.logger = logger;
361
361
  switch (persistence) {
362
362
  case AuthPersistence.SESSION:
363
- this.storage = window.sessionStorage;
364
- break;
365
- case AuthPersistence.LOCAL:
366
- this.storage = window.localStorage;
363
+ this.storage = resolveBrowserStorage('sessionStorage');
367
364
  break;
368
365
  case AuthPersistence.NONE:
369
366
  // Use in-memory storage
370
367
  this.storage = new InMemoryStorage();
371
368
  break;
369
+ case AuthPersistence.LOCAL:
372
370
  default:
373
- this.storage = window.localStorage;
371
+ this.storage = resolveBrowserStorage('localStorage');
374
372
  }
375
373
  }
376
374
  async get(key) {
@@ -425,6 +423,32 @@ class WebStorage {
425
423
  }
426
424
  }
427
425
  }
426
+ /**
427
+ * Returns the requested browser storage when it exists AND is usable, otherwise an in-memory
428
+ * fallback. Two environments make the fallback necessary:
429
+ * - Node / SSR / test runners: `window` is undefined, so the old unguarded `window.localStorage`
430
+ * read threw `ReferenceError: window is not defined` at import time (ISSUE-002).
431
+ * - Browsers that expose the API but refuse it (Safari private mode, cookies disabled, sandboxed
432
+ * iframes): `getItem`/`setItem` throw, so the probe below catches that and degrades gracefully.
433
+ */
434
+ function resolveBrowserStorage(kind) {
435
+ if (typeof window === 'undefined') {
436
+ return new InMemoryStorage();
437
+ }
438
+ try {
439
+ const candidate = window[kind];
440
+ if (!candidate) {
441
+ return new InMemoryStorage();
442
+ }
443
+ const probeKey = '__cap_auth_probe__';
444
+ candidate.setItem(probeKey, '1');
445
+ candidate.removeItem(probeKey);
446
+ return candidate;
447
+ }
448
+ catch (_a) {
449
+ return new InMemoryStorage();
450
+ }
451
+ }
428
452
  class InMemoryStorage {
429
453
  constructor() {
430
454
  this.data = new Map();
@@ -662,28 +686,27 @@ const BUILT_IN_PROVIDER_MANIFESTS = [
662
686
  {
663
687
  name: 'google',
664
688
  displayName: 'Google',
665
- packageName: '@google/gsi',
666
689
  setupInstructions: `
667
- To use Google authentication, you need to:
690
+ To use Google authentication:
668
691
 
669
- 1. Install the Google Sign-In SDK:
670
- npm install @google/gsi
692
+ 1. Create (or reuse) an OAuth 2.0 **Web** client in Google Cloud Console — Firebase creates one for you
693
+ when you enable the Google sign-in provider. Add your site origins (including your dev server, e.g.
694
+ http://localhost:5931) under "Authorized JavaScript origins".
671
695
 
672
- 2. Configure your Google OAuth client:
673
- - Go to https://console.cloud.google.com/
674
- - Create or select a project
675
- - Enable Google Sign-In API
676
- - Create OAuth 2.0 credentials
677
- - Add authorized JavaScript origins
678
-
679
- 3. Configure the provider:
696
+ 2. Configure the provider (no extra npm package is needed — the Google Identity Services script is
697
+ loaded on demand on web; the native SDKs ship with the plugin):
680
698
  auth.configure({
681
699
  providers: {
682
700
  google: {
683
- clientId: 'YOUR_CLIENT_ID'
701
+ clientId: 'YOUR_WEB_CLIENT_ID', // web + Android serverClientId fallback
702
+ serverClientId: 'YOUR_WEB_CLIENT_ID', // Android
703
+ iosClientId: 'YOUR_IOS_CLIENT_ID', // iOS (or GIDClientID in Info.plist)
684
704
  }
685
705
  }
686
706
  })
707
+
708
+ 3. Android: register your signing key's SHA-1 in Firebase / Google Cloud. iOS: add the reversed
709
+ client id as a URL scheme.
687
710
  `,
688
711
  platforms: ['web', 'ios', 'android'],
689
712
  configSchema: {
@@ -1138,7 +1161,26 @@ class ProviderRegistry {
1138
1161
  return (_b = this.NAME_ALIASES[name]) !== null && _b !== void 0 ? _b : name;
1139
1162
  }
1140
1163
  static async getProvider(name, options, deps) {
1141
- var _b, _c;
1164
+ const key = this.canonicalName(name);
1165
+ const existing = this.providers.get(key);
1166
+ if (existing)
1167
+ return existing;
1168
+ const pending = this.pending.get(key);
1169
+ if (pending)
1170
+ return pending;
1171
+ const promise = this.createProvider(name, options, deps);
1172
+ this.pending.set(key, promise);
1173
+ try {
1174
+ return await promise;
1175
+ }
1176
+ finally {
1177
+ if (this.pending.get(key) === promise)
1178
+ this.pending.delete(key);
1179
+ }
1180
+ }
1181
+ static async createProvider(name, options, deps) {
1182
+ var _b, _c, _d;
1183
+ const generation = this.generation;
1142
1184
  const key = this.canonicalName(name);
1143
1185
  // Check if already loaded
1144
1186
  const existing = this.providers.get(key);
@@ -1196,6 +1238,10 @@ class ProviderRegistry {
1196
1238
  if (provider.initialize) {
1197
1239
  await provider.initialize();
1198
1240
  }
1241
+ if (generation !== this.generation) {
1242
+ (_d = provider.dispose) === null || _d === void 0 ? void 0 : _d.call(provider);
1243
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Provider configuration changed during initialization');
1244
+ }
1199
1245
  // Cache the provider under its canonical key
1200
1246
  this.providers.set(key, provider);
1201
1247
  return provider;
@@ -1217,7 +1263,9 @@ class ProviderRegistry {
1217
1263
  }
1218
1264
  }
1219
1265
  static clearProvider(name) {
1266
+ this.generation++;
1220
1267
  const key = this.canonicalName(name);
1268
+ this.pending.delete(key);
1221
1269
  const provider = this.providers.get(key);
1222
1270
  if (provider === null || provider === void 0 ? void 0 : provider.dispose) {
1223
1271
  provider.dispose();
@@ -1225,6 +1273,8 @@ class ProviderRegistry {
1225
1273
  this.providers.delete(key);
1226
1274
  }
1227
1275
  static clearAll() {
1276
+ this.generation++;
1277
+ this.pending.clear();
1228
1278
  for (const [, provider] of this.providers) {
1229
1279
  if (provider.dispose) {
1230
1280
  provider.dispose();
@@ -1239,6 +1289,8 @@ class ProviderRegistry {
1239
1289
  const platform = PlatformDetector.getPlatform();
1240
1290
  const supported = [];
1241
1291
  for (const [name, manifest] of this.manifests) {
1292
+ if (!this.loaders.has(name))
1293
+ continue;
1242
1294
  if (!manifest.platforms ||
1243
1295
  manifest.platforms.includes(platform.platform)) {
1244
1296
  supported.push(name);
@@ -1249,6 +1301,8 @@ class ProviderRegistry {
1249
1301
  }
1250
1302
  _a = ProviderRegistry;
1251
1303
  ProviderRegistry.providers = new Map();
1304
+ ProviderRegistry.pending = new Map();
1305
+ ProviderRegistry.generation = 0;
1252
1306
  ProviderRegistry.loaders = new Map();
1253
1307
  ProviderRegistry.manifests = new Map();
1254
1308
  /** Providers constructed with their raw options object (not a BaseProviderConfig wrapper). */
@@ -1349,6 +1403,7 @@ class AuthManagerCore {
1349
1403
  this.isInitialized = false;
1350
1404
  this.tokenRefreshTimers = new Map();
1351
1405
  this.initPromise = null;
1406
+ this.sessionRevision = 0;
1352
1407
  this.logger = new Logger({
1353
1408
  enableLogging: false,
1354
1409
  logLevel: 'info',
@@ -1426,6 +1481,8 @@ class AuthManagerCore {
1426
1481
  async signIn(providerOrOptions) {
1427
1482
  var _a, _b, _c;
1428
1483
  await this.ensureInitialized();
1484
+ this.assertIdle();
1485
+ this.sessionRevision++;
1429
1486
  let providerName;
1430
1487
  let signInOptions = {};
1431
1488
  if (typeof providerOrOptions === 'string') {
@@ -1488,9 +1545,16 @@ class AuthManagerCore {
1488
1545
  throw AuthError.fromError(error);
1489
1546
  }
1490
1547
  }
1548
+ /** Load the provider SDK before a user gesture, without opening a sign-in prompt. */
1549
+ async prepare(provider) {
1550
+ await this.ensureInitialized();
1551
+ await this.resolveProvider(provider);
1552
+ }
1491
1553
  async signOut(options) {
1492
1554
  var _a;
1493
1555
  await this.ensureInitialized();
1556
+ this.assertIdle();
1557
+ this.sessionRevision++;
1494
1558
  const provider = (options === null || options === void 0 ? void 0 : options.provider) || this.state.provider;
1495
1559
  if (!provider) {
1496
1560
  this.logger.warn('No active auth session to sign out from');
@@ -1706,7 +1770,8 @@ class AuthManagerCore {
1706
1770
  throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No authenticated user to delete');
1707
1771
  }
1708
1772
  const provider = await this.resolveProvider(targetProvider);
1709
- const deleteFn = provider.deleteAccount;
1773
+ const deleteFn = provider
1774
+ .deleteAccount;
1710
1775
  if (typeof deleteFn !== 'function') {
1711
1776
  throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, `deleteAccount not supported for ${targetProvider}`);
1712
1777
  }
@@ -1760,7 +1825,11 @@ class AuthManagerCore {
1760
1825
  }
1761
1826
  }
1762
1827
  getProviderDeps() {
1763
- return { storage: this.storage, logger: this.logger };
1828
+ return {
1829
+ storage: this.storage,
1830
+ logger: this.logger,
1831
+ persistence: toAuthPersistence(this.config.persistence),
1832
+ };
1764
1833
  }
1765
1834
  /**
1766
1835
  * Resolves a provider instance through the registry, threading the configured options and the
@@ -1794,6 +1863,7 @@ class AuthManagerCore {
1794
1863
  }
1795
1864
  async restoreAuthState() {
1796
1865
  var _a, _b;
1866
+ const revision = this.sessionRevision;
1797
1867
  try {
1798
1868
  const stored = await this.storage.get('auth_state');
1799
1869
  if ((stored === null || stored === void 0 ? void 0 : stored.user) && (stored === null || stored === void 0 ? void 0 : stored.provider)) {
@@ -1803,7 +1873,7 @@ class AuthManagerCore {
1803
1873
  try {
1804
1874
  const provider = await ProviderRegistry.getProvider(stored.provider, providerConfig, this.getProviderDeps());
1805
1875
  const currentUser = await provider.getCurrentUser();
1806
- if (currentUser) {
1876
+ if (currentUser && revision === this.sessionRevision) {
1807
1877
  this.updateState({
1808
1878
  user: currentUser,
1809
1879
  isAuthenticated: true,
@@ -1818,7 +1888,8 @@ class AuthManagerCore {
1818
1888
  }
1819
1889
  catch (error) {
1820
1890
  this.logger.warn('Failed to restore auth session:', error);
1821
- await this.storage.remove('auth_state');
1891
+ if (revision === this.sessionRevision)
1892
+ await this.storage.remove('auth_state');
1822
1893
  }
1823
1894
  }
1824
1895
  }
@@ -1827,6 +1898,11 @@ class AuthManagerCore {
1827
1898
  this.logger.error('Failed to restore auth state:', error);
1828
1899
  }
1829
1900
  }
1901
+ assertIdle() {
1902
+ if (this.state.isLoading) {
1903
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'An authentication operation is already in progress');
1904
+ }
1905
+ }
1830
1906
  setupTokenRefresh(provider, credential) {
1831
1907
  this.clearTokenRefresh(provider);
1832
1908
  if (!credential.expiresAt || !credential.refreshToken) {
@@ -1880,6 +1956,7 @@ class AuthManagerCore {
1880
1956
  this.tokenRefreshTimers.clear();
1881
1957
  }
1882
1958
  dispose() {
1959
+ this.sessionRevision++;
1883
1960
  // Clear all timers
1884
1961
  for (const timer of this.tokenRefreshTimers.values()) {
1885
1962
  clearTimeout(timer);
@@ -1891,8 +1968,57 @@ class AuthManagerCore {
1891
1968
  this.stateEmitter.clear();
1892
1969
  }
1893
1970
  }
1894
- // Create singleton instance
1895
- const auth = new AuthManagerCore();
1971
+ let instance = null;
1972
+ /**
1973
+ * Returns the process-wide auth manager, constructing it on first call.
1974
+ *
1975
+ * The singleton is created lazily on purpose (ISSUE-002): constructing it eagerly at module scope
1976
+ * built a `WebStorage` that read `window.localStorage` while the module was being evaluated, which
1977
+ * crashed any import under Node / SSR and made `"sideEffects": false` untrue. Nothing touches the
1978
+ * browser until the first real use.
1979
+ */
1980
+ function getAuth() {
1981
+ if (!instance) {
1982
+ instance = new AuthManagerCore();
1983
+ }
1984
+ return instance;
1985
+ }
1986
+ /**
1987
+ * The shared auth manager. Every property access is forwarded to the lazily-created instance, so
1988
+ * `import { auth } from 'capacitor-auth-manager'` keeps working unchanged while importing the
1989
+ * package has no side effects.
1990
+ */
1991
+ const auth = new Proxy({}, {
1992
+ get(_target, property) {
1993
+ const target = getAuth();
1994
+ const value = Reflect.get(target, property, target);
1995
+ return typeof value === 'function'
1996
+ ? value.bind(target)
1997
+ : value;
1998
+ },
1999
+ set(_target, property, value) {
2000
+ return Reflect.set(getAuth(), property, value);
2001
+ },
2002
+ has(_target, property) {
2003
+ return Reflect.has(getAuth(), property);
2004
+ },
2005
+ });
2006
+
2007
+ let plugin = null;
2008
+ function getPlugin() {
2009
+ plugin !== null && plugin !== void 0 ? plugin : (plugin = core.registerPlugin('CapacitorAuthManager', {
2010
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
2011
+ }));
2012
+ return plugin;
2013
+ }
2014
+ // Importing the package never registers a native plugin or touches a browser global.
2015
+ const CapacitorAuthManager = new Proxy({}, {
2016
+ get(_target, property) {
2017
+ const target = getPlugin();
2018
+ const value = Reflect.get(target, property, target);
2019
+ return typeof value === 'function' ? value.bind(target) : value;
2020
+ },
2021
+ });
1896
2022
 
1897
2023
  /**
1898
2024
  * Normalize a provider constructor argument into a full {@link BaseProviderConfig}.
@@ -1900,9 +2026,8 @@ const auth = new AuthManagerCore();
1900
2026
  * The standalone providers are public (exported from `capacitor-auth-manager/providers/web`) and
1901
2027
  * get constructed two ways: the factory/registry pass a full {@link BaseProviderConfig}, while
1902
2028
  * tests and direct consumers pass the provider's own bare options object. This helper accepts
1903
- * either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`, so it never
1904
- * touches `window` and stays safe under SSR / Node test environments) plus the shared
1905
- * {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
2029
+ * either — a bare object is wrapped with an in-memory storage (`AuthPersistence.NONE`) plus the
2030
+ * shared {@link defaultLogger}. Callers that pass a full config keep their injected storage/logger.
1906
2031
  */
1907
2032
  function resolveProviderConfig(provider, input) {
1908
2033
  if (typeof input === 'object' &&
@@ -2056,11 +2181,6 @@ class BaseAuthProvider {
2056
2181
  }
2057
2182
  }
2058
2183
 
2059
- // This provides backward compatibility for users who still want to use the Capacitor plugin interface
2060
- const CapacitorAuthManager = core.registerPlugin('CapacitorAuthManager', {
2061
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorAuthManagerWeb()),
2062
- });
2063
-
2064
2184
  /**
2065
2185
  * Native Google provider — the implementation the registry loads on **iOS / Android**.
2066
2186
  *
@@ -2089,6 +2209,7 @@ class GoogleNativeProvider extends BaseAuthProvider {
2089
2209
  // Hand the Google config (clientId / serverClientId / iosClientId / scopes) to the native side
2090
2210
  // once; subsequent signIn() calls only pass per-request SignInProviderOptions.
2091
2211
  await CapacitorAuthManager.initialize({
2212
+ persistence: this.persistence,
2092
2213
  providers: [
2093
2214
  {
2094
2215
  provider: AuthProvider.GOOGLE,
@@ -2108,9 +2229,16 @@ class GoogleNativeProvider extends BaseAuthProvider {
2108
2229
  await this.initialize();
2109
2230
  }
2110
2231
  try {
2232
+ // AuthManagerCore spreads the per-call `options` to the top level before calling us, so read
2233
+ // both shapes: a nested `options` object (direct plugin-style callers) or the flattened one.
2234
+ const source = (options !== null && options !== void 0 ? options : {});
2235
+ const { credentials, options: nested } = source;
2236
+ const flat = Object.fromEntries(Object.entries(source).filter(([key]) => !['provider', 'credentials', 'options'].includes(key)));
2237
+ const perCall = Object.assign(Object.assign({}, flat), (nested !== null && nested !== void 0 ? nested : {}));
2111
2238
  const result = await CapacitorAuthManager.signIn({
2112
2239
  provider: AuthProvider.GOOGLE,
2113
- options: options === null || options === void 0 ? void 0 : options.options,
2240
+ credentials,
2241
+ options: perCall,
2114
2242
  });
2115
2243
  await this.setCurrentUser(result.user);
2116
2244
  return result;
@@ -2144,9 +2272,45 @@ class GoogleNativeProvider extends BaseAuthProvider {
2144
2272
  throw AuthError.fromError(error, AuthProvider.GOOGLE);
2145
2273
  }
2146
2274
  }
2275
+ /**
2276
+ * The current Google ID token, refreshed through the platform SDK when `forceRefresh` is set.
2277
+ *
2278
+ * `AuthManagerCore.getIdToken` looks for this method on the resolved provider and throws
2279
+ * `OPERATION_NOT_ALLOWED` when it is missing, so without it `auth.getIdToken()` failed on iOS and
2280
+ * Android even though both native layers implement it — while the same call worked on web.
2281
+ *
2282
+ * Capacitor cannot resolve a bare string, so the native side answers `{ token }`; the web
2283
+ * fallback in `src/web.ts` resolves the string itself. Read both shapes.
2284
+ */
2285
+ async getIdToken(forceRefresh = false) {
2286
+ var _a;
2287
+ if (!this.isInitialized) {
2288
+ await this.initialize();
2289
+ }
2290
+ try {
2291
+ const raw = (await CapacitorAuthManager.getIdToken({
2292
+ provider: AuthProvider.GOOGLE,
2293
+ forceRefresh,
2294
+ }));
2295
+ const token = typeof raw === 'string' ? raw : ((_a = raw === null || raw === void 0 ? void 0 : raw.token) !== null && _a !== void 0 ? _a : '');
2296
+ if (!token) {
2297
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available. Sign in again.', AuthProvider.GOOGLE);
2298
+ }
2299
+ return token;
2300
+ }
2301
+ catch (error) {
2302
+ throw AuthError.fromError(error, AuthProvider.GOOGLE);
2303
+ }
2304
+ }
2147
2305
  async getCurrentUser() {
2148
2306
  try {
2149
- const user = await CapacitorAuthManager.getCurrentUser();
2307
+ const raw = (await CapacitorAuthManager.getCurrentUser());
2308
+ // A Capacitor call cannot resolve `null`; the native side answers `{}` when nobody is signed
2309
+ // in. Treat anything without a string `uid` as "no user" — otherwise the empty object was
2310
+ // taken as a user and the app restored an authenticated state with no account behind it.
2311
+ const user = raw && typeof raw.uid === 'string' && raw.uid.length > 0
2312
+ ? raw
2313
+ : null;
2150
2314
  this.currentUser = user;
2151
2315
  return user;
2152
2316
  }
@@ -2178,27 +2342,42 @@ var googleNativeProvider = /*#__PURE__*/Object.freeze({
2178
2342
  });
2179
2343
 
2180
2344
  const GSI_SRC = 'https://accounts.google.com/gsi/client';
2345
+ const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/userinfo';
2346
+ const DEFAULT_SCOPES = ['openid', 'email', 'profile'];
2181
2347
  /**
2182
2348
  * Web Google provider — the implementation the registry loads on **web / electron**.
2183
2349
  *
2184
- * Uses the **Google Identity Services ID-token flow** (`google.accounts.id`): no client secret, no
2185
- * backend, no popup-blocker problems. The browser returns a Google **ID token** (JWT) which is
2186
- * surfaced as `result.credential.idToken` — the SAME field the native providers populate — so the
2187
- * Firebase handoff is identical on every platform:
2350
+ * Two Google Identity Services flows are available, selected by {@link GoogleAuthOptions.webFlow}
2351
+ * (default `'auto'`):
2352
+ *
2353
+ * 1. **One-Tap / FedCM id-token flow** (`google.accounts.id`): returns a Google **ID token** (JWT) as
2354
+ * `result.credential.idToken` — the same field the native providers populate.
2355
+ * 2. **OAuth2 popup flow** (`google.accounts.oauth2.initTokenClient`): a deterministic popup that works
2356
+ * from any click handler and returns an **access token** as `result.credential.accessToken`; the user
2357
+ * profile is read from Google's `userinfo` endpoint. `'auto'` falls back to this whenever the browser
2358
+ * does not display One-Tap (cooldown, FedCM opt-out, third-party-cookie settings).
2188
2359
  *
2189
- * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(result.credential.idToken));
2360
+ * Either credential is accepted by Firebase — the handoff is identical on every platform:
2190
2361
  *
2191
- * The id-token flow does NOT return an OAuth `accessToken` (use the GIS token client separately if you
2192
- * need to call Google APIs from the browser). Sign-in is triggered via One-Tap / FedCM `prompt()`; for a
2193
- * guaranteed button UX call {@link renderButton} to render Google's official button (same callback).
2362
+ * const { idToken, accessToken } = result.credential;
2363
+ * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(idToken ?? null, accessToken));
2364
+ *
2365
+ * Neither flow needs a client secret or a backend. For Google's official button call
2366
+ * {@link renderButton}; it shares the One-Tap credential callback.
2194
2367
  */
2195
2368
  class GoogleAuthProviderWeb extends BaseAuthProvider {
2196
2369
  constructor(config) {
2197
- super(config);
2370
+ super(resolveProviderConfig(AuthProvider.GOOGLE, config));
2198
2371
  this.loadPromise = null;
2199
2372
  /** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
2200
2373
  this.pendingResolve = null;
2201
2374
  this.pendingReject = null;
2375
+ /** Last credential issued in this page session (tokens are deliberately not persisted). */
2376
+ this.lastCredential = null;
2377
+ this.signingIn = false;
2378
+ this.pendingTimer = null;
2379
+ this.requestRevision = 0;
2380
+ this.pendingPopupReject = null;
2202
2381
  }
2203
2382
  get name() {
2204
2383
  return AuthProvider.GOOGLE;
@@ -2208,6 +2387,7 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2208
2387
  return;
2209
2388
  }
2210
2389
  try {
2390
+ this.requireClientId();
2211
2391
  await this.loadGsi();
2212
2392
  this.configureIdClient();
2213
2393
  await this.loadCurrentUser();
@@ -2218,45 +2398,34 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2218
2398
  throw AuthError.fromError(error, AuthProvider.GOOGLE);
2219
2399
  }
2220
2400
  }
2221
- async signIn(_options) {
2222
- if (!this.isInitialized) {
2223
- await this.initialize();
2401
+ async signIn(options) {
2402
+ var _a, _b, _c, _d, _e, _f, _g;
2403
+ if (this.signingIn) {
2404
+ throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'A Google sign-in is already in progress', AuthProvider.GOOGLE);
2224
2405
  }
2225
- this.configureIdClient();
2226
- return new Promise((resolve, reject) => {
2227
- this.pendingResolve = resolve;
2228
- this.pendingReject = (e) => reject(e);
2229
- const api = this.requireIdApi();
2230
- try {
2231
- api.prompt((notification) => {
2232
- var _a, _b, _c, _d, _e, _f, _g, _h;
2233
- // One-Tap was suppressed (cooldown / dismissed / FedCM opt-out): fail clearly so the
2234
- // consumer can fall back to renderButton(). Wrapped in try/catch because these moment
2235
- // methods are deprecated under FedCM and may throw.
2236
- try {
2237
- const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
2238
- const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
2239
- if (notDisplayed || skipped) {
2240
- 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';
2241
- this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Render the Google button via ` +
2242
- `provider.renderButton(element) for a guaranteed sign-in UI, or sign in on web ` +
2243
- `with your own Firebase popup.`, AuthProvider.GOOGLE));
2244
- }
2245
- }
2246
- catch (_j) {
2247
- // FedCM: moment methods unavailable — wait for the credential callback instead.
2248
- }
2249
- });
2406
+ this.signingIn = true;
2407
+ try {
2408
+ if (!this.isInitialized) {
2409
+ await this.initialize();
2250
2410
  }
2251
- catch (error) {
2252
- this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
2411
+ // AuthManagerCore spreads per-call options to the top level; direct callers nest them under
2412
+ // `options`. Read both shapes.
2413
+ const perCall = (options !== null && options !== void 0 ? options : {});
2414
+ 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';
2415
+ 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;
2416
+ if (flow === 'popup') {
2417
+ return await this.signInWithPopup(loginHint);
2253
2418
  }
2254
- });
2419
+ return await this.signInWithOneTap(flow === 'auto', loginHint);
2420
+ }
2421
+ finally {
2422
+ this.signingIn = false;
2423
+ }
2255
2424
  }
2256
2425
  /**
2257
- * Renders Google's official "Sign in with Google" button into `parent`. Use this when One-Tap is
2258
- * suppressed or you want a deterministic button. The button uses the SAME credential callback, so a
2259
- * click resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
2426
+ * Renders Google's official "Sign in with Google" button into `parent`. Use this when you want
2427
+ * Google's branded button rather than your own. It uses the SAME credential callback, so a click
2428
+ * resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
2260
2429
  */
2261
2430
  async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
2262
2431
  if (!this.isInitialized) {
@@ -2266,39 +2435,80 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2266
2435
  this.requireIdApi().renderButton(parent, options);
2267
2436
  }
2268
2437
  async signOut(_options) {
2269
- var _a, _b, _c;
2438
+ var _a, _b, _c, _d, _e, _f, _g;
2439
+ this.requestRevision++;
2440
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
2441
+ if (this.pendingReject) {
2442
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled by sign-out', AuthProvider.GOOGLE));
2443
+ (_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();
2444
+ }
2270
2445
  try {
2271
- (_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();
2446
+ (_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();
2272
2447
  }
2273
2448
  catch (error) {
2274
2449
  this.logger.warn('Google disableAutoSelect failed', error);
2275
2450
  }
2451
+ this.lastCredential = null;
2276
2452
  await this.clearStoredData();
2277
2453
  await this.setCurrentUser(null);
2278
2454
  }
2279
2455
  /**
2280
- * Web ID tokens cannot be refreshed silently — re-running One-Tap (with auto-select) re-issues a
2281
- * fresh ID token for a returning user. Falls back to a normal prompt if auto-select can't.
2456
+ * Web tokens cannot be refreshed silently without a backend — re-running the configured flow
2457
+ * (One-Tap auto-select for a returning user, or the popup) re-issues a fresh credential.
2282
2458
  */
2283
2459
  async refreshToken(_options) {
2284
2460
  return this.signIn();
2285
2461
  }
2462
+ /**
2463
+ * Returns the ID token from the current page session. `forceRefresh` (or an expired token) re-runs
2464
+ * One-Tap. Throws `NO_AUTH_SESSION` when the last sign-in was the popup flow, which issues no ID token.
2465
+ */
2466
+ async getIdToken(forceRefresh = false) {
2467
+ const cached = this.lastCredential;
2468
+ const expired = typeof (cached === null || cached === void 0 ? void 0 : cached.expiresAt) === 'number' && cached.expiresAt <= Date.now();
2469
+ if ((cached === null || cached === void 0 ? void 0 : cached.idToken) && !forceRefresh && !expired) {
2470
+ return cached.idToken;
2471
+ }
2472
+ if (cached && !cached.idToken && !forceRefresh) {
2473
+ 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);
2474
+ }
2475
+ const result = await this.signIn({
2476
+ provider: AuthProvider.GOOGLE,
2477
+ options: { webFlow: 'one-tap' },
2478
+ });
2479
+ if (!result.credential.idToken) {
2480
+ throw new AuthError(AuthErrorCode.NO_AUTH_SESSION, 'No Google ID token available', AuthProvider.GOOGLE);
2481
+ }
2482
+ return result.credential.idToken;
2483
+ }
2286
2484
  async revokeAccess(token) {
2287
- var _a, _b;
2288
- const user = (_a = this.currentUser) !== null && _a !== void 0 ? _a : (await this.getCurrentUser());
2289
- const hint = (_b = user === null || user === void 0 ? void 0 : user.email) !== null && _b !== void 0 ? _b : token;
2290
- if (!hint) {
2485
+ var _a, _b, _c, _d, _e;
2486
+ const accessToken = token !== null && token !== void 0 ? token : (_a = this.lastCredential) === null || _a === void 0 ? void 0 : _a.accessToken;
2487
+ const oauth2 = (_c = (_b = window.google) === null || _b === void 0 ? void 0 : _b.accounts) === null || _c === void 0 ? void 0 : _c.oauth2;
2488
+ if (accessToken && oauth2) {
2489
+ await new Promise((resolve) => {
2490
+ try {
2491
+ oauth2.revoke(accessToken, () => resolve());
2492
+ }
2493
+ catch (_a) {
2494
+ resolve();
2495
+ }
2496
+ });
2291
2497
  await this.signOut();
2292
2498
  return;
2293
2499
  }
2294
- await new Promise((resolve) => {
2295
- try {
2296
- this.requireIdApi().revoke(hint, () => resolve());
2297
- }
2298
- catch (_a) {
2299
- resolve();
2300
- }
2301
- });
2500
+ const user = (_d = this.currentUser) !== null && _d !== void 0 ? _d : (await this.getCurrentUser());
2501
+ const hint = (_e = user === null || user === void 0 ? void 0 : user.email) !== null && _e !== void 0 ? _e : token;
2502
+ if (hint) {
2503
+ await new Promise((resolve) => {
2504
+ try {
2505
+ this.requireIdApi().revoke(hint, () => resolve());
2506
+ }
2507
+ catch (_a) {
2508
+ resolve();
2509
+ }
2510
+ });
2511
+ }
2302
2512
  await this.signOut();
2303
2513
  }
2304
2514
  async isSupported() {
@@ -2313,7 +2523,217 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2313
2523
  return false;
2314
2524
  }
2315
2525
  }
2316
- // --- internals --------------------------------------------------------------------------------
2526
+ // --- One-Tap flow --------------------------------------------------------------------------------
2527
+ signInWithOneTap(fallbackToPopup, loginHint) {
2528
+ this.configureIdClient(loginHint);
2529
+ return new Promise((resolve, reject) => {
2530
+ this.pendingResolve = resolve;
2531
+ this.pendingReject = (e) => reject(e);
2532
+ this.pendingTimer = setTimeout(() => {
2533
+ var _a, _b, _c;
2534
+ 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));
2535
+ (_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();
2536
+ }, 120000);
2537
+ const fallback = (reason) => {
2538
+ this.logger.info(`Google One-Tap not shown (${reason}); using the popup flow`);
2539
+ // Drop the One-Tap resolvers so a late credential callback cannot double-resolve.
2540
+ this.pendingResolve = null;
2541
+ this.pendingReject = null;
2542
+ this.clearPendingTimer();
2543
+ this.signInWithPopup(loginHint).then(resolve, reject);
2544
+ };
2545
+ try {
2546
+ this.requireIdApi().prompt((notification) => {
2547
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
2548
+ // These moment methods are deprecated under FedCM and may throw — guard every call.
2549
+ try {
2550
+ const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
2551
+ const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
2552
+ if (notDisplayed || skipped) {
2553
+ 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';
2554
+ if (fallbackToPopup) {
2555
+ fallback(reason);
2556
+ }
2557
+ else {
2558
+ this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Use webFlow 'popup' or 'auto', or ` +
2559
+ `render Google's button via provider.renderButton(element).`, AuthProvider.GOOGLE));
2560
+ }
2561
+ return;
2562
+ }
2563
+ const dismissed = (_k = (_j = notification.isDismissedMoment) === null || _j === void 0 ? void 0 : _j.call(notification)) !== null && _k !== void 0 ? _k : false;
2564
+ if (dismissed) {
2565
+ const reason = (_m = (_l = notification.getDismissedReason) === null || _l === void 0 ? void 0 : _l.call(notification)) !== null && _m !== void 0 ? _m : '';
2566
+ // 'credential_returned' is the success path — the credential callback resolves it.
2567
+ if (reason !== 'credential_returned') {
2568
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, `Google One-Tap was dismissed (${reason || 'cancelled'})`, AuthProvider.GOOGLE));
2569
+ }
2570
+ }
2571
+ }
2572
+ catch (_o) {
2573
+ // FedCM: moment methods unavailable — wait for the credential callback instead.
2574
+ }
2575
+ });
2576
+ }
2577
+ catch (error) {
2578
+ if (fallbackToPopup) {
2579
+ fallback(error instanceof Error ? error.message : 'prompt failed');
2580
+ }
2581
+ else {
2582
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
2583
+ }
2584
+ }
2585
+ });
2586
+ }
2587
+ async handleCredential(response) {
2588
+ // Ignore a late callback after cancellation, timeout, or popup fallback.
2589
+ if (!this.pendingResolve)
2590
+ return;
2591
+ if (response.error || !response.credential) {
2592
+ this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
2593
+ response.error ||
2594
+ 'No Google ID token returned', AuthProvider.GOOGLE));
2595
+ return;
2596
+ }
2597
+ try {
2598
+ const idToken = response.credential;
2599
+ const claims = this.validateIdToken(idToken);
2600
+ const user = this.buildUser(claims);
2601
+ const credential = {
2602
+ providerId: 'google.com',
2603
+ signInMethod: 'google.com',
2604
+ idToken,
2605
+ expiresAt: typeof claims.exp === 'number' ? claims.exp * 1000 : undefined,
2606
+ tokenType: 'Bearer',
2607
+ scope: DEFAULT_SCOPES.join(' '),
2608
+ };
2609
+ this.lastCredential = credential;
2610
+ await this.setCurrentUser(user);
2611
+ this.resolvePending(this.createAuthResult(user, credential, false));
2612
+ }
2613
+ catch (error) {
2614
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
2615
+ }
2616
+ }
2617
+ // --- OAuth2 popup flow ---------------------------------------------------------------------------
2618
+ async signInWithPopup(loginHint) {
2619
+ var _a, _b, _c;
2620
+ const revision = this.requestRevision;
2621
+ const options = this.options;
2622
+ const clientId = this.requireClientId();
2623
+ await this.loadGsi();
2624
+ const oauth2 = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2;
2625
+ if (!oauth2) {
2626
+ throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services OAuth2 client not loaded', AuthProvider.GOOGLE);
2627
+ }
2628
+ const scopes = Array.from(new Set([...DEFAULT_SCOPES, ...((_c = options.scopes) !== null && _c !== void 0 ? _c : [])]));
2629
+ const tokenResponse = await new Promise((resolve, reject) => {
2630
+ var _a;
2631
+ let settled = false;
2632
+ const cleanup = () => {
2633
+ settled = true;
2634
+ clearTimeout(timer);
2635
+ this.pendingPopupReject = null;
2636
+ };
2637
+ const resolveToken = (response) => {
2638
+ if (settled)
2639
+ return;
2640
+ cleanup();
2641
+ resolve(response);
2642
+ };
2643
+ const rejectToken = (error) => {
2644
+ if (settled)
2645
+ return;
2646
+ cleanup();
2647
+ reject(error);
2648
+ };
2649
+ 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);
2650
+ this.pendingPopupReject = rejectToken;
2651
+ try {
2652
+ const client = oauth2.initTokenClient({
2653
+ client_id: clientId,
2654
+ scope: scopes.join(' '),
2655
+ hint: loginHint,
2656
+ hosted_domain: options.hostedDomain,
2657
+ include_granted_scopes: (_a = options.includeGrantedScopes) !== null && _a !== void 0 ? _a : true,
2658
+ callback: (response) => {
2659
+ if (response.error) {
2660
+ rejectToken(new AuthError(response.error === 'access_denied'
2661
+ ? AuthErrorCode.USER_CANCELLED
2662
+ : AuthErrorCode.SIGN_IN_FAILED, response.error_description || response.error, AuthProvider.GOOGLE));
2663
+ return;
2664
+ }
2665
+ resolveToken(response);
2666
+ },
2667
+ error_callback: (error) => {
2668
+ var _a;
2669
+ const type = (_a = error === null || error === void 0 ? void 0 : error.type) !== null && _a !== void 0 ? _a : 'unknown';
2670
+ rejectToken(new AuthError(type === 'popup_closed'
2671
+ ? AuthErrorCode.POPUP_CLOSED_BY_USER
2672
+ : type === 'popup_failed_to_open'
2673
+ ? AuthErrorCode.POPUP_BLOCKED
2674
+ : AuthErrorCode.SIGN_IN_FAILED, (error === null || error === void 0 ? void 0 : error.message) || `Google sign-in popup failed (${type})`, AuthProvider.GOOGLE));
2675
+ },
2676
+ });
2677
+ client.requestAccessToken({
2678
+ prompt: options.autoSelectEnabled ? '' : 'select_account',
2679
+ });
2680
+ }
2681
+ catch (error) {
2682
+ rejectToken(AuthError.fromError(error, AuthProvider.GOOGLE));
2683
+ }
2684
+ });
2685
+ const accessToken = tokenResponse.access_token;
2686
+ if (!accessToken) {
2687
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, 'Google returned no access token', AuthProvider.GOOGLE);
2688
+ }
2689
+ const profile = await this.fetchUserInfo(accessToken);
2690
+ if (revision !== this.requestRevision) {
2691
+ throw new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE);
2692
+ }
2693
+ if (typeof profile.sub !== 'string' || !profile.sub) {
2694
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google userinfo is missing a subject', AuthProvider.GOOGLE);
2695
+ }
2696
+ if (options.hostedDomain && profile.hd !== options.hostedDomain) {
2697
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Account is not in the required Google Workspace domain (${options.hostedDomain})`, AuthProvider.GOOGLE);
2698
+ }
2699
+ const user = this.buildUser(profile);
2700
+ const expiresIn = Number(tokenResponse.expires_in);
2701
+ const credential = {
2702
+ providerId: 'google.com',
2703
+ signInMethod: 'google.com',
2704
+ accessToken,
2705
+ expiresAt: this.calculateTokenExpiry(Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined),
2706
+ tokenType: tokenResponse.token_type || 'Bearer',
2707
+ scope: tokenResponse.scope || scopes.join(' '),
2708
+ };
2709
+ this.lastCredential = credential;
2710
+ await this.setCurrentUser(user);
2711
+ return this.createAuthResult(user, credential, false);
2712
+ }
2713
+ async fetchUserInfo(accessToken) {
2714
+ let response;
2715
+ try {
2716
+ response = await fetch(USERINFO_ENDPOINT, {
2717
+ headers: { Authorization: `Bearer ${accessToken}` },
2718
+ signal: AbortSignal.timeout(15000),
2719
+ });
2720
+ }
2721
+ catch (error) {
2722
+ throw new AuthError(AuthErrorCode.NETWORK_ERROR, `Could not reach Google userinfo: ${error instanceof Error ? error.message : String(error)}`, AuthProvider.GOOGLE);
2723
+ }
2724
+ if (!response.ok) {
2725
+ throw new AuthError(AuthErrorCode.SIGN_IN_FAILED, `Google userinfo request failed (${response.status})`, AuthProvider.GOOGLE);
2726
+ }
2727
+ return (await response.json());
2728
+ }
2729
+ // --- internals -----------------------------------------------------------------------------------
2730
+ requireClientId() {
2731
+ const options = this.options;
2732
+ if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
2733
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
2734
+ }
2735
+ return options.clientId;
2736
+ }
2317
2737
  requireIdApi() {
2318
2738
  var _a, _b;
2319
2739
  const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
@@ -2322,15 +2742,13 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2322
2742
  }
2323
2743
  return api;
2324
2744
  }
2325
- configureIdClient() {
2745
+ configureIdClient(loginHint) {
2326
2746
  var _a;
2327
2747
  const options = this.options;
2328
- if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
2329
- throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
2330
- }
2748
+ const clientId = this.requireClientId();
2331
2749
  this.currentNonce = options.nonce;
2332
2750
  const config = {
2333
- client_id: options.clientId,
2751
+ client_id: clientId,
2334
2752
  callback: (response) => this.handleCredential(response),
2335
2753
  auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
2336
2754
  cancel_on_tap_outside: false,
@@ -2341,41 +2759,25 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2341
2759
  if (options.nonce) {
2342
2760
  config.nonce = options.nonce;
2343
2761
  }
2344
- if (options.loginHint) {
2345
- config.login_hint = options.loginHint;
2762
+ const hint = loginHint !== null && loginHint !== void 0 ? loginHint : options.loginHint;
2763
+ if (hint) {
2764
+ config.login_hint = hint;
2346
2765
  }
2347
2766
  if (options.hostedDomain) {
2348
2767
  config.hd = options.hostedDomain;
2349
2768
  }
2350
2769
  this.requireIdApi().initialize(config);
2351
2770
  }
2352
- async handleCredential(response) {
2353
- if (response.error || !response.credential) {
2354
- this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
2355
- response.error ||
2356
- 'No Google ID token returned', AuthProvider.GOOGLE));
2357
- return;
2358
- }
2771
+ validateIdToken(idToken) {
2772
+ let claims;
2359
2773
  try {
2360
- const idToken = response.credential;
2361
- const claims = this.validateIdToken(idToken);
2362
- const user = this.buildUser(claims);
2363
- const credential = {
2364
- providerId: 'google.com',
2365
- signInMethod: 'google.com',
2366
- idToken,
2367
- tokenType: 'Bearer',
2368
- scope: 'openid email profile',
2369
- };
2370
- await this.setCurrentUser(user);
2371
- this.resolvePending(this.createAuthResult(user, credential, false));
2774
+ claims = decodeJwtPayload(idToken);
2775
+ if (!claims || typeof claims !== 'object' || Array.isArray(claims))
2776
+ throw new Error('Invalid claims');
2372
2777
  }
2373
- catch (error) {
2374
- this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
2778
+ catch (_a) {
2779
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
2375
2780
  }
2376
- }
2377
- validateIdToken(idToken) {
2378
- const claims = decodeJwtPayload(idToken);
2379
2781
  const options = this.options;
2380
2782
  const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
2381
2783
  if (!claims.iss || !validIssuers.includes(claims.iss)) {
@@ -2384,13 +2786,22 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2384
2786
  if (claims.aud !== options.clientId) {
2385
2787
  throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', AuthProvider.GOOGLE);
2386
2788
  }
2387
- if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
2789
+ if (typeof claims.exp !== 'number' ||
2790
+ !Number.isFinite(claims.exp) ||
2791
+ typeof claims.sub !== 'string' ||
2792
+ !claims.sub) {
2793
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token is missing required exp or sub claims', AuthProvider.GOOGLE);
2794
+ }
2795
+ if (claims.exp * 1000 <= Date.now()) {
2388
2796
  throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', AuthProvider.GOOGLE);
2389
2797
  }
2390
2798
  // Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
2391
- if (this.currentNonce && claims.nonce && claims.nonce !== this.currentNonce) {
2799
+ if (this.currentNonce && claims.nonce !== this.currentNonce) {
2392
2800
  throw new AuthError(AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', AuthProvider.GOOGLE);
2393
2801
  }
2802
+ if (options.hostedDomain && claims.hd !== options.hostedDomain) {
2803
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Google ID token does not match the required Workspace domain', AuthProvider.GOOGLE);
2804
+ }
2394
2805
  return claims;
2395
2806
  }
2396
2807
  buildUser(claims) {
@@ -2402,6 +2813,7 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2402
2813
  [claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
2403
2814
  null;
2404
2815
  const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
2816
+ const now = new Date().toISOString();
2405
2817
  return {
2406
2818
  uid,
2407
2819
  email,
@@ -2422,18 +2834,20 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2422
2834
  },
2423
2835
  ],
2424
2836
  metadata: {
2425
- creationTime: new Date().toISOString(),
2426
- lastSignInTime: new Date().toISOString(),
2837
+ creationTime: now,
2838
+ lastSignInTime: now,
2427
2839
  },
2428
2840
  };
2429
2841
  }
2430
2842
  resolvePending(result) {
2843
+ this.clearPendingTimer();
2431
2844
  const resolve = this.pendingResolve;
2432
2845
  this.pendingResolve = null;
2433
2846
  this.pendingReject = null;
2434
2847
  resolve === null || resolve === void 0 ? void 0 : resolve(result);
2435
2848
  }
2436
2849
  rejectPending(error) {
2850
+ this.clearPendingTimer();
2437
2851
  const reject = this.pendingReject;
2438
2852
  this.pendingResolve = null;
2439
2853
  this.pendingReject = null;
@@ -2444,6 +2858,22 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2444
2858
  this.logger.error('Google sign-in error with no pending request', error);
2445
2859
  }
2446
2860
  }
2861
+ clearPendingTimer() {
2862
+ if (this.pendingTimer !== null)
2863
+ clearTimeout(this.pendingTimer);
2864
+ this.pendingTimer = null;
2865
+ }
2866
+ dispose() {
2867
+ var _a, _b, _c, _d;
2868
+ this.requestRevision++;
2869
+ (_a = this.pendingPopupReject) === null || _a === void 0 ? void 0 : _a.call(this, new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was cancelled', AuthProvider.GOOGLE));
2870
+ if (this.pendingReject) {
2871
+ this.rejectPending(new AuthError(AuthErrorCode.USER_CANCELLED, 'Google sign-in was disposed', AuthProvider.GOOGLE));
2872
+ (_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();
2873
+ }
2874
+ this.lastCredential = null;
2875
+ super.dispose();
2876
+ }
2447
2877
  loadGsi() {
2448
2878
  var _a, _b;
2449
2879
  if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
@@ -2453,29 +2883,39 @@ class GoogleAuthProviderWeb extends BaseAuthProvider {
2453
2883
  return this.loadPromise;
2454
2884
  }
2455
2885
  this.loadPromise = new Promise((resolve, reject) => {
2456
- var _a, _b;
2457
2886
  const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
2887
+ const script = existing !== null && existing !== void 0 ? existing : document.createElement('script');
2888
+ const cleanup = () => {
2889
+ clearTimeout(timer);
2890
+ script.removeEventListener('load', onReady);
2891
+ script.removeEventListener('error', onError);
2892
+ };
2458
2893
  const onReady = () => {
2459
2894
  var _a, _b;
2460
- return ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
2461
- ? resolve()
2462
- : reject(new Error('Google Identity Services failed to load'));
2463
- };
2464
- if (existing) {
2465
- existing.addEventListener('load', onReady, { once: true });
2466
- existing.addEventListener('error', () => reject(new Error('Failed to load Google Identity Services')), { once: true });
2467
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
2895
+ cleanup();
2896
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
2468
2897
  resolve();
2898
+ else {
2899
+ if (!existing)
2900
+ script.remove();
2901
+ reject(new Error('Google Identity Services failed to load'));
2469
2902
  }
2470
- return;
2903
+ };
2904
+ const onError = () => {
2905
+ cleanup();
2906
+ if (!existing)
2907
+ script.remove();
2908
+ reject(new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to load Google Identity Services', AuthProvider.GOOGLE));
2909
+ };
2910
+ const timer = setTimeout(onError, 15000);
2911
+ script.addEventListener('load', onReady, { once: true });
2912
+ script.addEventListener('error', onError, { once: true });
2913
+ if (!existing) {
2914
+ script.src = GSI_SRC;
2915
+ script.async = true;
2916
+ script.defer = true;
2917
+ document.head.appendChild(script);
2471
2918
  }
2472
- const script = document.createElement('script');
2473
- script.src = GSI_SRC;
2474
- script.async = true;
2475
- script.defer = true;
2476
- script.onload = onReady;
2477
- script.onerror = () => reject(new Error('Failed to load Google Identity Services'));
2478
- document.head.appendChild(script);
2479
2919
  }).finally(() => {
2480
2920
  this.loadPromise = null;
2481
2921
  });
@@ -2489,8 +2929,6 @@ function decodeJwtPayload(jwt) {
2489
2929
  throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
2490
2930
  }
2491
2931
  if (typeof atob !== 'function') {
2492
- // This provider only runs in the browser (the registry routes native platforms to the native
2493
- // bridge); `atob` is always present there.
2494
2932
  throw new AuthError(AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', AuthProvider.GOOGLE);
2495
2933
  }
2496
2934
  const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
@@ -3107,6 +3545,8 @@ var web = /*#__PURE__*/Object.freeze({
3107
3545
  CapacitorAuthManagerWeb: CapacitorAuthManagerWeb
3108
3546
  });
3109
3547
 
3548
+ exports.CapacitorAuthManager = CapacitorAuthManager;
3110
3549
  exports.PlatformDetector = PlatformDetector;
3111
3550
  exports.ProviderRegistry = ProviderRegistry;
3112
3551
  exports.auth = auth;
3552
+ exports.getAuth = getAuth;