All files / src OAuthClient.js

73.69% Statements 269/365
64.01% Branches 185/289
69.23% Functions 45/65
74.78% Lines 264/353

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097                                                    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x                   34x 34x 34x 34x 34x 34x     34x 34x     34x   11x       34x                                           1x 1x 1x 1x 1x   1x   1x 1x 1x       1x       1x 1x                         1x       1x   4x 2x   2x 2x 2x 2x       2x     1x 5x       1x 5x                   1x 3x     3x   2x               2x 2x                 30x 30x 3339x 6x   3333x     1x                   1x 6x 6x   5x 5x 5x     5x 5x   5x 5x 3x 3x 3x       5x                 5x                       5x     3x 3x 3x 3x 3x     3x 3x                 1x 5x 5x   4x   4x 4x   4x                       4x     2x 2x 2x 2x 2x     3x 3x                   1x 2x 2x   1x   1x 1x   1x                       1x     1x 1x 1x 1x       1x     1x 1x                     1x 3x 3x   3x   3x             3x                       3x     3x 3x 3x 3x                         1x 2x 2x                         2x     2x 2x       2x                                     1x 16x 1x       15x 15x   6x         6x 6x     15x 15x   15x 15x 15x                               15x     10x     10x               5x 5x     5x                                                                                               5x               5x               5x 1x 1x     1x                                                                                         1x                   1x                 4x 1x               3x 3x                                                                                                 1x                                                                                                               1x                                                               1x   1x 1x 1x                 1x 15x       15x 15x     11x 11x   11x                 11x       4x 3x     4x 4x   4x                 1x 6x 1x     5x 1x     4x       1x             1x 4x         4x         4x       4x               1x 15x 15x   15x   11x 11x     4x   4x                                 4x     15x               1x                   1x 11x       11x 11x 11x 11x 11x 11x   11x 9x 6x 6x 6x 4x 4x 4x 4x                     5x 2x 2x 2x 2x       5x 5x 5x                 5x               1x 4x             1x 80x               1x 8x 8x             1x 15x 15x                 1x 46x 36x     10x 4x 4x     6x                 6x                 6x 6x 6x           6x     1x 11x       11x       11x   11x                 11x                 11x                 11x     1x  
/* eslint-disable no-undef */
/* eslint-disable camelcase */
/**
 
 Copyright (c) 2018 Intuit
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
 #
 #  http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
 */
 
/**
 * @namespace OAuthClient
 */
 
'use strict';
 
const atob = require('atob');
const Csrf = require('csrf');
const queryString = require('query-string');
const axios = require('axios');
const os = require('os');
const winston = require('winston');
const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken');
const AuthResponse = require('./response/AuthResponse');
const version = require('../package.json');
const Token = require('./access-token/Token');
 
// Move error classes to a separate file
const OAuthError = require('./errors/OAuthError');
const ValidationError = require('./errors/ValidationError');
const TokenError = require('./errors/TokenError');
 
/**
 * @constructor
 * @param {string} config.environment
 * @param {string} config.appSecret
 * @param {string} config.appKey
 * @param {string} [config.cachePrefix]
 */
