Skip to content

The open alternative to Salesforce, designed for AI.

2.4 KB
Raw Blame
import { Injectable } from '@nestjs/common';

import { ConfidentialClientApplication } from '@azure/msal-node';

import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import {
  ConnectedAccountRefreshAccessTokenException,
  ConnectedAccountRefreshAccessTokenExceptionCode,
} from 'src/engine/metadata-modules/connected-account/exceptions/connected-account-refresh-tokens.exception';
import { parseMsalError } from 'src/modules/connected-account/refresh-tokens-manager/drivers/microsoft/utils/parse-msal-error.util';
import type { ConnectedAccountPlaintextTokens } from 'src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service';

@Injectable()
export class MicrosoftApiRefreshAccessTokenService {
  constructor(private readonly config: TwentyConfigService) {}

  async refreshTokens(
    refreshToken: PlaintextString,
  ): Promise<ConnectedAccountPlaintextTokens> {
    const 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',
      },
    });

    try {
      const response = await msalClient.acquireTokenByRefreshToken({
        refreshToken,
        scopes: ['https://graph.microsoft.com/.default'],
        forceCache: true,
      });

      if (!response) {
        throw new ConnectedAccountRefreshAccessTokenException(
          'No response received from Microsoft token endpoint',
          ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN,
        );
      }

      return {
        accessToken: response.accessToken as PlaintextString,
        refreshToken: this.extractRefreshTokenFromCache(msalClient),
      };
    } catch (error) {
      if (error instanceof ConnectedAccountRefreshAccessTokenException) {
        throw error;
      }

      throw parseMsalError(error);
    }
  }

  private extractRefreshTokenFromCache(
    msalClient: ConfidentialClientApplication,
  ): PlaintextString {
    const tokenCache = JSON.parse(msalClient.getTokenCache().serialize());
    const refreshTokenKey = Object.keys(tokenCache.RefreshToken)[0];

    return tokenCache.RefreshToken[refreshTokenKey].secret;
  }
}