( code: string, requestedCapabilities: readonly GoogleCapability[] )
| 100 | } |
| 101 | |
| 102 | export async function exchangeGoogleOAuthCode( |
| 103 | code: string, |
| 104 | requestedCapabilities: readonly GoogleCapability[] |
| 105 | ): Promise<GoogleOAuthExchangeResult> { |
| 106 | const oauthClient = createGoogleOAuthClient(); |
| 107 | const tokenResponse = await oauthClient.getToken({ code }); |
| 108 | const tokens = tokenResponse.tokens; |
| 109 | |
| 110 | if (!tokens.access_token) { |
| 111 | throw new Error('Google OAuth response did not include an access token'); |
| 112 | } |
| 113 | |
| 114 | const grantedScopesFromToken = parseGoogleScopeString(tokens.scope); |
| 115 | const grantedScopes = |
| 116 | grantedScopesFromToken.length > 0 |
| 117 | ? grantedScopesFromToken |
| 118 | : resolveGoogleScopesForCapabilities(requestedCapabilities); |
| 119 | |
| 120 | const grantedScopeSet = new Set(grantedScopes); |
| 121 | if (!GOOGLE_IDENTITY_SCOPES.every(scope => grantedScopeSet.has(scope))) { |
| 122 | throw new Error('Required Google identity scopes were not granted'); |
| 123 | } |
| 124 | |
| 125 | if (!hasRequiredScopesForCapabilities(grantedScopes, requestedCapabilities)) { |
| 126 | throw new GoogleOAuthCapabilityScopesNotGrantedError(); |
| 127 | } |
| 128 | |
| 129 | const userInfo = await fetchGoogleUserInfo(tokens.access_token); |
| 130 | if (!userInfo.sub || !userInfo.email) { |
| 131 | throw new Error('Google userinfo response did not include account identity'); |
| 132 | } |
| 133 | if (userInfo.email_verified === false) { |
| 134 | throw new Error('Google account email is not verified'); |
| 135 | } |
| 136 | |
| 137 | return { |
| 138 | refreshToken: tokens.refresh_token ?? null, |
| 139 | grantedScopes, |
| 140 | googleSubject: userInfo.sub, |
| 141 | googleEmail: userInfo.email, |
| 142 | expiresAt: tokens.expiry_date ? new Date(tokens.expiry_date).toISOString() : null, |
| 143 | }; |
| 144 | } |
no test coverage detected