function OAuthClient(config) {
  this.environment = config.environment;
  this.clientId = config.clientId;
  this.clientSecret = config.clientSecret;
  this.redirectUri = config.redirectUri;
  this.token = new Token(config.token);
  this.logging = !!(
    Object.prototype.hasOwnProperty.call(config, 'logging') && config.logging === true
  );
  this.logger = null;
  this.state = new Csrf();
 
  // Configure Axios instance
  this.axiosInstance = axios.create({
    validateStatus(status) {
      return status >= 200 && status < 500;
    },
  });
 
  Iif (this.logging) {
    const dir = './logs';
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
    }
    this.logger = winston.createLogger({
      level: 'info',
      format: winston.format.combine(
        winston.format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss.SSS Z',  // This will include local timezone offset
        }),
        winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`),
      ),
      transports: [
        new winston.transports.File({
          filename: path.join(dir, 'oAuthClient-log.log'),
        }),
      ],
    });
  }
}
 
OAuthClient.cacheId = 'cacheID';
OAuthClient.authorizeEndpoint = 'https://appcenter.intuit.com/connect/oauth2';
OAuthClient.tokenEndpoint = 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer';
OAuthClient.revokeEndpoint = 'https://developer.api.intuit.com/v2/oauth2/tokens/revoke';
OAuthClient.userinfo_endpoint_production =
  'https://accounts.platform.intuit.com/v1/openid_connect/userinfo';
OAuthClient.userinfo_endpoint_sandbox =
  'https://sandbox-accounts.platform.intuit.com/v1/openid_connect/userinfo';
OAuthClient.migrate_sandbox = 'https://developer-sandbox.api.intuit.com/v2/oauth2/tokens/migrate';
OAuthClient.migrate_production = 'https://developer.api.intuit.com/v2/oauth2/tokens/migrate';
OAuthClient.environment = {
  sandbox: 'https://sandbox-quickbooks.api.intuit.com/',
  production: 'https://quickbooks.api.intuit.com/',
};
OAuthClient.qbo_environment = {
  sandbox: 'https://sandbox.qbo.intuit.com/app/',
  production: 'https://qbo.intuit.com/app/',
};
OAuthClient.jwks_uri = 'https://oauth.platform.intuit.com/op/v1/jwks';
OAuthClient.scopes = {
  Accounting: 'com.intuit.quickbooks.accounting',
  Payment: 'com.intuit.quickbooks.payment',
  Payroll: 'com.intuit.quickbooks.payroll',
  TimeTracking: 'com.intuit.quickbooks.payroll.timetracking',
  Benefits: 'com.intuit.quickbooks.payroll.benefits',
  Profile: 'profile',
  Email: 'email',
  Phone: 'phone',
  Address: 'address',
  OpenId: 'openid',
  Intuit_name: 'intuit_name',
};
OAuthClient.user_agent = `Intuit-OAuthClient-JS_${
  version.version
}_${os.type()}_${os.release()}_${os.platform()}`;
 
OAuthClient.prototype.setAuthorizeURLs = function setAuthorizeURLs(params) {
  // check if the customURL's are passed correctly
  if (!params) {
    throw new Error("Provide the custom authorize URL's");
  }
  OAuthClient.authorizeEndpoint = params.authorizeEndpoint;
  OAuthClient.tokenEndpoint = params.tokenEndpoint;
  OAuthClient.revokeEndpoint = params.revokeEndpoint;
  this.environment === 'sandbox'
    ? (OAuthClient.userinfo_endpoint_sandbox = params.userInfoEndpoint)
    : (OAuthClient.userinfo_endpoint_production = params.userInfoEndpoint);
 
  return this;
};
 
OAuthClient.prototype.getEnvironmentURI = function getEnvironmentURI() { 
  return (this.environment && this.environment === 'production') ? OAuthClient.environment.production : OAuthClient.environment.sandbox;
}
 
 
OAuthClient.prototype.getQBOEnvironmentURI = function getQBOEnvironmentURI() {
  return (this.environment && this.environment === 'production') ? OAuthClient.qbo_environment.production : OAuthClient.qbo_environment.sandbox;
}
 
 
/**
 * Redirect  User to Authorization Page
 * *
 * @param params
 * @returns {string} authorize Uri
 */
OAuthClient.prototype.authorizeUri = function authorizeUri(params) {
  params = params || {};
 
  // check if the scopes is provided
  if (!params.scope) throw new Error('Provide the scopes');
 
  const authUri = `${OAuthClient.authorizeEndpoint}?${queryString.stringify({
    response_type: 'code',
    redirect_uri: this.redirectUri,
    client_id: this.clientId,
    scope: Array.isArray(params.scope) ? params.scope.join(' ') : params.scope,
    state: params.state || this.state.create(this.state.secretSync()),
  })}`;
 
  this.log('info', 'The Authorize Uri is :', authUri);
  return authUri;
};
 
/**
 * Safe JSON stringify that handles circular references
 * @param {*} obj - Object to stringify
 * @returns {string} JSON string
 */
function safeStringify(obj) {
  try {
    return JSON.stringify(obj, (key, value) => {
      if (key === '_redirectable' || key === '_currentRequest' || key === 'socket') {
        return undefined;
      }
      return value;
    });
  } catch (e) {
    return String(obj);
  }
}
 
/**
 * Create Token { exchange authorization code for bearer_token }
 * *
 * @param {string|Object} uri
 * @returns {Promise}
 */
OAuthClient.prototype.createToken = function createToken(uri) {
  return new Promise((resolve) => {
    if (!uri) throw new Error('Provide the Uri');
    // Safely parse query string from URI
    const queryIndex = uri.indexOf('?');
    const queryPart = queryIndex !== -1 ? uri.substring(queryIndex + 1) : uri;
    const params = queryString.parse(queryPart);
    
    // Fix: Directly access token object instead of getToken() which returns a copy
    this.token.realmId = params.realmId || '';
    Eif ('state' in params) this.token.state = params.state;
 
    const body = {};
    if (params.code) {
      body.grant_type = 'authorization_code';
      body.code = params.code;
      body.redirect_uri = params.redirectUri || this.redirectUri;
    }
    
    // Log request details for debugging (without sensitive data)
    this.log('info', 'Token exchange request:', {
      grant_type: body.grant_type,
      code_length: body.code ? body.code.length : 0,
      redirect_uri: body.redirect_uri,
      has_code: !!body.code,
      realmId: this.token.realmId,
      state: this.token.state,
    });
 
    const request = {
      url: OAuthClient.tokenEndpoint,
      data: body,
      method: 'POST',
      headers: {
        Authorization: `Basic ${this.authHeader()}`,
        'Content-Type': AuthResponse._urlencodedContentType,
        Accept: AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    resolve(this.getTokenRequest(request));
  })
    .then((res) => {
      const authResponse = Object.prototype.hasOwnProperty.call(res, 'json') ? res : null;
      const json = (authResponse && authResponse.json) || res;
      this.token.setToken(json);
      this.log('info', 'Create Token response is : ', safeStringify(authResponse && authResponse.json));
      return authResponse;
    })
    .catch((e) => {
      this.log('error', 'Create Token () threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Refresh the access_token
 * *
 * @returns {Promise}
 */
OAuthClient.prototype.refresh = function refresh() {
  return new Promise((resolve) => {
    this.validateToken();
 
    const body = {};
 
    body.grant_type = 'refresh_token';
    body.refresh_token = this.getToken().refresh_token;
 
    const request = {
      url: OAuthClient.tokenEndpoint,
      data: body,
      method: 'POST',
      headers: {
        Authorization: `Basic ${this.authHeader()}`,
        'Content-Type': AuthResponse._urlencodedContentType,
        Accept: AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    resolve(this.getTokenRequest(request));
  })
    .then((res) => {
      const authResponse = Object.prototype.hasOwnProperty.call(res, 'json') ? res : null;
      const json = (authResponse && authResponse.json) || res;
      this.token.setToken(json);
      this.log('info', 'Refresh Token () response is : ', safeStringify(authResponse && authResponse.json));
      return authResponse;
    })
    .catch((e) => {
      this.log('error', 'Refresh Token () threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Refresh Tokens by passing refresh_token parameter explicitly
 * *
 * @param {string} refresh_token
 * @returns {Promise}
 */
OAuthClient.prototype.refreshUsingToken = function refreshUsingToken(refresh_token) {
  return new Promise((resolve) => {
    if (!refresh_token) throw new Error('The Refresh token is missing');
 
    const body = {};
 
    body.grant_type = 'refresh_token';
    body.refresh_token = refresh_token;
 
    const request = {
      url: OAuthClient.tokenEndpoint,
      data: body,
      method: 'POST',
      headers: {
        Authorization: `Basic ${this.authHeader()}`,
        'Content-Type': AuthResponse._urlencodedContentType,
        Accept: AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    resolve(this.getTokenRequest(request));
  })
    .then((res) => {
      const authResponse = Object.prototype.hasOwnProperty.call(res, 'json') ? res : null;
      const json = (authResponse && authResponse.json) || res;
      this.token.setToken(json);
      this.log(
        'info',
        'Refresh usingToken () response is : ', safeStringify(authResponse && authResponse.json),
      );
      return authResponse;
    })
    .catch((e) => {
      this.log('error', 'Refresh Token () threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Revoke access_token/refresh_token
 * *
 * @param {Object} params.access_token (optional)
 * @param {Object} params.refresh_token (optional)
 * @returns {Promise}
 */
OAuthClient.prototype.revoke = function revoke(params) {
  return new Promise((resolve) => {
    params = params || {};
 
    const body = {};
 
    body.token =
      params.access_token ||
      params.refresh_token ||
      (this.getToken().isAccessTokenValid()
        ? this.getToken().access_token
        : this.getToken().refresh_token);
 
    const request = {
      url: OAuthClient.revokeEndpoint,
      data: body,
      method: 'POST',
      headers: {
        Authorization: `Basic ${this.authHeader()}`,
        Accept: AuthResponse._jsonContentType,
        'Content-Type': AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    resolve(this.getTokenRequest(request));
  })
    .then((res) => {
      const authResponse = Object.prototype.hasOwnProperty.call(res, 'json') ? res : null;
      this.token.clearToken();
      this.log('info', 'Revoke Token () response is : ', safeStringify(authResponse && authResponse.json));
      return authResponse;
    })
    .catch((e) => {
      this.log('error', 'Revoke Token () threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Get User Info  { Get User Info }
 * *
 * @returns {Promise}
 */
OAuthClient.prototype.getUserInfo = function getUserInfo() {
  return new Promise((resolve) => {
    const request = {
      url:
        this.environment === 'sandbox'
          ? OAuthClient.userinfo_endpoint_sandbox
          : OAuthClient.userinfo_endpoint_production,
      method: 'GET',
      headers: {
        Authorization: `Bearer ${this.token.access_token}`,
        Accept: AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    resolve(this.getTokenRequest(request));
  })
    .then((res) => {
      const authResponse = Object.prototype.hasOwnProperty.call(res, 'json') ? res : null;
      this.log(
        'info',
        'The Get User Info () response is : ', safeStringify(authResponse && authResponse.json),
      );
      return authResponse;
    })
    .catch((e) => {
      this.log('error', 'Get User Info ()  threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Make API call. Pass the url,method,headers using `params` object
 *
 * @param {params} params
 * @param {string} params.url
 * @param {string} params.method (optional) default is GET
 * @param {Object} params.headers (optional)
 * @param {Object} params.body (optional)
 * @param {string} params.responseType (optional) default is json - options are json, text, stream, arraybuffer
 * @returns {Promise}
 */
OAuthClient.prototype.makeApiCall = async function makeApiCall({ url, method, headers: customHeaders, body, params, timeout, responseType, maxRetries = 3 }) {
  if (!url) {
    throw new ValidationError('URL is required for API call');
  }
 
  // Determine the full URL - backward compatibility for relative endpoints
  let fullUrl = url;
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    // User provided a relative endpoint
    const baseURL = (this.environment && this.environment === 'production') 
      ? OAuthClient.environment.production 
      : OAuthClient.environment.sandbox;
    
    // Remove leading slash if present to avoid double slashes
    const endpoint = url.startsWith('/') ? url.slice(1) : url;
    fullUrl = baseURL + endpoint;
  }
 
  let attempt = 0;
  let lastError = null;
 
  while (attempt < maxRetries) {
    try {
      const requestConfig = {
        method: method || 'GET',
        headers: {
          Authorization: `Bearer ${this.getToken().access_token}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'User-Agent': OAuthClient.user_agent,
          ...customHeaders,
        },
        timeout: timeout || 30000,
        responseType: responseType || 'json',
        data: body,
        params,
      };
 
      // Make the API call
      const response = await this.axiosInstance(fullUrl, requestConfig);
      
      // Log the successful response
      this.log('info', 'The makeAPICall () response is : ', JSON.stringify(response.data, null, 2));
      
      // Return in AuthResponse-compatible format for backward compatibility
      return {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        json: response.data,
        body: typeof response.data === 'string' ? response.data : JSON.stringify(response.data),
      };
    } catch (error) {
      attempt += 1;
      lastError = error;
 
      // Detailed error analysis and logging
      const errorAnalysis = {
        // Basic error properties
        basic: {
          name: error.name,
          message: error.message,
          stack: error.stack,
          code: error.code,
        },
        // Response analysis
        response: error.response ? {
          status: error.response.status,
          statusText: error.response.statusText,
          headers: error.response.headers,
          // Deep analysis of response data
          data: error.response.data,
          // Specific Fault object analysis
          fault: error.response.data && error.response.data.Fault ? {
            type: error.response.data.Fault.type,
            error: error.response.data.Fault.Error ? error.response.data.Fault.Error.map(err => ({
              message: err.Message,
              detail: err.Detail,
              code: err.code,
              element: err.element,
              additionalInfo: err.additionalInfo,
            })) : null,
            timestamp: error.response.data.time,
          } : null,
          // OAuth error fields
          oauth: {
            error: error.response.data && error.response.data.error,
            error_description: error.response.data && error.response.data.error_description,
          },
        } : null,
        // Request analysis
        request: error.request ? {
          method: error.request.method,
          path: error.request.path,
          headers: error.request.headers,
        } : null,
        // Context
        context: {
          attempt,
          url: fullUrl,
          timestamp: new Date().toISOString(),
        },
      };
 
      // Log the detailed error analysis
      this.log('error', 'Exception Analysis:', {
        hasFaultObject: !!(error.response && error.response.data && error.response.data.Fault),
        faultType: error.response && error.response.data && error.response.data.Fault && error.response.data.Fault.type,
        faultErrors: error.response && error.response.data && error.response.data.Fault && error.response.data.Fault.Error,
        fullAnalysis: errorAnalysis,
      });
 
      // Log the error for debugging
      this.log('error', 'API call failed:', {
        error: (error.response && error.response.data) || error.message,
        status: error.response && error.response.status,
        attempt,
        url: fullUrl,
      });
 
      // Handle Axios errors
      if (error.response) {
        const { status, data, headers: responseHeaders } = error.response;
        const intuitTid = responseHeaders && responseHeaders.intuit_tid;
 
        // Handle 400 errors with Fault object
        Iif (status === 400) {
          if (data && data.Fault) {
            const fault = data.Fault;
            const faultError = fault.Error && fault.Error[0];
            
            // Extract detailed error information from Fault object
            const errorMessage = (faultError && faultError.Message) || 'Bad Request';
            const errorCode = (faultError && faultError.code) || '400';
            const errorDetail = (faultError && faultError.Detail) || 'Request validation failed';
            const faultType = (fault && fault.type) || 'ValidationFault';
            
            // Create a more descriptive error message
            const detailedMessage = `${errorMessage}`;
            
            throw new OAuthError(
              detailedMessage,
              errorCode,
              errorDetail,
              intuitTid,
              {
                faultType,
                fault: {
                  type: faultType,
                  errors: fault.Error ? fault.Error.map(err => ({
                    message: err.Message,
                    detail: err.Detail,
                    code: err.code,
                  })) : [],
                  time: data.time,
                },
                timestamp: data.time,
              },
            );
          }
          
          // Handle other 400 errors
          throw new OAuthError(
            (data && data.error) || 'Bad Request',
            '400',
            (data && data.error_description) || 'Request validation failed',
            intuitTid,
          );
        }
 
        // Handle rate limit errors
        Iif (status === 429) {
          throw new OAuthError(
            'Rate limit exceeded',
            'RATE_LIMIT_EXCEEDED',
            'Too many requests, please try again later',
            intuitTid,
          );
        }
 
        // Handle other HTTP errors
        throw new OAuthError(
          (data && data.error) || error.message || 'Unknown error',
          status === 500 ? 'INTERNAL_SERVER_ERROR' : status.toString(),
          (data && data.error_description) || 'An error occurred during the API call',
          intuitTid,
        );
      }
 
      // Handle network errors
      if (error.code === 'ECONNABORTED') {
        throw new OAuthError(
          `Request timeout of ${timeout || 30000}ms exceeded`,
          'TIMEOUT_ERROR',
          'The request took too long to complete',
        );
      }
 
      // Handle other errors (no response received)
      Eif (error.request) {
        throw new OAuthError(
          'Connection reset by peer',
          'NETWORK_ERROR',
          'A network error occurred while making the request',
        );
      }
 
      // Handle any other errors
      throw new OAuthError(
        error.message || 'Unknown error',
        'OAUTH_ERROR',
        'An unexpected error occurred',
      );
    }
 
    // Add delay between retries
    if (attempt < maxRetries) {
      const delay = 2 ** attempt * 1000;
      // eslint-disable-next-line no-await-in-loop
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
 
  // If we've exhausted all retries, throw the last error
  if (lastError) {
    if (lastError instanceof OAuthError) {
      throw lastError;
    }
    throw new OAuthError(
      lastError.message || 'Maximum retry attempts reached',
      'MAX_RETRIES_EXCEEDED',
      'The request failed after multiple retry attempts',
    );
  }
 
  // This should never be reached, but TypeScript needs it
  throw new OAuthError(
    'Unexpected error in makeApiCall',
    'UNKNOWN_ERROR',
    'An unexpected error occurred in the API call',
  );
};
 
