UNPKG

@sap/cli-core

Version:

Command-Line Interface (CLI) Core Module

72 lines (71 loc) 2.96 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getTechnicalJwt = void 0; const path_1 = __importDefault(require("path")); const url_1 = require("url"); const fs_extra_1 = __importDefault(require("fs-extra")); const config_1 = require("../../../../config"); const logger_1 = require("../../../../logger"); const http_1 = require("../../../../utils/http"); const types_1 = require("./types"); const types_2 = require("../../../../types"); const getLogger = () => (0, logger_1.get)("commands.handler.authentication.technicalJWT.utils"); // eslint-disable-next-line @typescript-eslint/no-var-requires, import/extensions const cf = require("./cf.js"); const APPNAME_GLOBAL = "dwaas-core"; const getSecret = async () => { const { trace } = getLogger(); const config = (0, config_1.get)(); const secretsFile = config.options[types_1.OPTION_SECRET.longName] || path_1.default.join(process.cwd(), ".secret.json"); trace("reading secret from", secretsFile); if (fs_extra_1.default.existsSync(secretsFile)) { const content = await fs_extra_1.default.readFile(secretsFile, "utf8"); return JSON.parse(content); } const currentTarget = await cf.getCurrentTarget(); let [env] = await cf.getEnv(APPNAME_GLOBAL, currentTarget.org, currentTarget.space); env = JSON.parse(env); const vcap = Object.keys(env) .map((k) => env[k].VCAP_SERVICES) .find((v) => v); const url = Object.keys(env) .map((k) => env[k].VCAP_APPLICATION) .find((v) => v && v.uris && v.uris[0]).uris[0]; if (!vcap || !vcap.xsuaa) { throw new Error("The target application is missing a uaa binding."); } const uaa = vcap.xsuaa.find((v) => v.credentials); if (!uaa) { throw new Error("The target application is missing a uaa binding with credentials."); } return { url: `https://${url}`, uaaUrl: uaa.credentials.url, clientid: uaa.credentials.clientid, clientsecret: uaa.credentials.clientsecret, tenantid: uaa.credentials.tenantid, }; }; const getTechnicalJwt = async () => { const secret = await getSecret(); const { data } = await (0, http_1.fetch)({ method: "POST", url: `${secret.uaaUrl}/oauth/token`, headers: { "Content-Type": "application/x-www-form-urlencoded" }, data: new url_1.URLSearchParams({ grant_type: types_2.GrantType.client_credentials, response_type: "token", client_id: secret.clientid, client_secret: secret.clientsecret, }).toString(), }); if (!data.access_token) { throw new Error("No token could be retrieved from the application."); } return data.access_token; }; exports.getTechnicalJwt = getTechnicalJwt;