capacitor-auth-manager 2.4.0 → 2.4.1

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 (138) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/CapacitorAuthManager.podspec +1 -1
  3. package/LICENSE +1 -1
  4. package/Readme.md +136 -595
  5. package/android/build.gradle +8 -2
  6. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +43 -15
  7. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +24 -3
  8. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +427 -226
  9. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +28 -0
  10. package/dist/angular.cjs.js +942 -4545
  11. package/dist/core.cjs.js +913 -4515
  12. package/dist/esm/angular/auth.guard.js +0 -1
  13. package/dist/esm/angular/auth.module.js +0 -1
  14. package/dist/esm/angular/auth.service.js +0 -1
  15. package/dist/esm/angular/index.d.ts +1 -0
  16. package/dist/esm/angular/index.js +4 -1
  17. package/dist/esm/capacitor-plugin.js +0 -1
  18. package/dist/esm/core/auth-manager.d.ts +6 -0
  19. package/dist/esm/core/auth-manager.js +25 -4
  20. package/dist/esm/core/index.js +0 -1
  21. package/dist/esm/core/platform.js +0 -1
  22. package/dist/esm/core/provider-manifests.js +0 -1
  23. package/dist/esm/core/provider-registry.d.ts +7 -0
  24. package/dist/esm/core/provider-registry.js +55 -53
  25. package/dist/esm/core/types.js +0 -1
  26. package/dist/esm/definitions.d.ts +30 -1
  27. package/dist/esm/definitions.js +8 -1
  28. package/dist/esm/index.js +0 -1
  29. package/dist/esm/providers/base-provider.js +0 -1
  30. package/dist/esm/providers/native/google-native-provider.d.ts +26 -0
  31. package/dist/esm/providers/native/google-native-provider.js +114 -0
  32. package/dist/esm/providers/oauth-provider.js +0 -1
  33. package/dist/esm/providers/provider-factory.d.ts +9 -0
  34. package/dist/esm/providers/provider-factory.js +20 -57
  35. package/dist/esm/providers/web/google-provider.d.ts +70 -92
  36. package/dist/esm/providers/web/google-provider.js +262 -205
  37. package/dist/esm/providers/web/index.d.ts +0 -14
  38. package/dist/esm/providers/web/index.js +7 -16
  39. package/dist/esm/react/hooks.js +0 -1
  40. package/dist/esm/react/index.d.ts +1 -0
  41. package/dist/esm/react/index.js +4 -1
  42. package/dist/esm/react/types.js +0 -1
  43. package/dist/esm/utils/auth-error.js +0 -1
  44. package/dist/esm/utils/error-message.js +0 -1
  45. package/dist/esm/utils/event-emitter.js +0 -1
  46. package/dist/esm/utils/logger.js +0 -1
  47. package/dist/esm/utils/pending-verification-store.js +0 -1
  48. package/dist/esm/utils/storage.js +0 -1
  49. package/dist/esm/vue/composables.js +0 -1
  50. package/dist/esm/vue/index.d.ts +1 -0
  51. package/dist/esm/vue/index.js +4 -1
  52. package/dist/esm/web.js +0 -1
  53. package/dist/plugin.cjs.js +435 -4664
  54. package/dist/plugin.js +435 -4664
  55. package/dist/react.cjs.js +942 -4545
  56. package/dist/vue.cjs.js +942 -4545
  57. package/ios/Plugin/CapacitorAuthManager.swift +6 -6
  58. package/ios/Plugin/GoogleAuthProvider.swift +213 -105
  59. package/ios/Plugin/Models.swift +35 -4
  60. package/package.json +31 -30
  61. package/dist/angular.cjs.js.map +0 -1
  62. package/dist/core.cjs.js.map +0 -1
  63. package/dist/esm/angular/auth.guard.js.map +0 -1
  64. package/dist/esm/angular/auth.module.js.map +0 -1
  65. package/dist/esm/angular/auth.service.js.map +0 -1
  66. package/dist/esm/angular/index.js.map +0 -1
  67. package/dist/esm/capacitor-plugin.js.map +0 -1
  68. package/dist/esm/core/auth-manager.js.map +0 -1
  69. package/dist/esm/core/index.js.map +0 -1
  70. package/dist/esm/core/platform.js.map +0 -1
  71. package/dist/esm/core/provider-manifests.js.map +0 -1
  72. package/dist/esm/core/provider-registry.js.map +0 -1
  73. package/dist/esm/core/types.js.map +0 -1
  74. package/dist/esm/definitions.js.map +0 -1
  75. package/dist/esm/index.js.map +0 -1
  76. package/dist/esm/providers/base-provider.js.map +0 -1
  77. package/dist/esm/providers/oauth-provider.js.map +0 -1
  78. package/dist/esm/providers/provider-factory.js.map +0 -1
  79. package/dist/esm/providers/web/apple-provider.d.ts +0 -61
  80. package/dist/esm/providers/web/apple-provider.js +0 -293
  81. package/dist/esm/providers/web/apple-provider.js.map +0 -1
  82. package/dist/esm/providers/web/biometric-provider.d.ts +0 -60
  83. package/dist/esm/providers/web/biometric-provider.js +0 -374
  84. package/dist/esm/providers/web/biometric-provider.js.map +0 -1
  85. package/dist/esm/providers/web/email-code-provider.d.ts +0 -46
  86. package/dist/esm/providers/web/email-code-provider.js +0 -294
  87. package/dist/esm/providers/web/email-code-provider.js.map +0 -1
  88. package/dist/esm/providers/web/email-password-provider.d.ts +0 -52
  89. package/dist/esm/providers/web/email-password-provider.js +0 -430
  90. package/dist/esm/providers/web/email-password-provider.js.map +0 -1
  91. package/dist/esm/providers/web/facebook-provider.d.ts +0 -80
  92. package/dist/esm/providers/web/facebook-provider.js +0 -249
  93. package/dist/esm/providers/web/facebook-provider.js.map +0 -1
  94. package/dist/esm/providers/web/firebase-provider.d.ts +0 -22
  95. package/dist/esm/providers/web/firebase-provider.js +0 -338
  96. package/dist/esm/providers/web/firebase-provider.js.map +0 -1
  97. package/dist/esm/providers/web/github-provider.d.ts +0 -34
  98. package/dist/esm/providers/web/github-provider.js +0 -325
  99. package/dist/esm/providers/web/github-provider.js.map +0 -1
  100. package/dist/esm/providers/web/google-provider.js.map +0 -1
  101. package/dist/esm/providers/web/index.js.map +0 -1
  102. package/dist/esm/providers/web/linkedin-provider.d.ts +0 -37
  103. package/dist/esm/providers/web/linkedin-provider.js +0 -178
  104. package/dist/esm/providers/web/linkedin-provider.js.map +0 -1
  105. package/dist/esm/providers/web/magic-link-provider.d.ts +0 -44
  106. package/dist/esm/providers/web/magic-link-provider.js +0 -311
  107. package/dist/esm/providers/web/magic-link-provider.js.map +0 -1
  108. package/dist/esm/providers/web/microsoft-provider.d.ts +0 -23
  109. package/dist/esm/providers/web/microsoft-provider.js +0 -236
  110. package/dist/esm/providers/web/microsoft-provider.js.map +0 -1
  111. package/dist/esm/providers/web/phone-password-provider.d.ts +0 -63
  112. package/dist/esm/providers/web/phone-password-provider.js +0 -442
  113. package/dist/esm/providers/web/phone-password-provider.js.map +0 -1
  114. package/dist/esm/providers/web/slack-provider.d.ts +0 -39
  115. package/dist/esm/providers/web/slack-provider.js +0 -175
  116. package/dist/esm/providers/web/slack-provider.js.map +0 -1
  117. package/dist/esm/providers/web/sms-provider.d.ts +0 -46
  118. package/dist/esm/providers/web/sms-provider.js +0 -306
  119. package/dist/esm/providers/web/sms-provider.js.map +0 -1
  120. package/dist/esm/providers/web/username-password-provider.d.ts +0 -59
  121. package/dist/esm/providers/web/username-password-provider.js +0 -435
  122. package/dist/esm/providers/web/username-password-provider.js.map +0 -1
  123. package/dist/esm/react/hooks.js.map +0 -1
  124. package/dist/esm/react/index.js.map +0 -1
  125. package/dist/esm/react/types.js.map +0 -1
  126. package/dist/esm/utils/auth-error.js.map +0 -1
  127. package/dist/esm/utils/error-message.js.map +0 -1
  128. package/dist/esm/utils/event-emitter.js.map +0 -1
  129. package/dist/esm/utils/logger.js.map +0 -1
  130. package/dist/esm/utils/pending-verification-store.js.map +0 -1
  131. package/dist/esm/utils/storage.js.map +0 -1
  132. package/dist/esm/vue/composables.js.map +0 -1
  133. package/dist/esm/vue/index.js.map +0 -1
  134. package/dist/esm/web.js.map +0 -1
  135. package/dist/plugin.cjs.js.map +0 -1
  136. package/dist/plugin.js.map +0 -1
  137. package/dist/react.cjs.js.map +0 -1
  138. package/dist/vue.cjs.js.map +0 -1