/**
 * Validate id_token
 * *
 * @param {Object} params(optional)
 * @returns {Promise<AuthResponse>}
 */
OAuthClient.prototype.validateIdToken = function validateIdToken(params = {}) {
  return new Promise((resolve) => {
    if (!this.getToken().id_token) throw new Error('The bearer token does not have id_token');
 
    const id_token = this.getToken().id_token || params.id_token;
 
    // Decode ID Token
    const token_parts = id_token.split('.');
    const id_token_header = JSON.parse(atob(token_parts[0]));
    const id_token_payload = JSON.parse(atob(token_parts[1]));
 
    // Step 1 : First check if the issuer is as mentioned in "issuer"
    if (id_token_payload.iss !== 'https://oauth.platform.intuit.com/op/v1') {
      throw new Error('Invalid issuer in ID token');
    }
 
    // Step 2 : check if the aud field in idToken contains application's clientId
    if (!id_token_payload.aud.find((audience) => audience === this.clientId)) {
      throw new Error('Invalid audience in ID token');
    }
 
    // Step 3 : ensure the timestamp has not elapsed
    if (id_token_payload.exp < Date.now() / 1000) {
      throw new Error('ID token has expired');
    }
 
    const request = {
      url: OAuthClient.jwks_uri,
      method: 'GET',
      headers: {
        Accept: AuthResponse._jsonContentType,
        'User-Agent': OAuthClient.user_agent,
      },
    };
 
    return resolve(this.getKeyFromJWKsURI(id_token, id_token_header.kid, request));
  })
    .then((res) => {
      this.log('info', 'The validateIdToken () response is :', safeStringify(res));
      if (res) return true;
      return false;
    })
    .catch((e) => {
      this.log('error', 'The validateIdToken () threw an exception : ', safeStringify(e));
      throw e;
    });
};
 
