UNPKG

@microfocus/alm-octane-js-rest-sdk

Version:

NodeJS wrapper for the OpenText Core Software Delivery Platform API

403 lines (402 loc) 21.7 kB
"use strict"; /* * Copyright 2020-2025 Open Text. * * The only warranties for products and services of Open Text and * its affiliates and licensors (“Open Text”) are as may be set forth * in the express warranty statements accompanying such products and services. * Nothing herein should be construed as constituting an additional warranty. * Open Text shall not be liable for technical or editorial errors or * omissions contained herein. The information contained herein is subject * to change without notice. * * Except as specifically indicated otherwise, this document contains * confidential information and a valid license is required for possession, * use or copying. If this work is provided to the U.S. Government, * consistent with FAR 12.211 and 12.212, Commercial Computer Software, * Computer Software Documentation, and Technical Data for Commercial Items are * licensed to the U.S. Government under vendor's standard commercial license. * * 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. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importStar(require("axios")); const async_mutex_1 = require("async-mutex"); const tough_cookie_1 = require("tough-cookie"); const log4js_1 = __importDefault(require("log4js")); // TS1479 is a type-check false positive here in Node16/CJS mode for this dual-runtime dependency. // @ts-expect-error TS1479 const https_proxy_agent_1 = require("https-proxy-agent"); const logger = log4js_1.default.getLogger(); logger.level = 'debug'; /** * @class * * @param {Object} params - configurations to access Octane REST API * @param {String} params.server - server of Octane REST API URL (ex: https://myOctane:8080) * @param {Number} params.user - Octane user * @param {Number} params.password - Octane password * @param {String} [params.proxy] - if set, using proxy to connect to Octane * @param {Object} [params.headers] - JSON containing headers which will be used for all the requests */ class RequestHandler { constructor(params) { if (!params.token && (!params.user || !params.password)) { throw new Error('Either token or user and password must be provided'); } this._user = params.user; this._password = params.password; this._needsAuthenication = false; this._cookieJar = new tough_cookie_1.CookieJar(); this._token = params.token; this._mutex = new async_mutex_1.Mutex(); this._options = { baseURL: params.server, responseType: 'json', }; if (params.proxy) { let httpAgent; if (params.proxyUsername && params.proxyPassword) { const proxyUrlWithCredentials = this.createProxyUrlWithCredentials(params.proxy, params.proxyUsername, params.proxyPassword); httpAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrlWithCredentials); } else { httpAgent = new https_proxy_agent_1.HttpsProxyAgent(params.proxy); } this._options.httpAgent = httpAgent; this._options.httpsAgent = httpAgent; } if (params.headers) { this._options.headers = axios_1.AxiosHeaders.from(params.headers); const customCookies = axios_1.AxiosHeaders.from(this._options.headers).get('Cookie'); const cookieHeader = Array.isArray(customCookies) ? customCookies.join('; ') : customCookies; if (typeof cookieHeader === 'string' && cookieHeader.length > 0) { this._cookieJar.setCookieSync(cookieHeader, this._options.baseURL); } } this._requestor = axios_1.default.create(this._options); } createProxyUrlWithCredentials(proxyUrl, username, password) { const proxySplit = proxyUrl.split('://'); const proxyProps = []; proxyProps.push(proxySplit[0]); proxyProps.push('://'); proxyProps.push(`${username}:${password}@`); proxyProps.push(proxySplit[1]); return proxyProps.join(''); } /** * Fires a GET request for the given URL. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. * @throws - The error returned by the server if the request fails. */ async get(url, config) { return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.get(url, Object.assign(Object.assign({}, config), { headers: headersWithCookie })), config === null || config === void 0 ? void 0 : config.headers) .catch(async (err) => { await this._reauthenticate(err); return await this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.get(url, Object.assign(Object.assign({}, config), { headers: headersWithCookie }))), config === null || config === void 0 ? void 0 : config.headers); }); } /** * Fires a DELETE request for the given URL. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. * @throws - The error returned by the server if the request fails. */ async delete(url, config) { return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.delete(url, Object.assign(Object.assign({}, config), { headers: headersWithCookie })), config === null || config === void 0 ? void 0 : config.headers) .catch(async (err) => { await this._reauthenticate(err); return this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.delete(url, Object.assign(Object.assign({}, config), { headers: headersWithCookie }))), config === null || config === void 0 ? void 0 : config.headers); }); } /** * Fires a PUT request for the given URL. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param body - A JSON which will be passed in the body of the request. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. * @throws - The error returned by the server if the request fails. */ async update(url, body, config) { return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.put(url, body, Object.assign(Object.assign({}, config), { headers: headersWithCookie })), config === null || config === void 0 ? void 0 : config.headers) .catch(async (err) => { await this._reauthenticate(err); return this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.put(url, body, Object.assign(Object.assign({}, config), { headers: headersWithCookie }))), config === null || config === void 0 ? void 0 : config.headers); }); } /** * Fires a POST request for the given URL. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param body - A JSON which will be passed in the body of the request. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. * @throws - The error returned by the server if the request fails. */ async create(url, body, config) { return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.post(url, body, Object.assign(Object.assign({}, config), { headers: headersWithCookie })), config === null || config === void 0 ? void 0 : config.headers) .catch(async (err) => { await this._reauthenticate(err); return this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.post(url, body, Object.assign(Object.assign({}, config), { headers: headersWithCookie }))), config === null || config === void 0 ? void 0 : config.headers); }); } /** * A sign in request is fired. * * @throws - The error returned by the server if the request fails. */ async authenticate() { const authOptions = { url: '/authentication/sign_in', body: { user: this._user, password: this._password, }, }; logger.debug('Signing in...'); // Filter out 'on-behalf-of' header if it exists in default headers const headers = this._options.headers && this.hasHeader(this._options.headers, 'on-behalf-of') ? this.filterOutHeaders(this._options.headers, ['on-behalf-of']) : this._options.headers; const response = await this._requestor.post(authOptions.url, authOptions.body, { headers }); // Save cookies from the authentication response await this.updateCookieJarFromResponse(response, authOptions.url); logger.debug('Signed in.'); return response; } /** * Fires a GET request for the given URL. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. The result is the content of the targeted attachment. * @throws - The error returned by the server if the request fails. */ async getAttachmentContent(url, config) { const attachmentConfig = { headers: { accept: 'application/octet-stream' }, responseType: 'arraybuffer', }; const configHeaders = config === null || config === void 0 ? void 0 : config.headers; const requestHeaders = Object.assign(Object.assign({}, configHeaders), attachmentConfig.headers); return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.get(url, Object.assign(Object.assign(Object.assign({}, config), attachmentConfig), { headers: headersWithCookie })), requestHeaders) .catch(async (err) => { await this._reauthenticate(err); return this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.get(url, Object.assign(Object.assign(Object.assign({}, config), attachmentConfig), { headers: headersWithCookie }))), requestHeaders); }); } /** * Fires a POST request for the given URL. This request should upload the attachment to Octane. In case the request fails with a 401 (Unauthorized) code, one attempt to reauthenticate is sent. If the authentication was successful the initial request is fired again and the response is returned. * * @param url - A url to the specific resource. The URL should exclude the server and point to the desired resource. * @param body - An object which will be passed in the body of the request. This object should contain the content of the attachment. * @param config - Extra configuration for the request (ex. headers) * @returns - The result of the operation returned by the server. * @throws - The error returned by the server if the request fails. */ async uploadAttachment(url, body, config) { const attachmentConfig = { headers: { 'content-type': 'application/octet-stream' }, }; const configHeaders = config === null || config === void 0 ? void 0 : config.headers; const requestHeaders = Object.assign(Object.assign({}, configHeaders), attachmentConfig.headers); return await this.sendRequestWithCookies(url, async (headersWithCookie) => this._requestor.post(url, body, Object.assign(Object.assign(Object.assign({}, config), attachmentConfig), { headers: headersWithCookie })), requestHeaders) .catch(async (err) => { await this._reauthenticate(err); return this.sendRequestWithCookies(url, (headersWithCookie => this._requestor.post(url, body, Object.assign(Object.assign(Object.assign({}, config), attachmentConfig), { headers: headersWithCookie }))), requestHeaders); }); } /** * A sign-out request is fired. * * @throws - The error returned by the server if the request fails. */ async signOut() { logger.debug('Signing out...'); const cookieHeader = await this.getCookieHeaderForUrl('/authentication/sign_out'); const headers = Object.assign(Object.assign({}, this._options.headers), { 'Cookie': cookieHeader }); const response = await this._requestor.post('/authentication/sign_out', undefined, { headers }); logger.debug('Signed out.'); return response; } /** * In case the previous request had a 401 (Unauthorized) status code, an authentication request must be fired. * * @param {Object} err - The error code of the previous error thrown at the failed request. * @throws - The error returned by the server if the request fails. * @private */ async _reauthenticate(err) { this._needsAuthenication = true; return this._mutex.runExclusive(async () => { if (err.response && err.response.status === 401) { if (!this._needsAuthenication) { return; } logger.debug('The received error had status code 401. Trying to authenticate...'); const request = await this.authenticate(); this._needsAuthenication = false; return request; } else { throw err; } }); } async sendRequestWithCookies(url, callBack, customHeaders) { if (this._user && this._password) { return await this.sendRequestWithCredentials(url, callBack, customHeaders); } if (this._token) { return await this.sendRequestWithToken(url, callBack, customHeaders); } throw new Error('No valid authentication available. Neither credentials nor token provided.'); } /** * Sends an HTTP request using cookie-based authentication. * Adds the `Cookie` header to the request using stored credentials. * Updates the cookie jar with any cookies received in the response. * * @param url The URL to send the request to. * @param callBack A callback that performs the actual HTTP request with the provided headers. * @param customHeaders Optional custom headers to include in the request. * @returns The Axios response from the server. * @throws Error if the request fails. */ async sendRequestWithCredentials(url, callBack, customHeaders) { const cookieHeader = await this.getCookieHeaderForUrl(url); const headersWithCookie = this.mergeHeaders(customHeaders, { Cookie: cookieHeader }); const response = await callBack(headersWithCookie); await this.updateCookieJarFromResponse(response, url); return response; } /** * Sends an HTTP request using token-based authentication. * Adds the `Authorization` header with the bearer token to the request. * If the server responds with a 401 status, throws an error indicating token authentication failure. * * @param url The URL to send the request to. * @param callBack A callback that performs the actual HTTP request with the provided headers. * @param customHeaders Optional custom headers to include in the request. * @returns The Axios response from the server. * @throws Error if token authentication fails (401) or another request error occurs. */ async sendRequestWithToken(url, callBack, customHeaders) { const headersWithToken = this.mergeHeaders(customHeaders, { Authorization: `Bearer ${this._token}` }); try { const response = await callBack(headersWithToken); await this.updateCookieJarFromResponse(response, url); return response; } catch (err) { if (err.response && err.response.status === 401) { throw new Error('Token authentication failed. The token may be expired or invalid.'); } throw err; } } async updateCookieJarFromResponse(response, url) { const setCookieHeaders = response.headers['set-cookie']; if (setCookieHeaders) { for (const header of setCookieHeaders) { try { // Parse the Set-Cookie header into a Cookie object const cookie = tough_cookie_1.Cookie.parse(header); if (cookie) { await new Promise((resolve, reject) => { this._cookieJar.setCookie(cookie, this._options.baseURL + url, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } } catch (error) { console.error('Failed to parse or set cookie:', error); } } } } async getCookieHeaderForUrl(url) { return await this._cookieJar.getCookieString(this._options.baseURL + url); } mergeHeaders(headers, additionalHeaders) { const normalizedHeaders = axios_1.AxiosHeaders.from((headers !== null && headers !== void 0 ? headers : {})); if (additionalHeaders) { for (const [key, value] of Object.entries(additionalHeaders)) { normalizedHeaders.set(key, value); } } return normalizedHeaders.toJSON(); } hasHeader(headers, key) { if (!headers) return false; const normalizedKey = key.toLowerCase(); const normalizedHeaders = axios_1.AxiosHeaders.from(headers); return normalizedHeaders.has(normalizedKey); } filterOutHeaders(headers, excludeKeys) { const result = axios_1.AxiosHeaders.from(headers); for (const key of excludeKeys) { result.delete(key); } return result.toJSON(); } } exports.default = RequestHandler;