@@ -1,272 +1,329 @@
1
1
  import { AuthProvider, AuthErrorCode, } from '../../definitions';
2
- import { OAuthProvider, } from '../oauth-provider';
2
+ import { BaseAuthProvider } from '../base-provider';
3
3
  import { AuthError } from '../../utils/auth-error';
4
- export class GoogleAuthProviderWeb extends OAuthProvider {
4
+ const GSI_SRC = 'https://accounts.google.com/gsi/client';
5
+ /**
6
+ * Web Google provider — the implementation the registry loads on **web / electron**.
7
+ *
8
+ * Uses the **Google Identity Services ID-token flow** (`google.accounts.id`): no client secret, no
9
+ * backend, no popup-blocker problems. The browser returns a Google **ID token** (JWT) which is
10
+ * surfaced as `result.credential.idToken` — the SAME field the native providers populate — so the
11
+ * Firebase handoff is identical on every platform:
12
+ *
13
+ * await signInWithCredential(getAuth(), GoogleAuthProvider.credential(result.credential.idToken));
14
+ *
15
+ * The id-token flow does NOT return an OAuth `accessToken` (use the GIS token client separately if you
16
+ * need to call Google APIs from the browser). Sign-in is triggered via One-Tap / FedCM `prompt()`; for a
17
+ * guaranteed button UX call {@link renderButton} to render Google's official button (same callback).
18
+ */
19
+ export class GoogleAuthProviderWeb extends BaseAuthProvider {
5
20
  constructor(config) {
6
21
  super(config);
7
- this.initPromise = null;
22
+ this.loadPromise = null;
23
+ /** Resolver for the in-flight sign-in; the GIS credential callback fulfils it. */
24
+ this.pendingResolve = null;
25
+ this.pendingReject = null;
8
26
  }
9
- getOAuthConfig() {
10
- const options = this.options;
11
- return {
12
- clientId: options.clientId,
13
- clientSecret: options.clientSecret,
14
- redirectUri: window.location.origin,
15
- authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
16
- tokenEndpoint: 'https://oauth2.googleapis.com/token',
17
- revokeEndpoint: 'https://oauth2.googleapis.com/revoke',
18
- userInfoEndpoint: 'https://www.googleapis.com/oauth2/v3/userinfo',
19
- scopes: options.scopes || ['openid', 'email', 'profile'],
20
- responseType: 'code',
21
- additionalParams: {
22
- access_type: options.offlineAccess ? 'offline' : 'online',
23
- include_granted_scopes: options.includeGrantedScopes ? 'true' : 'false',
24
- },
25
- };
27
+ get name() {
28
+ return AuthProvider.GOOGLE;
26
29
  }
27
30
  async initialize() {
28
31
  if (this.isInitialized) {
29
32
  return;
30
33
  }
31
- if (this.initPromise) {
32
- return this.initPromise;
33
- }
34
- this.initPromise = this._initialize();
35
- try {
36
- await this.initPromise;
37
- }
38
- finally {
39
- this.initPromise = null;
40
- }
41
- }
42
- async _initialize() {
43
- var _a, _b;
44
- const options = this.options;
45
34
  try {
46
- // Load Google Identity Services library
47
- await this.loadGoogleIdentityServices();
48
- // Initialize Google client
49
- if (!((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2)) {
50
- throw new Error('Google Identity Services not loaded');
51
- }
52
- window.google.accounts.oauth2.initCodeClient({
53
- client_id: options.clientId,
54
- scope: (options.scopes || ['openid', 'email', 'profile']).join(' '),
55
- ux_mode: 'popup',
56
- callback: (_response) => {
57
- // This callback will be overridden per sign-in
58
- },
59
- });
60
- // Load previously authenticated user
35
+ await this.loadGsi();
36
+ this.configureIdClient();
61
37
  await this.loadCurrentUser();
62
38
  this.isInitialized = true;
63
- this.logger.info('Google Auth provider initialized');
39
+ this.logger.info('Google (web) provider initialized');
64
40
  }
65
41
  catch (error) {
66
- this.logger.error('Failed to initialize Google Auth', error);
67
- throw AuthError.fromError(error, this.provider);
42
+ throw AuthError.fromError(error, AuthProvider.GOOGLE);
68
43
  }
69
44
  }
70
- async signIn(options) {
71
- this.validateInitialized();
45
+ async signIn(_options) {
46
+ if (!this.isInitialized) {
47
+ await this.initialize();
48
+ }
49
+ this.configureIdClient();
72
50
  return new Promise((resolve, reject) => {
73
- var _a, _b, _c, _d, _e;
51
+ this.pendingResolve = resolve;
52
+ this.pendingReject = (e) => reject(e);
53
+ const api = this.requireIdApi();
74
54
  try {
75
- const googleOptions = this.options;
76
- // Configure sign-in options
77
- const signInConfig = {
78
- client_id: googleOptions.clientId,
79
- scope: (((_a = options === null || options === void 0 ? void 0 : options.options) === null || _a === void 0 ? void 0 : _a.scopes) ||
80
- googleOptions.scopes || ['openid', 'email', 'profile']).join(' '),
81
- callback: async (response) => {
82
- if (response.error) {
83
- reject(new AuthError(this.mapGoogleError(response.error), response.error_description || response.error, this.provider));
84
- return;
85
- }
86
- try {
87
- // Exchange authorization code for tokens
88
- if (!response.code) {
89
- throw new AuthError(AuthErrorCode.INVALID_GRANT, 'No authorization code received', this.provider);
90
- }
91
- const tokenResponse = await this.exchangeCodeForTokens(response.code, this.getOAuthConfig());
92
- // Get user info
93
- const userInfo = await this.getUserInfo(tokenResponse.access_token);
94
- // Create AuthUser and AuthCredential
95
- const user = this.createAuthUser(userInfo, tokenResponse);
96
- const credential = this.createOAuthCredential(tokenResponse);
97
- // Save user and credential
98
- await this.setCurrentUser(user);
99
- await this.saveCredential(credential);
100
- resolve(this.createAuthResult(user, credential, false));
55
+ api.prompt((notification) => {
56
+ var _a, _b, _c, _d, _e, _f, _g, _h;
57
+ // One-Tap was suppressed (cooldown / dismissed / FedCM opt-out): fail clearly so the
58
+ // consumer can fall back to renderButton(). Wrapped in try/catch because these moment
59
+ // methods are deprecated under FedCM and may throw.
60
+ try {
61
+ const notDisplayed = (_b = (_a = notification.isNotDisplayed) === null || _a === void 0 ? void 0 : _a.call(notification)) !== null && _b !== void 0 ? _b : false;
62
+ const skipped = (_d = (_c = notification.isSkippedMoment) === null || _c === void 0 ? void 0 : _c.call(notification)) !== null && _d !== void 0 ? _d : false;
63
+ if (notDisplayed || skipped) {
64
+ const reason = (_h = (_f = (_e = notification.getNotDisplayedReason) === null || _e === void 0 ? void 0 : _e.call(notification)) !== null && _f !== void 0 ? _f : (_g = notification.getSkippedReason) === null || _g === void 0 ? void 0 : _g.call(notification)) !== null && _h !== void 0 ? _h : 'suppressed';
65
+ this.rejectPending(new AuthError(AuthErrorCode.POPUP_BLOCKED, `Google One-Tap was not displayed (${reason}). Render the Google button via ` +
66
+ `provider.renderButton(element) for a guaranteed sign-in UI, or sign in on web ` +
67
+ `with your own Firebase popup.`, AuthProvider.GOOGLE));
101
68
  }
102
- catch (error) {
103
- reject(AuthError.fromError(error, this.provider));
104
- }
105
- },
106
- };
107
- // Add login hint if provided
108
- if (((_b = options === null || options === void 0 ? void 0 : options.options) === null || _b === void 0 ? void 0 : _b.loginHint) || googleOptions.loginHint) {
109
- signInConfig.login_hint =
110
- ((_c = options === null || options === void 0 ? void 0 : options.options) === null || _c === void 0 ? void 0 : _c.loginHint) || googleOptions.loginHint;
111
- }
112
- // Add hosted domain if provided
113
- if (googleOptions.hostedDomain) {
114
- signInConfig.hd = googleOptions.hostedDomain;
115
- }
116
- // Create new client with callback
117
- if (!((_e = (_d = window.google) === null || _d === void 0 ? void 0 : _d.accounts) === null || _e === void 0 ? void 0 : _e.oauth2)) {
118
- throw new Error('Google Identity Services not loaded');
119
- }
120
- const client = window.google.accounts.oauth2.initCodeClient(signInConfig);
121
- // Request authorization code
122
- client.requestCode();
69
+ }
70
+ catch (_j) {
71
+ // FedCM: moment methods unavailable — wait for the credential callback instead.
72
+ }
73
+ });
123
74
  }
124
75
  catch (error) {
125
- reject(AuthError.fromError(error, this.provider));
76
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
126
77
  }
127
78
  });
128
79
  }
129
- async signOut(options) {
130
- var _a, _b;
131
- this.validateInitialized();
80
+ /**
81
+ * Renders Google's official "Sign in with Google" button into `parent`. Use this when One-Tap is
82
+ * suppressed or you want a deterministic button. The button uses the SAME credential callback, so a
83
+ * click resolves the most recent (or next) {@link signIn} promise with the ID-token credential.
84
+ */
85
+ async renderButton(parent, options = { theme: 'outline', size: 'large' }) {
86
+ if (!this.isInitialized) {
87
+ await this.initialize();
88
+ }
89
+ this.configureIdClient();
90
+ this.requireIdApi().renderButton(parent, options);
91
+ }
92
+ async signOut(_options) {
93
+ var _a, _b, _c;
132
94
  try {
133
- // Revoke token if requested
134
- if (options === null || options === void 0 ? void 0 : options.revokeToken) {
135
- const credential = await this.loadCredential();
136
- if (credential === null || credential === void 0 ? void 0 : credential.accessToken) {
137
- await this.revokeAccess(credential.accessToken);
138
- }
139
- }
140
- // Clear stored data
141
- await this.clearStoredData();
142
- await this.setCurrentUser(null);
143
- // Disconnect Google account if available
144
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
145
- window.google.accounts.id.disableAutoSelect();
146
- }
147
- this.logger.info('Signed out from Google');
95
+ (_c = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) === null || _c === void 0 ? void 0 : _c.disableAutoSelect();
148
96
  }
149
97
  catch (error) {
150
- this.logger.error('Failed to sign out from Google', error);
151
- throw AuthError.fromError(error, this.provider);
98
+ this.logger.warn('Google disableAutoSelect failed', error);
99
+ }
100
+ await this.clearStoredData();
101
+ await this.setCurrentUser(null);
102
+ }
103
+ /**
104
+ * Web ID tokens cannot be refreshed silently — re-running One-Tap (with auto-select) re-issues a
105
+ * fresh ID token for a returning user. Falls back to a normal prompt if auto-select can't.
106
+ */
107
+ async refreshToken(_options) {
108
+ return this.signIn();
109
+ }
110
+ async revokeAccess(token) {
111
+ var _a, _b;
112
+ const user = (_a = this.currentUser) !== null && _a !== void 0 ? _a : (await this.getCurrentUser());
113
+ const hint = (_b = user === null || user === void 0 ? void 0 : user.email) !== null && _b !== void 0 ? _b : token;
114
+ if (!hint) {
115
+ await this.signOut();
116
+ return;
152
117
  }
118
+ await new Promise((resolve) => {
119
+ try {
120
+ this.requireIdApi().revoke(hint, () => resolve());
121
+ }
122
+ catch (_a) {
123
+ resolve();
124
+ }
125
+ });
126
+ await this.signOut();
153
127
  }
154
128
  async isSupported() {
155
- // Check if we're in a browser environment
156
129
  if (typeof window === 'undefined' || typeof document === 'undefined') {
157
130
  return false;
158
131
  }
159
- // Check if we can load Google Identity Services
160
132
  try {
161
- await this.loadGoogleIdentityServices();
133
+ await this.loadGsi();
162
134
  return true;
163
135
  }
164
136
  catch (_a) {
165
137
  return false;
166
138
  }
167
139
  }
168
- async linkAccount(options) {
169
- // For web, linking is the same as signing in
170
- return this.signIn(options);
171
- }
172
- async unlinkAccount(_options) {
173
- // For web, unlinking is the same as signing out
174
- await this.signOut();
175
- }
176
- async openAuthorizationUrl(_url) {
177
- // This method is not used in Google Identity Services flow
178
- throw new AuthError(AuthErrorCode.OPERATION_NOT_ALLOWED, 'Direct OAuth flow not supported for Google. Use signIn method instead.', this.provider);
179
- }
180
- async parseUserFromTokenResponse(response) {
181
- // Get user info from the userinfo endpoint
182
- if (response.access_token) {
183
- return this.getUserInfo(response.access_token);
140
+ // --- internals --------------------------------------------------------------------------------
141
+ requireIdApi() {
142
+ var _a, _b;
143
+ const api = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id;
144
+ if (!api) {
145
+ throw new AuthError(AuthErrorCode.PROVIDER_NOT_INITIALIZED, 'Google Identity Services not loaded', AuthProvider.GOOGLE);
184
146
  }
185
- throw new AuthError(AuthErrorCode.INVALID_CREDENTIALS, 'No access token in response', this.provider);
147
+ return api;
186
148
  }
187
- async getUserInfo(accessToken) {
188
- try {
189
- const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
190
- headers: {
191
- Authorization: `Bearer ${accessToken}`,
192
- },
193
- });
194
- if (!response.ok) {
195
- throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to fetch user info', this.provider);
196
- }
197
- return (await response.json());
149
+ configureIdClient() {
150
+ var _a;
151
+ const options = this.options;
152
+ if (!(options === null || options === void 0 ? void 0 : options.clientId)) {
153
+ throw new AuthError(AuthErrorCode.MISSING_CONFIGURATION, 'Google web sign-in requires a `clientId` (your OAuth 2.0 Web client ID).', AuthProvider.GOOGLE);
198
154
  }
199
- catch (error) {
200
- if (error instanceof AuthError) {
201
- throw error;
202
- }
203
- throw new AuthError(AuthErrorCode.NETWORK_ERROR, 'Failed to fetch user info', this.provider, error);
155
+ this.currentNonce = options.nonce;
156
+ const config = {
157
+ client_id: options.clientId,
158
+ callback: (response) => this.handleCredential(response),
159
+ auto_select: (_a = options.autoSelectEnabled) !== null && _a !== void 0 ? _a : false,
160
+ cancel_on_tap_outside: false,
161
+ context: 'signin',
162
+ use_fedcm_for_prompt: true,
163
+ itp_support: true,
164
+ };
165
+ if (options.nonce) {
166
+ config.nonce = options.nonce;
204
167
  }
168
+ if (options.loginHint) {
169
+ config.login_hint = options.loginHint;
170
+ }
171
+ if (options.hostedDomain) {
172
+ config.hd = options.hostedDomain;
173
+ }
174
+ this.requireIdApi().initialize(config);
205
175
  }
206
- async loadGoogleIdentityServices() {
207
- var _a, _b;
208
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2) {
176
+ async handleCredential(response) {
177
+ if (response.error || !response.credential) {
178
+ this.rejectPending(new AuthError(AuthErrorCode.SIGN_IN_FAILED, response.error_description ||
179
+ response.error ||
180
+ 'No Google ID token returned', AuthProvider.GOOGLE));
209
181
  return;
210
182
  }
211
- return new Promise((resolve, reject) => {
212
- const script = document.createElement('script');
213
- script.src = 'https://accounts.google.com/gsi/client';
214
- script.async = true;
215
- script.defer = true;
216
- script.onload = () => {
217
- var _a, _b;
218
- if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.oauth2) {
219
- resolve();
220
- }
221
- else {
222
- reject(new Error('Google Identity Services failed to load'));
223
- }
224
- };
225
- script.onerror = () => {
226
- reject(new Error('Failed to load Google Identity Services'));
183
+ try {
184
+ const idToken = response.credential;
185
+ const claims = this.validateIdToken(idToken);
186
+ const user = this.buildUser(claims);
187
+ const credential = {
188
+ providerId: 'google.com',
189
+ signInMethod: 'google.com',
190
+ idToken,
191
+ tokenType: 'Bearer',
192
+ scope: 'openid email profile',
227
193
  };
228
- document.head.appendChild(script);
229
- });
194
+ await this.setCurrentUser(user);
195
+ this.resolvePending(this.createAuthResult(user, credential, false));
196
+ }
197
+ catch (error) {
198
+ this.rejectPending(AuthError.fromError(error, AuthProvider.GOOGLE));
199
+ }
230
200
  }
231
- mapGoogleError(error) {
232
- const errorMap = {
233
- access_denied: AuthErrorCode.ACCESS_DENIED,
234
- unauthorized_client: AuthErrorCode.APP_NOT_AUTHORIZED,
235
- invalid_request: AuthErrorCode.INVALID_REQUEST,
236
- invalid_scope: AuthErrorCode.INVALID_SCOPE,
237
- server_error: AuthErrorCode.SERVER_ERROR,
238
- temporarily_unavailable: AuthErrorCode.TEMPORARILY_UNAVAILABLE,
239
- popup_closed_by_user: AuthErrorCode.POPUP_CLOSED_BY_USER,
240
- popup_blocked: AuthErrorCode.POPUP_BLOCKED,
241
- };
242
- return errorMap[error] || AuthErrorCode.INTERNAL_ERROR;
201
+ validateIdToken(idToken) {
202
+ const claims = decodeJwtPayload(idToken);
203
+ const options = this.options;
204
+ const validIssuers = ['accounts.google.com', 'https://accounts.google.com'];
205
+ if (!claims.iss || !validIssuers.includes(claims.iss)) {
206
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, `Unexpected ID token issuer: ${claims.iss}`, AuthProvider.GOOGLE);
207
+ }
208
+ if (claims.aud !== options.clientId) {
209
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'ID token audience does not match the configured clientId', AuthProvider.GOOGLE);
210
+ }
211
+ if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {
212
+ throw new AuthError(AuthErrorCode.TOKEN_EXPIRED, 'Google ID token has expired', AuthProvider.GOOGLE);
213
+ }
214
+ // Validate nonce only when the consumer supplied one (avoids hashing ambiguity otherwise).
215
+ if (this.currentNonce && claims.nonce && claims.nonce !== this.currentNonce) {
216
+ throw new AuthError(AuthErrorCode.INVALID_NONCE, 'ID token nonce does not match the requested nonce', AuthProvider.GOOGLE);
217
+ }
218
+ return claims;
243
219
  }
244
- createAuthUser(userInfo, tokenResponse) {
220
+ buildUser(claims) {
221
+ var _a, _b;
222
+ const uid = claims.sub || this.generateUniqueId();
223
+ const email = (_a = claims.email) !== null && _a !== void 0 ? _a : null;
224
+ const emailVerified = claims.email_verified === true || claims.email_verified === 'true';
225
+ const displayName = claims.name ||
226
+ [claims.given_name, claims.family_name].filter(Boolean).join(' ') ||
227
+ null;
228
+ const photoURL = (_b = claims.picture) !== null && _b !== void 0 ? _b : null;
245
229
  return {
246
- uid: userInfo.sub || '',
247
- email: userInfo.email || null,
248
- emailVerified: userInfo.email_verified || false,
249
- displayName: userInfo.name || null,
250
- photoURL: userInfo.picture || null,
230
+ uid,
231
+ email,
232
+ emailVerified,
233
+ displayName,
234
+ photoURL,
251
235
  phoneNumber: null,
252
236
  isAnonymous: false,
253
237
  tenantId: null,
254
238
  providerData: [
255
239
  {
256
- providerId: AuthProvider.GOOGLE,
257
- uid: userInfo.sub || '',
258
- displayName: userInfo.name || null,
259
- email: userInfo.email || null,
240
+ providerId: 'google.com',
241
+ uid,
242
+ displayName,
243
+ email,
260
244
  phoneNumber: null,
261
- photoURL: userInfo.picture || null,
245
+ photoURL,
262
246
  },
263
247
  ],
264
248
  metadata: {
265
249
  creationTime: new Date().toISOString(),
266
250
  lastSignInTime: new Date().toISOString(),
267
251
  },
268
- refreshToken: tokenResponse.refresh_token,
269
252
  };
270
253
  }
254
+ resolvePending(result) {
255
+ const resolve = this.pendingResolve;
256
+ this.pendingResolve = null;
257
+ this.pendingReject = null;
258
+ resolve === null || resolve === void 0 ? void 0 : resolve(result);
259
+ }
260
+ rejectPending(error) {
261
+ const reject = this.pendingReject;
262
+ this.pendingResolve = null;
263
+ this.pendingReject = null;
264
+ if (reject) {
265
+ reject(error);
266
+ }
267
+ else {
268
+ this.logger.error('Google sign-in error with no pending request', error);
269
+ }
270
+ }
271
+ loadGsi() {
272
+ var _a, _b;
273
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
274
+ return Promise.resolve();
275
+ }
276
+ if (this.loadPromise) {
277
+ return this.loadPromise;
278
+ }
279
+ this.loadPromise = new Promise((resolve, reject) => {
280
+ var _a, _b;
281
+ const existing = document.querySelector(`script[src="${GSI_SRC}"]`);
282
+ const onReady = () => {
283
+ var _a, _b;
284
+ return ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id)
285
+ ? resolve()
286
+ : reject(new Error('Google Identity Services failed to load'));
287
+ };
288
+ if (existing) {
289
+ existing.addEventListener('load', onReady, { once: true });
290
+ existing.addEventListener('error', () => reject(new Error('Failed to load Google Identity Services')), { once: true });
291
+ if ((_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.accounts) === null || _b === void 0 ? void 0 : _b.id) {
292
+ resolve();
293
+ }
294
+ return;
295
+ }
296
+ const script = document.createElement('script');
297
+ script.src = GSI_SRC;
298
+ script.async = true;
299
+ script.defer = true;
300
+ script.onload = onReady;
301
+ script.onerror = () => reject(new Error('Failed to load Google Identity Services'));
302
+ document.head.appendChild(script);
303
+ }).finally(() => {
304
+ this.loadPromise = null;
305
+ });
306
+ return this.loadPromise;
307
+ }
308
+ }
309
+ /** Decodes a JWT payload (no signature verification — Google issues the token directly to this origin). */
310
+ function decodeJwtPayload(jwt) {
311
+ const parts = jwt.split('.');
312
+ if (parts.length !== 3) {
313
+ throw new AuthError(AuthErrorCode.INVALID_TOKEN, 'Malformed Google ID token', AuthProvider.GOOGLE);
314
+ }
315
+ if (typeof atob !== 'function') {
316
+ // This provider only runs in the browser (the registry routes native platforms to the native
317
+ // bridge); `atob` is always present there.
318
+ throw new AuthError(AuthErrorCode.INTERNAL_ERROR, 'Google web sign-in requires a browser environment (atob unavailable).', AuthProvider.GOOGLE);
319
+ }
320
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
321
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
322
+ const binary = atob(padded);
323
+ const bytes = new Uint8Array(binary.length);
324
+ for (let i = 0; i < binary.length; i++) {
325
+ bytes[i] = binary.charCodeAt(i);
326
+ }
327
+ const json = new TextDecoder().decode(bytes);
328
+ return JSON.parse(json);
271
329
  }
272
- //# sourceMappingURL=google-provider.js.map
@@ -1,15 +1 @@
1
1
  export { GoogleAuthProviderWeb } from './google-provider';
2
- export { AppleAuthProviderWeb } from './apple-provider';
3
- export { MicrosoftAuthProviderWeb } from './microsoft-provider';
4
- export { FacebookAuthProviderWeb } from './facebook-provider';
5
- export { GitHubAuthProviderWeb } from './github-provider';
6
- export { FirebaseAuthProviderWeb } from './firebase-provider';
7
- export { MagicLinkProvider } from './magic-link-provider';
8
- export { SMSProvider } from './sms-provider';
9
- export { EmailPasswordProvider } from './email-password-provider';
10
- export { BiometricProvider } from './biometric-provider';
11
- export { SlackProvider } from './slack-provider';
12
- export { LinkedInProvider } from './linkedin-provider';
13
- export { UsernamePasswordProvider } from './username-password-provider';
14
- export { EmailCodeProvider } from './email-code-provider';
15
- export { PhonePasswordProvider } from './phone-password-provider';
@@ -1,17 +1,8 @@
1
- // Web provider exports
1
+ // Web provider exports.
2
+ //
3
+ // WIP: providers ship one at a time (see docs/features/google-provider-production-v3). As of 2.4.1
4
+ // only the hardened Google web provider is exported here. The other web providers still exist in this
5
+ // folder but are excluded from the published build until each is re-enabled and verified. Re-add a
6
+ // provider's export below (and restore its registry loader + remove its tsconfig.build exclude) when
7
+ // its turn comes.
2
8
  export { GoogleAuthProviderWeb } from './google-provider';
3
- export { AppleAuthProviderWeb } from './apple-provider';
4
- export { MicrosoftAuthProviderWeb } from './microsoft-provider';
5
- export { FacebookAuthProviderWeb } from './facebook-provider';
6
- export { GitHubAuthProviderWeb } from './github-provider';
7
- export { FirebaseAuthProviderWeb } from './firebase-provider';
8
- export { MagicLinkProvider } from './magic-link-provider';
9
- export { SMSProvider } from './sms-provider';
10
- export { EmailPasswordProvider } from './email-password-provider';
11
- export { BiometricProvider } from './biometric-provider';
12
- export { SlackProvider } from './slack-provider';
13
- export { LinkedInProvider } from './linkedin-provider';
14
- export { UsernamePasswordProvider } from './username-password-provider';
15
- export { EmailCodeProvider } from './email-code-provider';
16
- export { PhonePasswordProvider } from './phone-password-provider';
17
- //# sourceMappingURL=index.js.map
@@ -304,4 +304,3 @@ export function useIsAuthenticated() {
304
304
  const { isAuthenticated } = useAuthState();
305
305
  return isAuthenticated;
306
306
  }
307
- //# sourceMappingURL=hooks.js.map
@@ -1,2 +1,3 @@
1
1
  export * from './hooks';
2
2
  export * from './types';
3
+ export { AuthProvider, AuthErrorCode } from '../definitions';
@@ -1,3 +1,6 @@
1
1
  export * from './hooks';
2
2
  export * from './types';
3
- //# sourceMappingURL=index.js.map
3
+ // Re-export the AuthProvider enum (+ error codes) so consumers get `useAuth().signIn(AuthProvider.GOOGLE)`
4
+ // with a single import. Using the enum is the recommended, typo-safe way to name a provider — plain
5
+ // strings like 'google' still work.
6
+ export { AuthProvider, AuthErrorCode } from '../definitions';
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=types.js.map
@@ -85,4 +85,3 @@ export function isAuthError(error) {
85
85
  error.name === 'AuthError' &&
86
86
  error.code !== undefined));
87
87
  }
88
- //# sourceMappingURL=auth-error.js.map
@@ -18,4 +18,3 @@ export function getErrorMessage(error) {
18
18
  }
19
19
  return undefined;
20
20
  }
21
- //# sourceMappingURL=error-message.js.map
@@ -31,4 +31,3 @@ export class EventEmitter {
31
31
  return this.listeners.size;
32
32
  }
33
33
  }
34
- //# sourceMappingURL=event-emitter.js.map
@@ -159,4 +159,3 @@ export const defaultLogger = new Logger({
159
159
  logLevel: 'warn',
160
160
  prefix: 'CapacitorAuthManager',
161
161
  });
162
- //# sourceMappingURL=logger.js.map
@@ -100,4 +100,3 @@ export class PendingVerificationStore {
100
100
  return all;
101
101
  }
102
102
  }
103
- //# sourceMappingURL=pending-verification-store.js.map
@@ -154,4 +154,3 @@ class InMemoryStorage {
154
154
  this.data.set(key, value);
155
155
  }
156
156
  }
157
- //# sourceMappingURL=storage.js.map
@@ -287,4 +287,3 @@ export function useAuthConfig() {
287
287
  error: readonly(error),
288
288
  };
289
289
  }
290
- //# sourceMappingURL=composables.js.map
@@ -1 +1,2 @@
1
1
  export { useAuth, useAuthState, useUser, useAuthProvider, useAuthConfig, } from './composables';
2
+ export { AuthProvider, AuthErrorCode } from '../definitions';