/**
 * Get Key from JWKURI
 * *
 * @param {string} id_token
 * @param {string} kid
 * @param {Object} request
 * @returns {Promise}
 */
OAuthClient.prototype.getKeyFromJWKsURI = function getKeyFromJWKsURI(id_token, kid, request) {
  return new Promise((resolve) => {
    resolve(this.loadResponse(request));
  })
    .then((response) => {
      if (Number(response.status) !== 200) throw new Error('Could not reach JWK endpoint');
      // Find the key by KID
      const key = response.data.keys.find((el) => el.kid === kid);
      if (!key) {
        throw new Error(`Key with kid "${kid}" not found in JWKS`);
      }
      const cert = this.getPublicKey(key.n, key.e);
 
      return jwt.verify(id_token, cert);
    })
    .catch((e) => {
      e = this.createError(e);
      this.log(
        'error',
        'The getKeyFromJWKsURI () threw an exception : ',
        safeStringify(e),
      );
      throw e;
    });
};
 
/**
 * Get Public Key
 * *
 * @param modulus
 * @param exponent
 */
OAuthClient.prototype.getPublicKey = function getPublicKey(modulus, exponent) {
  // eslint-disable-next-line global-require
  const getPem = require('rsa-pem-from-mod-exp');
  const pem = getPem(modulus, exponent);
  return pem;
};
 
