-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Migrate MicrosoftAPIRefreshAccessTokenService to @azure/msal-node
#16954
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
78 changes: 32 additions & 46 deletions
78
...refresh-tokens-manager/drivers/microsoft/services/microsoft-api-refresh-tokens.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,67 +1,53 @@ | ||
| import { Injectable } from '@nestjs/common'; | ||
|
|
||
| import axios, { AxiosError } from 'axios'; | ||
| import { ConfidentialClientApplication } from '@azure/msal-node'; | ||
|
|
||
| import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service'; | ||
| import type { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service'; | ||
| import { | ||
| ConnectedAccountRefreshAccessTokenException, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode, | ||
| } from 'src/modules/connected-account/refresh-tokens-manager/exceptions/connected-account-refresh-tokens.exception'; | ||
| import { type ConnectedAccountTokens } from 'src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service'; | ||
|
|
||
| export type MicrosoftTokens = { | ||
| accessToken: string; | ||
| refreshToken: string; | ||
| }; | ||
|
|
||
| interface MicrosoftRefreshTokenResponse { | ||
| access_token: string; | ||
| refresh_token: string; | ||
| scope: string; | ||
| token_type: string; | ||
| expires_in: number; | ||
| id_token?: string; | ||
| } | ||
| import type { ConnectedAccountTokens } from 'src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service'; | ||
| import { parseMsalError } from 'src/modules/connected-account/refresh-tokens-manager/drivers/microsoft/utils/parse-msal-error.util'; | ||
|
|
||
| @Injectable() | ||
| export class MicrosoftAPIRefreshAccessTokenService { | ||
| constructor(private readonly twentyConfigService: TwentyConfigService) {} | ||
| private msalClient: ConfidentialClientApplication; | ||
|
|
||
| constructor(private readonly config: TwentyConfigService) { | ||
| this.msalClient = new ConfidentialClientApplication({ | ||
| auth: { | ||
| clientId: this.config.get('AUTH_MICROSOFT_CLIENT_ID'), | ||
| clientSecret: this.config.get('AUTH_MICROSOFT_CLIENT_SECRET'), | ||
| authority: 'https://login.microsoftonline.com/common', | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| async refreshTokens(refreshToken: string): Promise<ConnectedAccountTokens> { | ||
| try { | ||
| const response = await axios.post<MicrosoftRefreshTokenResponse>( | ||
| 'https://login.microsoftonline.com/common/oauth2/v2.0/token', | ||
| new URLSearchParams({ | ||
| client_id: this.twentyConfigService.get('AUTH_MICROSOFT_CLIENT_ID'), | ||
| client_secret: this.twentyConfigService.get( | ||
| 'AUTH_MICROSOFT_CLIENT_SECRET', | ||
| ), | ||
| refresh_token: refreshToken, | ||
| grant_type: 'refresh_token', | ||
| }), | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded', | ||
| }, | ||
| }, | ||
| ); | ||
| const responseData = response.data as MicrosoftRefreshTokenResponse; | ||
| const response = await this.msalClient.acquireTokenByRefreshToken({ | ||
| refreshToken, | ||
| scopes: ['https://graph.microsoft.com/.default'], | ||
| }); | ||
|
|
||
| return { | ||
| accessToken: responseData.access_token, | ||
| refreshToken: responseData.refresh_token, | ||
| }; | ||
| } catch (error) { | ||
| if ( | ||
| error instanceof AxiosError && | ||
| error.response?.data?.error === 'invalid_grant' | ||
| ) { | ||
| if (!response) { | ||
| throw new ConnectedAccountRefreshAccessTokenException( | ||
| `Failed to refresh Microsoft token: ${error.response?.data?.error} - ${error.response?.data?.error_description}`, | ||
| 'No response received from Microsoft token endpoint', | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN, | ||
| ); | ||
| } | ||
| throw error; | ||
|
|
||
| return { | ||
| accessToken: response.accessToken, | ||
| refreshToken, | ||
| }; | ||
neo773 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } catch (error) { | ||
| if (error instanceof ConnectedAccountRefreshAccessTokenException) { | ||
| throw error; | ||
| } | ||
|
|
||
| throw parseMsalError(error); | ||
| } | ||
| } | ||
| } | ||
83 changes: 83 additions & 0 deletions
83
...connected-account/refresh-tokens-manager/drivers/microsoft/utils/parse-msal-error.util.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import { | ||
| AuthError, | ||
| InteractionRequiredAuthError, | ||
| ServerError, | ||
| } from '@azure/msal-node'; | ||
|
|
||
| import { | ||
| ConnectedAccountRefreshAccessTokenException, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode, | ||
| } from 'src/modules/connected-account/refresh-tokens-manager/exceptions/connected-account-refresh-tokens.exception'; | ||
|
|
||
| /** | ||
| * @see https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes | ||
| */ | ||
| const PERMANENT_AUTH_ERROR_CODES = new Set([ | ||
| 'invalid_grant', | ||
| 'invalid_client', | ||
| 'unauthorized_client', | ||
| 'invalid_request', | ||
| ]); | ||
|
|
||
| /** | ||
| * @see https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/src/error/ClientAuthErrorCodes.ts | ||
| */ | ||
| const TRANSIENT_AUTH_ERROR_CODES = new Set([ | ||
| 'network_error', | ||
| 'no_network_connectivity', | ||
| 'endpoints_resolution_error', | ||
| 'openid_config_error', | ||
| 'request_cannot_be_made', | ||
| ]); | ||
|
|
||
| export const parseMsalError = ( | ||
| error: unknown, | ||
| ): ConnectedAccountRefreshAccessTokenException => { | ||
| if (error instanceof InteractionRequiredAuthError) { | ||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| `Microsoft token refresh requires re-authentication: ${error.errorCode}`, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN, | ||
| ); | ||
| } | ||
|
|
||
| if (error instanceof ServerError) { | ||
| const status = error.status; | ||
|
|
||
| if (status === 429) { | ||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| 'Microsoft rate limit exceeded', | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.TEMPORARY_NETWORK_ERROR, | ||
| ); | ||
| } | ||
|
|
||
| if (status && status >= 500 && status < 600) { | ||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| `Microsoft server error (${status}): ${error.errorMessage}`, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.TEMPORARY_NETWORK_ERROR, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| if (error instanceof AuthError) { | ||
| if (TRANSIENT_AUTH_ERROR_CODES.has(error.errorCode)) { | ||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| `Microsoft network error: ${error.errorCode} - ${error.errorMessage}`, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.TEMPORARY_NETWORK_ERROR, | ||
| ); | ||
| } | ||
|
|
||
| if (PERMANENT_AUTH_ERROR_CODES.has(error.errorCode)) { | ||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| `Microsoft auth error: ${error.errorCode} - ${error.errorMessage}`, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| const message = error instanceof Error ? error.message : String(error); | ||
|
|
||
| return new ConnectedAccountRefreshAccessTokenException( | ||
| `Microsoft token refresh failed: ${message}`, | ||
| ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN, | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: Using
import typeforTwentyConfigServicemay break NestJS dependency injection. Type-only imports are erased at compile time, which can prevent TypeScript from emitting the design-time type metadata that NestJS needs for constructor injection. Use a regular import to match the pattern in the Google service.Prompt for AI agents
✅ Addressed in
d4ecb69