UNPKG

@sap-cloud-sdk/core

Version:
271 lines • 13.8 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.headerForClientCredentials = exports.jwtBearerTokenGrant = exports.refreshTokenGrant = exports.userTokenGrant = exports.clientCredentialsGrant = void 0; var util_1 = require("@sap-cloud-sdk/util"); var axios_1 = __importDefault(require("axios")); var opossum_1 = __importDefault(require("opossum")); var http_agent_1 = require("../../../http-agent"); var resilience_options_1 = require("../resilience-options"); var logger = (0, util_1.createLogger)({ package: 'core', messageContext: 'xsuaa-service' }); var circuitBreaker; /** * @deprecated Since v1.49.0 Use `@sap/xssec` lib instead. * Executes a client credentials grant request. * If the first parameter is an instance of [[XsuaaServiceCredentials]], the response's access_token will be verified. * If the first parameter is a URI, the response will not be verified. * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance. * @param clientCredentials - Client credentials for which to request a token. * @param options - Options to use by retrieving access token. * @param customBody - Object containing value required for the body request. * @returns A promise resolving to the response. */ function clientCredentialsGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, options, customBody) { if (customBody === void 0) { customBody = {}; } return __awaiter(this, void 0, void 0, function () { var authHeader, body, data, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: authHeader = headerForClientCredentials(clientCredentials); body = __assign({ grant_type: GrantType.CLIENT_CREDENTIALS }, customBody); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, objectToXWwwUrlEncodedBodyString(body), options)]; case 2: data = (_a.sent()).data; return [2 /*return*/, data]; case 3: error_1 = _a.sent(); throw accessTokenError(error_1, GrantType.CLIENT_CREDENTIALS); case 4: return [2 /*return*/]; } }); }); } exports.clientCredentialsGrant = clientCredentialsGrant; /** * @deprecated Since v1.41.0 Use [[jwtBearerTokenGrant]] instead. * Executes a user token grant request against the given URI. * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance. * @param userJwt - The JWT of the user on whose behalf the request is executed. * @param clientId - The client_id of the target XSUAA service instance. * @param options - Options to use by retrieving access token * @returns A promise resolving to the response of the XSUAA service. */ function userTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, userJwt, clientId, options) { return __awaiter(this, void 0, void 0, function () { var authHeader, body, data, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: authHeader = 'Bearer ' + userJwt; body = objectToXWwwUrlEncodedBodyString({ client_id: clientId, grant_type: GrantType.USER_TOKEN, response_type: 'token' }); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)]; case 2: data = (_a.sent()).data; return [2 /*return*/, data]; case 3: error_2 = _a.sent(); throw accessTokenError(error_2, GrantType.USER_TOKEN); case 4: return [2 /*return*/]; } }); }); } exports.userTokenGrant = userTokenGrant; /** * @deprecated Since v1.41.0 Use [[jwtBearerTokenGrant]] instead. * Executes a refresh token grant request against the given URI. * If the first parameter is an instance of [[XsuaaServiceCredentials]], the response's access_token will be verified. * If the first parameter is an URI, the response will not be verified. * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance. * @param clientCredentials - The credentials (client_id, client_secret) of the target XSUAA service instance. * @param refreshToken - The refresh token that should be used to generate a new access token. * @param options - Options to use by retrieving access token. * @returns A promise resolving to the response of the XSUAA service. */ function refreshTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, refreshToken, options) { return __awaiter(this, void 0, void 0, function () { var authHeader, body, data, error_3; return __generator(this, function (_a) { switch (_a.label) { case 0: authHeader = headerForClientCredentials(clientCredentials); body = objectToXWwwUrlEncodedBodyString({ grant_type: GrantType.REFRESH_TOKEN, refresh_token: refreshToken }); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)]; case 2: data = (_a.sent()).data; return [2 /*return*/, data]; case 3: error_3 = _a.sent(); throw accessTokenError(error_3, GrantType.REFRESH_TOKEN); case 4: return [2 /*return*/]; } }); }); } exports.refreshTokenGrant = refreshTokenGrant; /** * @deprecated Since v1.49.0 Use `@sap/xssec` lib instead. * Executes a JWT bearer token grant request against the given URI. * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance. * @param clientCredentials - The credentials (client_id, client_secret) of the target XSUAA service instance. * @param userJwt - The JWT of the user on whose behalf the request is executed. * @param options - Options to use by retrieving access token. * @returns A promise resolving to the response of the XSUAA service. */ function jwtBearerTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, userJwt, options) { return __awaiter(this, void 0, void 0, function () { var authHeader, body, data, error_4; return __generator(this, function (_a) { switch (_a.label) { case 0: authHeader = headerForClientCredentials(clientCredentials); body = objectToXWwwUrlEncodedBodyString({ client_id: clientCredentials.username, assertion: userJwt, grant_type: GrantType.JWT_BEARER_TOKEN, response_type: 'token' }); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)]; case 2: data = (_a.sent()).data; return [2 /*return*/, data]; case 3: error_4 = _a.sent(); throw accessTokenError(error_4, GrantType.JWT_BEARER_TOKEN); case 4: return [2 /*return*/]; } }); }); } exports.jwtBearerTokenGrant = jwtBearerTokenGrant; function headers(authHeader) { return { headers: { Authorization: authHeader, 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' } }; } function post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options) { if (options === void 0) { options = { enableCircuitBreaker: true }; } var targetUri = typeof tokenServiceUrlOrXsuaaServiceCredentials === 'string' ? tokenServiceUrlOrXsuaaServiceCredentials : getTokenServiceUrl(tokenServiceUrlOrXsuaaServiceCredentials); var config = __assign(__assign(__assign({}, (0, http_agent_1.urlAndAgent)(targetUri)), { proxy: false, method: 'post', data: body }), headers(authHeader)); if (options.enableCircuitBreaker) { return getCircuitBreaker().fire(config); } return axios_1.default.request(config); } function headerForClientCredentials(clientCredentials) { return ('Basic ' + (0, util_1.encodeBase64)("".concat(clientCredentials.username, ":").concat(clientCredentials.password))); } exports.headerForClientCredentials = headerForClientCredentials; function objectToXWwwUrlEncodedBodyString(bodyAsObject) { return Object.entries(bodyAsObject) .map(function (kv) { return kv.join('='); }) .join('&'); } var GrantType; (function (GrantType) { GrantType["USER_TOKEN"] = "user_token"; GrantType["REFRESH_TOKEN"] = "refresh_token"; GrantType["CLIENT_CREDENTIALS"] = "client_credentials"; GrantType["JWT_BEARER_TOKEN"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; })(GrantType || (GrantType = {})); function getTokenServiceUrl(xsuaaServiceCredentials) { var xsuaaUri = xsuaaServiceCredentials.url.replace(/\/$/, ''); logger.info("Adding \"/oauth/token\" to the end of the target uri: ".concat(xsuaaUri, ".")); return "".concat(xsuaaUri, "/oauth/token"); } function accessTokenError(error, grant) { return new util_1.ErrorWithCause("FetchTokenError: ".concat(grantTypeMapper[grant], " Grant failed! ").concat(error.message), error); } function getCircuitBreaker() { if (!circuitBreaker) { circuitBreaker = new opossum_1.default(axios_1.default.request, resilience_options_1.circuitBreakerDefaultOptions); } return circuitBreaker; } var grantTypeMapper = (_a = {}, _a[GrantType.USER_TOKEN] = 'User token', _a[GrantType.REFRESH_TOKEN] = 'Refresh token', _a[GrantType.CLIENT_CREDENTIALS] = 'Client credentials', _a[GrantType.JWT_BEARER_TOKEN] = 'JWT token', _a); //# sourceMappingURL=xsuaa-service.js.map