/**
 * Get Token Request
 * *
 * @param {Object} request
 * @returns {Promise}
 */
OAuthClient.prototype.getTokenRequest = function getTokenRequest(request) {
  const authResponse = new AuthResponse({
    token: this.token,
  });
 
  return new Promise((resolve) => {
    resolve(this.loadResponse(request));
  })
    .then((response) => {
      this.validateResponse(response);
      authResponse.processResponse(response);
 
      Iif (!authResponse.valid()) {
        throw new OAuthError(
          'Response has an Error',
          response.status.toString(),
          response.statusText,
          response.headers && response.headers.intuit_tid,
        );
      }
 
      return authResponse;
    })
    .catch((e) => {
      // If axios error has response data, populate authResponse with it
      if (e.response && e.response.data) {
        authResponse.processResponse(e.response);
      }
      
      Eif (!e.authResponse) {
        e = this.createError(e, authResponse);
      }
      throw e;
    });
};
 
/**
 * Validate Token { validates if token object has refresh token }
 * *
 * @returns {boolean}
 */
OAuthClient.prototype.validateToken = function validateToken() {
  if (!this.token.refreshToken()) {
    throw new Error('The Refresh token is missing');
  }
 
  if (!this.token.isRefreshTokenValid()) {
    throw new Error('The Refresh token is invalid, please Authorize again.');
  }
 
  return true;
};
 
// Add retry configuration
OAuthClient.retryConfig = {
  maxRetries: 3,
  retryDelay: 1000, // 1 second
  retryableStatusCodes: [408, 429, 500, 502, 503, 504],
  retryableErrors: ['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED'],
};
 
OAuthClient.prototype.shouldRetry = function shouldRetry(error, attempt) {
  Iif (attempt >= OAuthClient.retryConfig.maxRetries) {
    return false;
  }
 
  // Check if it's a retryable status code
  Iif (error.response && OAuthClient.retryConfig.retryableStatusCodes.includes(error.response.status)) {
    return true;
  }
 
  // Check if it's a retryable network error
  Iif (error.code && OAuthClient.retryConfig.retryableErrors.includes(error.code)) {
    return true;
  }
 
  return false;
};
 
/**
 * Make HTTP Request using Axios Client
 * @param request
 * @returns response
 */
OAuthClient.prototype.loadResponse = function loadResponse(request) {
  this.currentRequest = request;
  let attempt = 0;
 
  const executeRequest = () => axios(request)
      .then((response) => {
        this.currentRequest = null;
        return response;
      })
      .catch((error) => {
        this.currentRequest = null;
        
        Iif (this.shouldRetry(error, attempt)) {
          attempt += 1;
          const delay = OAuthClient.retryConfig.retryDelay * (2 ** (attempt - 1));
          
          this.log('warn', `Retrying request (attempt ${attempt}/${OAuthClient.retryConfig.maxRetries})`, {
            error: error.message,
            delay,
            url: request.url,
          });
 
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve(executeRequest());
            }, delay);
          });
        }
 
        throw error;
      });
 
  return executeRequest();
};
 
/**
 * Load response from JWK URI
 * @param request
 * @returns response
 */
OAuthClient.prototype.loadResponseFromJWKsURI = function loadResponseFromJWKsURI(request) {
  return axios.get(request).then((response) => response);
};
 
/**
 * Create Error Wrapper
 * @param {Error|string} error - Error object or error message
 * @param {AuthResponse} authResponse - AuthResponse object
 * @returns {Error} error
 */
OAuthClient.prototype.createError = function createError(error, authResponse) {
  Iif (!error) {
    return new Error('');
  }
 
  const wrappedError = new Error();
  wrappedError.error = '';
  wrappedError.authResponse = authResponse || '';
  wrappedError.intuit_tid = (authResponse && authResponse.getIntuitTid()) || '';
  wrappedError.originalMessage = error.message || '';
  wrappedError.error_description = '';
 
  if (authResponse) {
    if (authResponse.body) {
      try {
        const body = typeof authResponse.body === 'string' ? JSON.parse(authResponse.body) : authResponse.body;
        if (body.error) {
          wrappedError.error = body.error;
          wrappedError.error_description = body.error_description || '';
          wrappedError.message = body.error;
          return wrappedError;
        }
      } catch (e) {
        // If parsing fails, use the original body
        wrappedError.error = authResponse.body;
        wrappedError.error_description = authResponse.body;
        wrappedError.message = authResponse.body;
        return wrappedError;
      }
    }
    
    if (authResponse.response && authResponse.response.statusText) {
      wrappedError.error = authResponse.response.statusText;
      wrappedError.error_description = authResponse.response.statusText;
      wrappedError.message = authResponse.response.statusText;
      return wrappedError;
    }
  }
 
  Eif (error instanceof Error) {
    wrappedError.error = error.message;
    wrappedError.message = error.message;
  } else if (typeof error === 'string') {
    wrappedError.error = error;
    wrappedError.message = error;
  } else {
    wrappedError.error = error.toString();
    wrappedError.message = error.toString();
  }
 
  return wrappedError;
};
 
/**
 * isAccessToken Valid () { TTL of access_token }
 * @returns {boolean}
 * @private
 */
OAuthClient.prototype.isAccessTokenValid = function isAccessTokenValid() {
  return this.token.isAccessTokenValid();
};
 
/**
 * GetToken
 * @returns {Token}
 */
OAuthClient.prototype.getToken = function getToken() {
  return this.token;
};
 
/**
 * Set Token
 * @param {Object}
 * @returns {Token}
 */
OAuthClient.prototype.setToken = function setToken(params) {
  this.token = new Token(params);
  return this.token;
};
 
/**
 * Get AuthHeader
 * @returns {string} authHeader
 */
OAuthClient.prototype.authHeader = function authHeader() {
  const apiKey = `${this.clientId}:${this.clientSecret}`;
  return typeof btoa === 'function' ? btoa(apiKey) : Buffer.from(apiKey).toString('base64');
};
 
/**
 * Log the message
 * @param {string} level - Log level
 * @param {string} message - Log message
 * @param {*} data - Log data
 */
OAuthClient.prototype.log = function log(level, message, data) {
  if (!this.logger) {
    return;
  }
 
  if (typeof data === 'string') {
    this.logger.log(level, message + data);
    return;
  }
 
  const logData = {
    timestamp: new Date().toISOString(),
    level,
    message,
    environment: this.environment,
    clientId: this.clientId,
  };
 
  // Add safe request context if available
  Iif (this.currentRequest) {
    logData.request = {
      url: this.currentRequest.url,
      method: this.currentRequest.method,
      headers: { ...this.currentRequest.headers },
    };
  }
 
  // Add safe data context
  Eif (data) {
    try {
      logData.data = JSON.parse(safeStringify(data));
    } catch (e) {
      logData.data = String(data);
    }
  }
 
  this.logger.log(level, safeStringify(logData));
};
 
OAuthClient.prototype.validateResponse = function validateResponse(response) {
  Iif (!response) {
    throw new ValidationError('Empty response received');
  }
 
  Iif (!response.status) {
    throw new ValidationError('Response missing status code');
  }
 
  const intuitTid = response.headers && response.headers.intuit_tid;
 
  Iif (response.status === 429) {
    throw new OAuthError(
      'Rate limit exceeded',
      'RATE_LIMIT_EXCEEDED',
      'Too many requests, please try again later',
      intuitTid,
    );
  }
 
  Iif (response.status === 401) {
    throw new TokenError(
      'Unauthorized',
      'UNAUTHORIZED',
      'Invalid or expired access token',
      intuitTid,
    );
  }
 
  Iif (response.status === 403) {
    throw new OAuthError(
      'Forbidden',
      'FORBIDDEN',
      'Insufficient permissions',
      intuitTid,
    );
  }
 
  return true;
};
 
module.exports = OAuthClient;