@rockcarver/frodo-lib 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.12.4] - 2022-09-17
11
+
12
+ ### Added
13
+
14
+ - Frodo now allows two new parameters when adding a connection profile:
15
+
16
+ \--authentication-service [service] Name of the authentication service/tree to use.
17
+
18
+ \--authentication-header-overrides [headers] Map of headers: {"host":"am.example.com:8081"}.
19
+
20
+ These parameters are currently only supported in the `frodo conn add` command and the configuration elements will be automatically applied to commands issued using that connection profile.
21
+
22
+ % frodo conn add https://platform.example.com:9443/am username password --authentication-service ldapService --authentication-header-overrides '{"host":"am.example.com:8081"}' -k
23
+ ForgeOps deployment detected.
24
+ Connected to ForgeRock Access Management 7.2.0 Build 64ef7ebc01ed3df1a1264d7b0400351bc101361f (2022-June-27 08:15)
25
+ Saving creds in /Users/vscheuber/.frodo/.frodorc...
26
+ Updating connection profile https://platform.example.com:9443/am
27
+ Advanced setting: Authentication Service: ldapService
28
+ Advanced setting: Authentication Header Overrides:
29
+ { host: 'am.example.com:8081' }
30
+ %
31
+
32
+ After the connection profile is created with the additional parameters, the environment can be accessed as usual. In this case it requires the `-k` parameter for every command, as the environment uses a self-signed certificate.
33
+
34
+ % frodo journey list platform alpha -k
35
+ ForgeOps deployment detected.
36
+ Connected to ForgeRock Access Management 7.2.0 Build 64ef7ebc01ed3df1a1264d7b0400351bc101361f (2022-June-27 08:15)
37
+ Listing journeys in realm "alpha"...
38
+ Agent
39
+ Example
40
+ Facebook-ProvisionIDMAccount
41
+ Google-AnonymousUser
42
+ Google-DynamicAccountCreation
43
+ HmacOneTimePassword
44
+ PersistentCookie
45
+ PlatformForgottenUsername
46
+ PlatformLogin
47
+ PlatformProgressiveProfile
48
+ PlatformRegistration
49
+ PlatformResetPassword
50
+ PlatformUpdatePassword
51
+ RetryLimit
52
+ %
53
+
54
+ ### Fixed
55
+
56
+ - \#94: Frodo can now connect to improperly configured platform instances
57
+
10
58
  ## [0.12.3] - 2022-09-16
11
59
 
12
60
  ### Fixed
@@ -501,7 +549,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
501
549
  - Fixed problem with adding connection profiles
502
550
  - Miscellaneous bug fixes
503
551
 
504
- [Unreleased]: https://github.com/rockcarver/frodo-lib/compare/v0.12.3...HEAD
552
+ [Unreleased]: https://github.com/rockcarver/frodo-lib/compare/v0.12.4...HEAD
553
+
554
+ [0.12.4]: https://github.com/rockcarver/frodo-lib/compare/v0.12.3...v0.12.4
505
555
 
506
556
  [0.12.3]: https://github.com/rockcarver/frodo-lib/compare/v0.12.2...v0.12.3
507
557
 
@@ -19,6 +19,7 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try
19
19
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
20
20
 
21
21
  var authenticateUrlTemplate = '%s/json%s/authenticate';
22
+ var authenticateWithServiceUrlTemplate = "".concat(authenticateUrlTemplate, "?authIndexType=service&authIndexValue=%s");
22
23
  var apiVersion = 'resource=2.0, protocol=1.0';
23
24
 
24
25
  var getApiConfig = () => ({
@@ -51,9 +52,7 @@ function _step() {
51
52
  _step = _asyncToGenerator(function* () {
52
53
  var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
53
54
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
54
-
55
- var urlString = _util.default.format(authenticateUrlTemplate, _SessionStorage.default.session.getTenant(), getRealmUrl('/'));
56
-
55
+ var urlString = _SessionStorage.default.session.getAuthenticationService() ? _util.default.format(authenticateWithServiceUrlTemplate, _SessionStorage.default.session.getTenant(), getRealmUrl('/'), _SessionStorage.default.session.getAuthenticationService()) : _util.default.format(authenticateUrlTemplate, _SessionStorage.default.session.getTenant(), getRealmUrl('/'));
57
56
  return (0, _BaseApi.generateAmApi)(getApiConfig()).post(urlString, data, config);
58
57
  });
59
58
  return _step.apply(this, arguments);
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticateApi.js","names":["authenticateUrlTemplate","apiVersion","getApiConfig","realmPathTemplate","getRealmUrl","realm","localRealm","startsWith","length","substring","realmPath","util","format","step","data","config","urlString","storage","session","getTenant","generateAmApi","post"],"sources":["api/AuthenticateApi.ts"],"sourcesContent":["import util from 'util';\nimport { generateAmApi } from './BaseApi';\nimport storage from '../storage/SessionStorage';\n\nconst authenticateUrlTemplate = '%s/json%s/authenticate';\n\nconst apiVersion = 'resource=2.0, protocol=1.0';\nconst getApiConfig = () => ({\n apiVersion,\n});\n\nconst realmPathTemplate = '/realms/%s';\n\nexport function getRealmUrl(realm) {\n let localRealm = realm;\n if (localRealm.startsWith('/') && localRealm.length > 1) {\n localRealm = localRealm.substring(1);\n }\n let realmPath = util.format(realmPathTemplate, 'root');\n if (localRealm !== '/') {\n realmPath += util.format(realmPathTemplate, localRealm);\n }\n return realmPath;\n}\n\nexport async function step(data = {}, config = {}) {\n const urlString = util.format(\n authenticateUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/')\n );\n return generateAmApi(getApiConfig()).post(urlString, data, config);\n}\n"],"mappings":";;;;;;;;AAAA;;AACA;;AACA;;;;;;;;AAEA,IAAMA,uBAAuB,GAAG,wBAAhC;AAEA,IAAMC,UAAU,GAAG,4BAAnB;;AACA,IAAMC,YAAY,GAAG,OAAO;EAC1BD;AAD0B,CAAP,CAArB;;AAIA,IAAME,iBAAiB,GAAG,YAA1B;;AAEO,SAASC,WAAT,CAAqBC,KAArB,EAA4B;EACjC,IAAIC,UAAU,GAAGD,KAAjB;;EACA,IAAIC,UAAU,CAACC,UAAX,CAAsB,GAAtB,KAA8BD,UAAU,CAACE,MAAX,GAAoB,CAAtD,EAAyD;IACvDF,UAAU,GAAGA,UAAU,CAACG,SAAX,CAAqB,CAArB,CAAb;EACD;;EACD,IAAIC,SAAS,GAAGC,aAAA,CAAKC,MAAL,CAAYT,iBAAZ,EAA+B,MAA/B,CAAhB;;EACA,IAAIG,UAAU,KAAK,GAAnB,EAAwB;IACtBI,SAAS,IAAIC,aAAA,CAAKC,MAAL,CAAYT,iBAAZ,EAA+BG,UAA/B,CAAb;EACD;;EACD,OAAOI,SAAP;AACD;;SAEqBG,I;;;;;4BAAf,aAA4C;IAAA,IAAxBC,IAAwB,uEAAjB,EAAiB;IAAA,IAAbC,MAAa,uEAAJ,EAAI;;IACjD,IAAMC,SAAS,GAAGL,aAAA,CAAKC,MAAL,CAChBZ,uBADgB,EAEhBiB,uBAAA,CAAQC,OAAR,CAAgBC,SAAhB,EAFgB,EAGhBf,WAAW,CAAC,GAAD,CAHK,CAAlB;;IAKA,OAAO,IAAAgB,sBAAA,EAAclB,YAAY,EAA1B,EAA8BmB,IAA9B,CAAmCL,SAAnC,EAA8CF,IAA9C,EAAoDC,MAApD,CAAP;EACD,C"}
1
+ {"version":3,"file":"AuthenticateApi.js","names":["authenticateUrlTemplate","authenticateWithServiceUrlTemplate","apiVersion","getApiConfig","realmPathTemplate","getRealmUrl","realm","localRealm","startsWith","length","substring","realmPath","util","format","step","data","config","urlString","storage","session","getAuthenticationService","getTenant","generateAmApi","post"],"sources":["api/AuthenticateApi.ts"],"sourcesContent":["import util from 'util';\nimport { generateAmApi } from './BaseApi';\nimport storage from '../storage/SessionStorage';\n\nconst authenticateUrlTemplate = '%s/json%s/authenticate';\nconst authenticateWithServiceUrlTemplate = `${authenticateUrlTemplate}?authIndexType=service&authIndexValue=%s`;\n\nconst apiVersion = 'resource=2.0, protocol=1.0';\nconst getApiConfig = () => ({\n apiVersion,\n});\n\nconst realmPathTemplate = '/realms/%s';\n\nexport function getRealmUrl(realm) {\n let localRealm = realm;\n if (localRealm.startsWith('/') && localRealm.length > 1) {\n localRealm = localRealm.substring(1);\n }\n let realmPath = util.format(realmPathTemplate, 'root');\n if (localRealm !== '/') {\n realmPath += util.format(realmPathTemplate, localRealm);\n }\n return realmPath;\n}\n\nexport async function step(data = {}, config = {}) {\n const urlString = storage.session.getAuthenticationService()\n ? util.format(\n authenticateWithServiceUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/'),\n storage.session.getAuthenticationService()\n )\n : util.format(\n authenticateUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/')\n );\n return generateAmApi(getApiConfig()).post(urlString, data, config);\n}\n"],"mappings":";;;;;;;;AAAA;;AACA;;AACA;;;;;;;;AAEA,IAAMA,uBAAuB,GAAG,wBAAhC;AACA,IAAMC,kCAAkC,aAAMD,uBAAN,6CAAxC;AAEA,IAAME,UAAU,GAAG,4BAAnB;;AACA,IAAMC,YAAY,GAAG,OAAO;EAC1BD;AAD0B,CAAP,CAArB;;AAIA,IAAME,iBAAiB,GAAG,YAA1B;;AAEO,SAASC,WAAT,CAAqBC,KAArB,EAA4B;EACjC,IAAIC,UAAU,GAAGD,KAAjB;;EACA,IAAIC,UAAU,CAACC,UAAX,CAAsB,GAAtB,KAA8BD,UAAU,CAACE,MAAX,GAAoB,CAAtD,EAAyD;IACvDF,UAAU,GAAGA,UAAU,CAACG,SAAX,CAAqB,CAArB,CAAb;EACD;;EACD,IAAIC,SAAS,GAAGC,aAAA,CAAKC,MAAL,CAAYT,iBAAZ,EAA+B,MAA/B,CAAhB;;EACA,IAAIG,UAAU,KAAK,GAAnB,EAAwB;IACtBI,SAAS,IAAIC,aAAA,CAAKC,MAAL,CAAYT,iBAAZ,EAA+BG,UAA/B,CAAb;EACD;;EACD,OAAOI,SAAP;AACD;;SAEqBG,I;;;;;4BAAf,aAA4C;IAAA,IAAxBC,IAAwB,uEAAjB,EAAiB;IAAA,IAAbC,MAAa,uEAAJ,EAAI;IACjD,IAAMC,SAAS,GAAGC,uBAAA,CAAQC,OAAR,CAAgBC,wBAAhB,KACdR,aAAA,CAAKC,MAAL,CACEZ,kCADF,EAEEiB,uBAAA,CAAQC,OAAR,CAAgBE,SAAhB,EAFF,EAGEhB,WAAW,CAAC,GAAD,CAHb,EAIEa,uBAAA,CAAQC,OAAR,CAAgBC,wBAAhB,EAJF,CADc,GAOdR,aAAA,CAAKC,MAAL,CACEb,uBADF,EAEEkB,uBAAA,CAAQC,OAAR,CAAgBE,SAAhB,EAFF,EAGEhB,WAAW,CAAC,GAAD,CAHb,CAPJ;IAYA,OAAO,IAAAiB,sBAAA,EAAcnB,YAAY,EAA1B,EAA8BoB,IAA9B,CAAmCN,SAAnC,EAA8CF,IAA9C,EAAoDC,MAApD,CAAP;EACD,C"}
@@ -140,7 +140,7 @@ function generateAmApi(resource) {
140
140
  baseURL: "".concat(_SessionStorage.default.session.getTenant(), "/json"),
141
141
  timeout
142
142
  }, requestOverride), {}, {
143
- headers,
143
+ headers: _objectSpread(_objectSpread({}, headers), _SessionStorage.default.session.getAuthenticationHeaderOverrides()),
144
144
  httpAgent: getHttpAgent(),
145
145
  httpsAgent: getHttpsAgent(),
146
146
  proxy: getProxy()
@@ -176,7 +176,7 @@ function generateOauth2Api(resource) {
176
176
  baseURL: "".concat(_SessionStorage.default.session.getTenant(), "/json").concat(resource.path),
177
177
  timeout
178
178
  }, requestOverride), {}, {
179
- headers,
179
+ headers: _objectSpread(_objectSpread({}, headers), _SessionStorage.default.session.getAuthenticationHeaderOverrides()),
180
180
  httpAgent: getHttpAgent(),
181
181
  httpsAgent: getHttpsAgent(),
182
182
  proxy: getProxy()
@@ -1 +1 @@
1
- {"version":3,"file":"BaseApi.js","names":["__dirname","path","dirname","fileURLToPath","pkg","JSON","parse","fs","readFileSync","resolve","axiosRetry","axios","retries","shouldResetTimeout","retryCondition","_error","timeout","maxSockets","maxFreeSockets","freeSocketTimeout","userAgent","name","version","httpAgent","httpsAgent","getHttpAgent","Agent","getHttpsAgent","options","rejectUnauthorized","storage","session","getAllowInsecureConnection","httpsProxy","process","env","HTTPS_PROXY","https_proxy","console","error","parsed","url","hostname","port","protocol","HttpsProxyAgent","HttpsAgent","getProxy","generateAmApi","resource","requestOverride","headers","apiVersion","Cookie","getCookieName","getCookieValue","requestDetails","baseURL","getTenant","proxy","request","create","generateOauth2Api","raw","generateIdmApi","getTenantURL","getBearerToken","generateLogKeysApi","generateLogApi","getLogApiKey","getLogApiSecret","generateESVApi"],"sources":["api/BaseApi.ts"],"sourcesContent":["import Agent from 'agentkeepalive';\nimport axios, { AxiosProxyConfig } from 'axios';\nimport axiosRetry from 'axios-retry';\nimport HttpsProxyAgent from 'https-proxy-agent';\nimport url from 'url';\nimport fs from 'fs';\nimport storage from '../storage/SessionStorage';\nimport { getTenantURL } from './utils/ApiUtils';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\naxiosRetry(axios, {\n retries: 3,\n shouldResetTimeout: true,\n retryCondition: (_error) => true, // retry no matter what\n});\n\n// all agents\nconst timeout = 30000;\n\n// agentkeepalive\nconst maxSockets = 100;\nconst maxFreeSockets = 10;\nconst freeSocketTimeout = 30000;\n\nconst userAgent = `${pkg.name}/${pkg.version}`;\nlet httpAgent, httpsAgent;\n\nfunction getHttpAgent() {\n if (httpAgent) return httpAgent;\n httpAgent = new Agent({\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpAgent;\n}\n\n/**\n * Helper method to create properly configured httpsAgent\n * @returns {any} appropriate httpsAgent\n */\nfunction getHttpsAgent() {\n if (httpsAgent) return httpsAgent;\n const options = {\n rejectUnauthorized: !storage.session.getAllowInsecureConnection(),\n };\n const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;\n if (httpsProxy) {\n // https://github.com/axios/axios/issues/3459\n console.error(`Using proxy ${httpsProxy}`['yellow']);\n const parsed = url.parse(httpsProxy);\n options['host'] = parsed.hostname;\n options['port'] = parsed.port;\n options['protocol'] = parsed.protocol;\n options.rejectUnauthorized = !storage.session.getAllowInsecureConnection();\n httpsAgent = HttpsProxyAgent(options);\n return httpsAgent;\n }\n httpsAgent = new Agent.HttpsAgent({\n ...options,\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpsAgent;\n}\n\n/**\n * Get Proxy config\n * @returns {AxiosProxyConfig | false} axios proxy config or false\n */\nfunction getProxy(): AxiosProxyConfig | false {\n if (process.env.HTTPS_PROXY || process.env.https_proxy) return false;\n return null;\n}\n\n/**\n * Generates an AM Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateAmApi(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.getCookieName()}=${storage.session.getCookieValue()}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json`,\n timeout,\n ...requestOverride,\n headers,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an OAuth2 Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateOauth2Api(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.raw['cookieName']}=${storage.session.raw['cookieValue']}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json${resource.path}`,\n timeout,\n ...requestOverride,\n headers,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an IDM Axios API instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateIdmApi(requestOverride = {}) {\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers: {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n },\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a LogKeys API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogKeysApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a Log API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'X-API-Key': storage.session.getLogApiKey(),\n 'X-API-Secret': storage.session.getLogApiSecret(),\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an ESV Axios API instance for Environment Secrets and Variables\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateESVApi(resource, requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;;;;;;;AAGA,IAAMA,QAAS,GAAGC,aAAA,CAAKC,OAAL,CAAa,IAAAC,kBAAA,sDAAb,CAAlB;;AAEA,IAAMC,GAAG,GAAGC,IAAI,CAACC,KAAL,CACVC,WAAA,CAAGC,YAAH,CAAgBP,aAAA,CAAKQ,OAAL,CAAaT,QAAb,EAAwB,oBAAxB,CAAhB,EAA+D,MAA/D,CADU,CAAZ;AAIA,IAAAU,mBAAA,EAAWC,cAAX,EAAkB;EAChBC,OAAO,EAAE,CADO;EAEhBC,k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B;EAHF,CAAhB;;EAKA,IAAMd,cAAc;IAClBC,OAAO,EAAE,IAAAQ,sBAAA,EAAanC,uBAAA,CAAQC,OAAR,CAAgB2B,SAAhB,EAAb,CADS;IAElB1C,OAFkB;IAGlBmC;EAHkB,GAIfD,eAJe;IAKlB3B,SAAS,EAAEE,YAAY,EALL;IAMlBD,UAAU,EAAEG,aAAa,EANP;IAOlBgC,KAAK,EAAEZ,QAAQ;EAPG,EAApB;;EAUA,IAAMa,OAAO,GAAGjD,cAAA,CAAMkD,MAAN,CAAaL,cAAb,CAAhB;;EAEA,OAAOI,OAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASW,cAAT,CAAwBtB,QAAxB,EAAwD;EAAA,IAAtBC,eAAsB,uEAAJ,EAAI;EAC7D,IAAMC,OAAO,GAAG;IACd,cAAc/B,SADA;IAEd,gBAAgB,kBAFF;IAGd,sBAAsB6B,QAAQ,CAACG;EAHjB,CAAhB;;EAKA,IAAMI,cAAc;IAClBC,OAAO,EAAE,IAAAQ,sBAAA,EAAanC,uBAAA,CAAQC,OAAR,CAAgB2B,SAAhB,EAAb,CADS;IAElB1C,OAFkB;IAGlBmC;EAHkB,GAIfD,eAJe;IAKlB3B,SAAS,EAAEE,YAAY,EALL;IAMlBD,UAAU,EAAEG,aAAa,EANP;IAOlBgC,KAAK,EAAEZ,QAAQ;EAPG,EAApB;;EAUA,IAAIjB,uBAAA,CAAQC,OAAR,CAAgBmC,cAAhB,EAAJ,EAAsC;IACpCV,cAAc,CAACL,OAAf,CACE,eADF,qBAEcrB,uBAAA,CAAQC,OAAR,CAAgBmC,cAAhB,EAFd;EAGD;;EAED,IAAMN,OAAO,GAAGjD,cAAA,CAAMkD,MAAN,CAAaL,cAAb,CAAhB;;EAEA,OAAOI,OAAP;AACD"}
1
+ {"version":3,"file":"BaseApi.js","names":["__dirname","path","dirname","fileURLToPath","pkg","JSON","parse","fs","readFileSync","resolve","axiosRetry","axios","retries","shouldResetTimeout","retryCondition","_error","timeout","maxSockets","maxFreeSockets","freeSocketTimeout","userAgent","name","version","httpAgent","httpsAgent","getHttpAgent","Agent","getHttpsAgent","options","rejectUnauthorized","storage","session","getAllowInsecureConnection","httpsProxy","process","env","HTTPS_PROXY","https_proxy","console","error","parsed","url","hostname","port","protocol","HttpsProxyAgent","HttpsAgent","getProxy","generateAmApi","resource","requestOverride","headers","apiVersion","Cookie","getCookieName","getCookieValue","requestDetails","baseURL","getTenant","getAuthenticationHeaderOverrides","proxy","request","create","generateOauth2Api","raw","generateIdmApi","getTenantURL","getBearerToken","generateLogKeysApi","generateLogApi","getLogApiKey","getLogApiSecret","generateESVApi"],"sources":["api/BaseApi.ts"],"sourcesContent":["import Agent from 'agentkeepalive';\nimport axios, { AxiosProxyConfig } from 'axios';\nimport axiosRetry from 'axios-retry';\nimport HttpsProxyAgent from 'https-proxy-agent';\nimport url from 'url';\nimport fs from 'fs';\nimport storage from '../storage/SessionStorage';\nimport { getTenantURL } from './utils/ApiUtils';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\naxiosRetry(axios, {\n retries: 3,\n shouldResetTimeout: true,\n retryCondition: (_error) => true, // retry no matter what\n});\n\n// all agents\nconst timeout = 30000;\n\n// agentkeepalive\nconst maxSockets = 100;\nconst maxFreeSockets = 10;\nconst freeSocketTimeout = 30000;\n\nconst userAgent = `${pkg.name}/${pkg.version}`;\nlet httpAgent, httpsAgent;\n\nfunction getHttpAgent() {\n if (httpAgent) return httpAgent;\n httpAgent = new Agent({\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpAgent;\n}\n\n/**\n * Helper method to create properly configured httpsAgent\n * @returns {any} appropriate httpsAgent\n */\nfunction getHttpsAgent() {\n if (httpsAgent) return httpsAgent;\n const options = {\n rejectUnauthorized: !storage.session.getAllowInsecureConnection(),\n };\n const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;\n if (httpsProxy) {\n // https://github.com/axios/axios/issues/3459\n console.error(`Using proxy ${httpsProxy}`['yellow']);\n const parsed = url.parse(httpsProxy);\n options['host'] = parsed.hostname;\n options['port'] = parsed.port;\n options['protocol'] = parsed.protocol;\n options.rejectUnauthorized = !storage.session.getAllowInsecureConnection();\n httpsAgent = HttpsProxyAgent(options);\n return httpsAgent;\n }\n httpsAgent = new Agent.HttpsAgent({\n ...options,\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpsAgent;\n}\n\n/**\n * Get Proxy config\n * @returns {AxiosProxyConfig | false} axios proxy config or false\n */\nfunction getProxy(): AxiosProxyConfig | false {\n if (process.env.HTTPS_PROXY || process.env.https_proxy) return false;\n return null;\n}\n\n/**\n * Generates an AM Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateAmApi(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.getCookieName()}=${storage.session.getCookieValue()}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json`,\n timeout,\n ...requestOverride,\n headers: {\n ...headers,\n ...storage.session.getAuthenticationHeaderOverrides(),\n },\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an OAuth2 Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateOauth2Api(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.raw['cookieName']}=${storage.session.raw['cookieValue']}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json${resource.path}`,\n timeout,\n ...requestOverride,\n headers: {\n ...headers,\n ...storage.session.getAuthenticationHeaderOverrides(),\n },\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an IDM Axios API instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateIdmApi(requestOverride = {}) {\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers: {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n },\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a LogKeys API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogKeysApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a Log API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'X-API-Key': storage.session.getLogApiKey(),\n 'X-API-Secret': storage.session.getLogApiSecret(),\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an ESV Axios API instance for Environment Secrets and Variables\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateESVApi(resource, requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;;;;;;;AAGA,IAAMA,QAAS,GAAGC,aAAA,CAAKC,OAAL,CAAa,IAAAC,kBAAA,sDAAb,CAAlB;;AAEA,IAAMC,GAAG,GAAGC,IAAI,CAACC,KAAL,CACVC,WAAA,CAA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;IACpCX,cAAc,CAACL,OAAf,CACE,eADF,qBAEcrB,uBAAA,CAAQC,OAAR,CAAgBoC,cAAhB,EAFd;EAGD;;EAED,IAAMN,OAAO,GAAGlD,cAAA,CAAMmD,MAAN,CAAaN,cAAb,CAAhB;;EAEA,OAAOK,OAAP;AACD"}
@@ -158,7 +158,9 @@ function _determineDeploymentType() {
158
158
  try {
159
159
  yield (0, _OAuth2OIDCApi.authorize)(bodyFormData, config);
160
160
  } catch (e) {
161
- if (e.response && e.response.status === 302) {
161
+ var _e$response, _e$response$headers, _e$response$headers$l;
162
+
163
+ if (((_e$response = e.response) === null || _e$response === void 0 ? void 0 : _e$response.status) === 302 && ((_e$response$headers = e.response.headers) === null || _e$response$headers === void 0 ? void 0 : (_e$response$headers$l = _e$response$headers.location) === null || _e$response$headers$l === void 0 ? void 0 : _e$response$headers$l.indexOf('code=')) > -1) {
162
164
  (0, _Console.printMessage)('ForgeRock Identity Cloud ', 'info', false);
163
165
  deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;
164
166
  } else {
@@ -166,7 +168,9 @@ function _determineDeploymentType() {
166
168
  bodyFormData = "redirect_uri=".concat(redirectURL, "&scope=").concat(idmAdminScope, "&response_type=code&client_id=").concat(forgeopsClientId, "&csrf=").concat(_SessionStorage.default.session.getCookieValue(), "&decision=allow&code_challenge=").concat(challenge, "&code_challenge_method=").concat(challengeMethod);
167
169
  yield (0, _OAuth2OIDCApi.authorize)(bodyFormData, config);
168
170
  } catch (ex) {
169
- if (ex.response.status === 302) {
171
+ var _ex$response, _ex$response$headers, _ex$response$headers$;
172
+
173
+ if (((_ex$response = ex.response) === null || _ex$response === void 0 ? void 0 : _ex$response.status) === 302 && ((_ex$response$headers = ex.response.headers) === null || _ex$response$headers === void 0 ? void 0 : (_ex$response$headers$ = _ex$response$headers.location) === null || _ex$response$headers$ === void 0 ? void 0 : _ex$response$headers$.indexOf('code=')) > -1) {
170
174
  adminClientId = forgeopsClientId;
171
175
  (0, _Console.printMessage)('ForgeOps deployment ', 'info', false);
172
176
  deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;
@@ -263,16 +267,21 @@ function _authenticate() {
263
267
  (0, _Console.printMessage)('+++ likely cause, bad credentials!!! +++', 'error');
264
268
  return null;
265
269
  } catch (e) {
266
- if (e.response && e.response.status === 401) {
270
+ var _e$response2;
271
+
272
+ if (((_e$response2 = e.response) === null || _e$response2 === void 0 ? void 0 : _e$response2.status) === 401) {
267
273
  (0, _Console.printMessage)("error authenticating - ".concat(e.message), 'error');
268
274
  (0, _Console.printMessage)('+++ likely cause, bad credentials +++', 'error');
269
275
  }
270
276
 
271
- if (e.message && e.message === 'self signed certificate') {
277
+ if (e.message === 'self signed certificate') {
272
278
  (0, _Console.printMessage)("error authenticating - ".concat(e.message), 'error');
273
279
  (0, _Console.printMessage)('+++ use -k, --insecure option to allow +++', 'error');
274
280
  } else {
281
+ var _e$response3;
282
+
275
283
  (0, _Console.printMessage)("error authenticating - ".concat(e.message), 'error');
284
+ (0, _Console.printMessage)((_e$response3 = e.response) === null || _e$response3 === void 0 ? void 0 : _e$response3.data, 'error');
276
285
  }
277
286
 
278
287
  return null;
@@ -409,6 +418,10 @@ function _getTokens() {
409
418
  _SessionStorage.default.session.setUsername(conn.username);
410
419
 
411
420
  _SessionStorage.default.session.setPassword(conn.password);
421
+
422
+ _SessionStorage.default.session.setAuthenticationService(conn.authenticationService);
423
+
424
+ _SessionStorage.default.session.setAuthenticationHeaderOverrides(conn.authenticationHeaderOverrides);
412
425
  } else {
413
426
  return false;
414
427
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticateOps.js","names":["adminClientPassword","redirectUrlTemplate","idmAdminScope","adminClientId","getCookieName","getServerInfo","data","cookieName","error","printMessage","checkAndHandle2FA","payload","element","callbacks","type","input","value","includes","need2fa","output","code","readlineSync","question","determineDefaultRealm","deploymentType","storage","session","getRealm","global","DEFAULT_REALM_KEY","setRealm","DEPLOYMENT_TYPE_REALM_MAP","determineDeploymentType","fidcClientId","forgeopsClientId","verifier","encodeBase64Url","randomBytes","challenge","createHash","update","digest","challengeMethod","redirectURL","url","resolve","getTenant","config","maxRedirects","bodyFormData","getCookieValue","CLASSIC_DEPLOYMENT_TYPE_KEY","authorize","e","response","status","CLOUD_DEPLOYMENT_TYPE_KEY","ex","FORGEOPS_DEPLOYMENT_TYPE_KEY","getSemanticVersion","versionInfo","versionString","version","rx","match","Error","authenticate","setCookieName","headers","getUsername","getPassword","response1","step","skip2FA","response2","setCookieValue","getDeploymentType","setDeploymentType","getServerVersionInfo","fullVersion","setAmVersion","message","getAuthCode","codeChallenge","codeChallengeMethod","redirectLocationURL","request","res","responseUrl","queryObject","parse","query","getAccessToken","authCode","auth","username","password","accessToken","setBearerToken","access_token","getTokens","save","credsFromParameters","conn","getConnectionProfile","setTenant","tenant","setUsername","setPassword","getBearerToken","saveConnectionProfile"],"sources":["ops/AuthenticateOps.ts"],"sourcesContent":["import url from 'url';\nimport { createHash, randomBytes } from 'crypto';\nimport readlineSync from 'readline-sync';\nimport { encodeBase64Url } from '../api/utils/Base64';\nimport storage from '../storage/SessionStorage';\nimport * as global from '../storage/StaticStorage';\nimport { printMessage } from './utils/Console';\nimport { getServerInfo, getServerVersionInfo } from '../api/ServerInfoApi';\nimport { step } from '../api/AuthenticateApi';\nimport { accessToken, authorize } from '../api/OAuth2OIDCApi';\nimport {\n getConnectionProfile,\n saveConnectionProfile,\n} from './ConnectionProfileOps';\n\nconst adminClientPassword = 'doesnotmatter';\nconst redirectUrlTemplate = '/platform/appAuthHelperRedirect.html';\n\nconst idmAdminScope = 'fr:idm:* openid';\n\nlet adminClientId = 'idmAdminClient';\n\n/**\n * Helper function to get cookie name\n * @returns {String} cookie name\n */\nasync function getCookieName() {\n try {\n return (await getServerInfo()).data.cookieName;\n } catch (error) {\n printMessage(`Error getting cookie name: ${error}`, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to determine if this is a setup mfa prompt in the ID Cloud tenant admin login journey\n * @param {Object} payload response from the previous authentication journey step\n * @returns {Object} an object indicating if 2fa is required and the original payload\n */\nfunction checkAndHandle2FA(payload) {\n // let skippable = false;\n if ('callbacks' in payload) {\n for (const element of payload.callbacks) {\n if (element.type === 'HiddenValueCallback') {\n if (element.input[0].value.includes('skip')) {\n // skippable = true;\n element.input[0].value = 'Skip';\n return {\n need2fa: true,\n payload,\n };\n }\n }\n if (element.type === 'NameCallback') {\n if (element.output[0].value.includes('code')) {\n // skippable = false;\n printMessage('2FA is enabled and required for this user...');\n const code = readlineSync.question(`${element.output[0].value}: `);\n element.input[0].value = code;\n return {\n need2fa: true,\n payload,\n };\n }\n }\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n}\n\n/**\n * Helper function to set the default realm by deployment type\n * @param {String} deploymentType deployment type\n */\nfunction determineDefaultRealm(deploymentType) {\n if (storage.session.getRealm() === global.DEFAULT_REALM_KEY) {\n storage.session.setRealm(global.DEPLOYMENT_TYPE_REALM_MAP[deploymentType]);\n }\n}\n\n/**\n * Helper function to determine the deployment type\n * @returns {String} deployment type\n */\nasync function determineDeploymentType() {\n const fidcClientId = 'idmAdminClient';\n const forgeopsClientId = 'idm-admin-ui';\n\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n\n const config = {\n maxRedirects: 0,\n };\n let bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${fidcClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n\n let deploymentType = global.CLASSIC_DEPLOYMENT_TYPE_KEY;\n try {\n await authorize(bodyFormData, config);\n } catch (e) {\n if (e.response && e.response.status === 302) {\n printMessage('ForgeRock Identity Cloud ', 'info', false);\n deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;\n } else {\n try {\n bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${forgeopsClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n await authorize(bodyFormData, config);\n } catch (ex) {\n if (ex.response.status === 302) {\n adminClientId = forgeopsClientId;\n printMessage('ForgeOps deployment ', 'info', false);\n deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;\n } else {\n printMessage('Classic deployment ', 'info', false);\n }\n }\n }\n printMessage('detected.');\n }\n determineDefaultRealm(deploymentType);\n return deploymentType;\n}\n\n/**\n * Helper function to extract the semantic version string from a version info object\n * @param {Object} versionInfo version info object\n * @returns {String} semantic version\n */\nasync function getSemanticVersion(versionInfo) {\n if ('version' in versionInfo) {\n const versionString = versionInfo.version;\n const rx = /([\\d]\\.[\\d]\\.[\\d](\\.[\\d])*)/g;\n const version = versionString.match(rx);\n return version[0];\n }\n throw new Error('Cannot extract semantic version from version info object.');\n}\n\n/**\n * Helper function to authenticate and obtain and store session cookie\n * @returns {String} empty string or null\n */\nasync function authenticate() {\n storage.session.setCookieName(await getCookieName());\n try {\n const config = {\n headers: {\n 'X-OpenAM-Username': storage.session.getUsername(),\n 'X-OpenAM-Password': storage.session.getPassword(),\n },\n };\n const response1 = (await step({}, config)).data;\n const skip2FA = checkAndHandle2FA(response1);\n let response2 = {};\n if (skip2FA.need2fa) {\n response2 = (await step(skip2FA.payload)).data;\n } else {\n response2 = skip2FA.payload;\n }\n if ('tokenId' in response2) {\n storage.session.setCookieValue(response2['tokenId']);\n if (!storage.session.getDeploymentType()) {\n storage.session.setDeploymentType(await determineDeploymentType());\n } else {\n determineDefaultRealm(storage.session.getDeploymentType());\n }\n const versionInfo = (await getServerVersionInfo()).data;\n printMessage(`Connected to ${versionInfo.fullVersion}`);\n const version = await getSemanticVersion(versionInfo);\n storage.session.setAmVersion(version);\n return '';\n }\n printMessage(`error authenticating`, 'error');\n printMessage('+++ likely cause, bad credentials!!! +++', 'error');\n return null;\n } catch (e) {\n if (e.response && e.response.status === 401) {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ likely cause, bad credentials +++', 'error');\n }\n if (e.message && e.message === 'self signed certificate') {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ use -k, --insecure option to allow +++', 'error');\n } else {\n printMessage(`error authenticating - ${e.message}`, 'error');\n }\n return null;\n }\n}\n\n/**\n * Helper function to obtain an oauth2 authorization code\n * @param {String} redirectURL oauth2 redirect uri\n * @param {String} codeChallenge PKCE code challenge\n * @param {String} codeChallengeMethod PKCE code challenge method\n * @returns {String} oauth2 authorization code or null\n */\nasync function getAuthCode(redirectURL, codeChallenge, codeChallengeMethod) {\n try {\n const bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${adminClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${codeChallenge}&code_challenge_method=${codeChallengeMethod}`;\n const config = {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n };\n const response = await authorize(bodyFormData, config);\n if (response.status < 200 || response.status > 399) {\n printMessage('error getting auth code', 'error');\n printMessage(\n 'likely cause: mismatched parameters with OAuth client config',\n 'error'\n );\n return null;\n }\n const redirectLocationURL = response.request.res.responseUrl;\n const queryObject = url.parse(redirectLocationURL, true).query;\n if ('code' in queryObject) {\n return queryObject.code;\n }\n printMessage('auth code not found', 'error');\n return null;\n } catch (error) {\n printMessage(`error getting auth code - ${error.message}`, 'error');\n printMessage(error.response.data, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to obtain oauth2 access token\n * @returns {String} empty string or null\n */\nasync function getAccessToken() {\n try {\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n const authCode = await getAuthCode(redirectURL, challenge, challengeMethod);\n if (authCode == null) {\n printMessage('error getting auth code', 'error');\n return null;\n }\n let response = null;\n if (\n storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY\n ) {\n const config = {\n auth: {\n username: adminClientId,\n password: adminClientPassword,\n },\n };\n const bodyFormData = `redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData, config);\n } else {\n const bodyFormData = `client_id=${adminClientId}&redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData);\n }\n if (response.status < 200 || response.status > 399) {\n printMessage(`access token call returned ${response.status}`, 'error');\n return null;\n }\n if ('access_token' in response.data) {\n storage.session.setBearerToken(response.data.access_token);\n return '';\n }\n printMessage(\"can't get access token\", 'error');\n return null;\n } catch (e) {\n printMessage('error getting access token - ', 'error');\n return null;\n }\n}\n\n/**\n * Get tokens\n * @param {boolean} save true to save a connection profile upon successful authentication, false otherwise\n * @returns {boolean} true if tokens were successfully obtained, false otherwise\n */\nexport async function getTokens(save = false) {\n let credsFromParameters = true;\n // if username/password on cli are empty, try to read from connections.json\n if (\n storage.session.getUsername() == null &&\n storage.session.getPassword() == null\n ) {\n credsFromParameters = false;\n const conn = await getConnectionProfile();\n if (conn) {\n storage.session.setTenant(conn.tenant);\n storage.session.setUsername(conn.username);\n storage.session.setPassword(conn.password);\n } else {\n return false;\n }\n }\n await authenticate();\n if (\n storage.session.getCookieValue() &&\n !storage.session.getBearerToken() &&\n (storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY ||\n storage.session.getDeploymentType() ===\n global.FORGEOPS_DEPLOYMENT_TYPE_KEY)\n ) {\n await getAccessToken();\n }\n if (save && storage.session.getCookieValue() && credsFromParameters) {\n // valid cookie, which means valid username/password combo. Save it in connections.json\n saveConnectionProfile();\n return true;\n }\n if (!storage.session.getCookieValue()) {\n return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;;;;;AAKA,IAAMA,mBAAmB,GAAG,eAA5B;AACA,IAAMC,mBAAmB,GAAG,sCAA5B;AAEA,IAAMC,aAAa,GAAG,iBAAtB;AAEA,IAAIC,aAAa,GAAG,gBAApB;AAEA;AACA;AACA;AACA;;SACeC,a;;;AASf;AACA;AACA;AACA;AACA;;;;qCAbA,aAA+B;IAC7B,IAAI;MACF,OAAO,OAAO,IAAAC,4BAAA,GAAP,EAAwBC,IAAxB,CAA6BC,UAApC;IACD,CAFD,CAEE,OAAOC,KAAP,EAAc;MACd,IAAAC,qBAAA,uCAA2CD,KAA3C,GAAoD,OAApD;MACA,OAAO,IAAP;IACD;EACF,C;;;;AAOD,SAASE,iBAAT,CAA2BC,OAA3B,EAAoC;EAClC;EACA,IAAI,eAAeA,OAAnB,EAA4B;IAC1B,KAAK,IAAMC,OAAX,IAAsBD,OAAO,CAACE,SAA9B,EAAyC;MACvC,IAAID,OAAO,CAACE,IAAR,KAAiB,qBAArB,EAA4C;QAC1C,IAAIF,OAAO,CAACG,KAAR,CAAc,CAAd,EAAiBC,KAAjB,CAAuBC,QAAvB,CAAgC,MAAhC,CAAJ,EAA6C;UAC3C;UACAL,OAAO,CAACG,KAAR,CAAc,CAAd,EAAiBC,KAAjB,GAAyB,MAAzB;UACA,OAAO;YACLE,OAAO,EAAE,IADJ;YAELP;UAFK,CAAP;QAID;MACF;;MACD,IAAIC,OAAO,CAACE,IAAR,KAAiB,cAArB,EAAqC;QACnC,IAAIF,OAAO,CAACO,MAAR,CAAe,CAAf,EAAkBH,KAAlB,CAAwBC,QAAxB,CAAiC,MAAjC,CAAJ,EAA8C;UAC5C;UACA,IAAAR,qBAAA,EAAa,8CAAb;;UACA,IAAMW,IAAI,GAAGC,qBAAA,CAAaC,QAAb,WAA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CoD,mBAAhD,EAAqE;MACnE;MACA,IAAAQ,2CAAA;MACA,OAAO,IAAP;IACD;;IACD,IAAI,CAACrF,uBAAA,CAAQC,OAAR,CAAgBwB,cAAhB,EAAL,EAAuC;MACrC,OAAO,KAAP;IACD;;IACD,OAAO,IAAP;EACD,C"}
1
+ {"version":3,"file":"AuthenticateOps.js","names":["adminClientPassword","redirectUrlTemplate","idmAdminScope","adminClientId","getCookieName","getServerInfo","data","cookieName","error","printMessage","checkAndHandle2FA","payload","element","callbacks","type","input","value","includes","need2fa","output","code","readlineSync","question","determineDefaultRealm","deploymentType","storage","session","getRealm","global","DEFAULT_REALM_KEY","setRealm","DEPLOYMENT_TYPE_REALM_MAP","determineDeploymentType","fidcClientId","forgeopsClientId","verifier","encodeBase64Url","randomBytes","challenge","createHash","update","digest","challengeMethod","redirectURL","url","resolve","getTenant","config","maxRedirects","bodyFormData","getCookieValue","CLASSIC_DEPLOYMENT_TYPE_KEY","authorize","e","response","status","headers","location","indexOf","CLOUD_DEPLOYMENT_TYPE_KEY","ex","FORGEOPS_DEPLOYMENT_TYPE_KEY","getSemanticVersion","versionInfo","versionString","version","rx","match","Error","authenticate","setCookieName","getUsername","getPassword","response1","step","skip2FA","response2","setCookieValue","getDeploymentType","setDeploymentType","getServerVersionInfo","fullVersion","setAmVersion","message","getAuthCode","codeChallenge","codeChallengeMethod","redirectLocationURL","request","res","responseUrl","queryObject","parse","query","getAccessToken","authCode","auth","username","password","accessToken","setBearerToken","access_token","getTokens","save","credsFromParameters","conn","getConnectionProfile","setTenant","tenant","setUsername","setPassword","setAuthenticationService","authenticationService","setAuthenticationHeaderOverrides","authenticationHeaderOverrides","getBearerToken","saveConnectionProfile"],"sources":["ops/AuthenticateOps.ts"],"sourcesContent":["import url from 'url';\nimport { createHash, randomBytes } from 'crypto';\nimport readlineSync from 'readline-sync';\nimport { encodeBase64Url } from '../api/utils/Base64';\nimport storage from '../storage/SessionStorage';\nimport * as global from '../storage/StaticStorage';\nimport { printMessage } from './utils/Console';\nimport { getServerInfo, getServerVersionInfo } from '../api/ServerInfoApi';\nimport { step } from '../api/AuthenticateApi';\nimport { accessToken, authorize } from '../api/OAuth2OIDCApi';\nimport {\n getConnectionProfile,\n saveConnectionProfile,\n} from './ConnectionProfileOps';\n\nconst adminClientPassword = 'doesnotmatter';\nconst redirectUrlTemplate = '/platform/appAuthHelperRedirect.html';\n\nconst idmAdminScope = 'fr:idm:* openid';\n\nlet adminClientId = 'idmAdminClient';\n\n/**\n * Helper function to get cookie name\n * @returns {String} cookie name\n */\nasync function getCookieName() {\n try {\n return (await getServerInfo()).data.cookieName;\n } catch (error) {\n printMessage(`Error getting cookie name: ${error}`, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to determine if this is a setup mfa prompt in the ID Cloud tenant admin login journey\n * @param {Object} payload response from the previous authentication journey step\n * @returns {Object} an object indicating if 2fa is required and the original payload\n */\nfunction checkAndHandle2FA(payload) {\n // let skippable = false;\n if ('callbacks' in payload) {\n for (const element of payload.callbacks) {\n if (element.type === 'HiddenValueCallback') {\n if (element.input[0].value.includes('skip')) {\n // skippable = true;\n element.input[0].value = 'Skip';\n return {\n need2fa: true,\n payload,\n };\n }\n }\n if (element.type === 'NameCallback') {\n if (element.output[0].value.includes('code')) {\n // skippable = false;\n printMessage('2FA is enabled and required for this user...');\n const code = readlineSync.question(`${element.output[0].value}: `);\n element.input[0].value = code;\n return {\n need2fa: true,\n payload,\n };\n }\n }\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n}\n\n/**\n * Helper function to set the default realm by deployment type\n * @param {String} deploymentType deployment type\n */\nfunction determineDefaultRealm(deploymentType) {\n if (storage.session.getRealm() === global.DEFAULT_REALM_KEY) {\n storage.session.setRealm(global.DEPLOYMENT_TYPE_REALM_MAP[deploymentType]);\n }\n}\n\n/**\n * Helper function to determine the deployment type\n * @returns {String} deployment type\n */\nasync function determineDeploymentType() {\n const fidcClientId = 'idmAdminClient';\n const forgeopsClientId = 'idm-admin-ui';\n\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n\n const config = {\n maxRedirects: 0,\n };\n let bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${fidcClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n\n let deploymentType = global.CLASSIC_DEPLOYMENT_TYPE_KEY;\n try {\n await authorize(bodyFormData, config);\n } catch (e) {\n if (\n e.response?.status === 302 &&\n e.response.headers?.location?.indexOf('code=') > -1\n ) {\n printMessage('ForgeRock Identity Cloud ', 'info', false);\n deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;\n } else {\n try {\n bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${forgeopsClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n await authorize(bodyFormData, config);\n } catch (ex) {\n if (\n ex.response?.status === 302 &&\n ex.response.headers?.location?.indexOf('code=') > -1\n ) {\n adminClientId = forgeopsClientId;\n printMessage('ForgeOps deployment ', 'info', false);\n deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;\n } else {\n printMessage('Classic deployment ', 'info', false);\n }\n }\n }\n printMessage('detected.');\n }\n determineDefaultRealm(deploymentType);\n return deploymentType;\n}\n\n/**\n * Helper function to extract the semantic version string from a version info object\n * @param {Object} versionInfo version info object\n * @returns {String} semantic version\n */\nasync function getSemanticVersion(versionInfo) {\n if ('version' in versionInfo) {\n const versionString = versionInfo.version;\n const rx = /([\\d]\\.[\\d]\\.[\\d](\\.[\\d])*)/g;\n const version = versionString.match(rx);\n return version[0];\n }\n throw new Error('Cannot extract semantic version from version info object.');\n}\n\n/**\n * Helper function to authenticate and obtain and store session cookie\n * @returns {String} empty string or null\n */\nasync function authenticate() {\n storage.session.setCookieName(await getCookieName());\n try {\n const config = {\n headers: {\n 'X-OpenAM-Username': storage.session.getUsername(),\n 'X-OpenAM-Password': storage.session.getPassword(),\n },\n };\n const response1 = (await step({}, config)).data;\n const skip2FA = checkAndHandle2FA(response1);\n let response2 = {};\n if (skip2FA.need2fa) {\n response2 = (await step(skip2FA.payload)).data;\n } else {\n response2 = skip2FA.payload;\n }\n if ('tokenId' in response2) {\n storage.session.setCookieValue(response2['tokenId']);\n if (!storage.session.getDeploymentType()) {\n storage.session.setDeploymentType(await determineDeploymentType());\n } else {\n determineDefaultRealm(storage.session.getDeploymentType());\n }\n const versionInfo = (await getServerVersionInfo()).data;\n printMessage(`Connected to ${versionInfo.fullVersion}`);\n const version = await getSemanticVersion(versionInfo);\n storage.session.setAmVersion(version);\n return '';\n }\n printMessage(`error authenticating`, 'error');\n printMessage('+++ likely cause, bad credentials!!! +++', 'error');\n return null;\n } catch (e) {\n if (e.response?.status === 401) {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ likely cause, bad credentials +++', 'error');\n }\n if (e.message === 'self signed certificate') {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ use -k, --insecure option to allow +++', 'error');\n } else {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage(e.response?.data, 'error');\n }\n return null;\n }\n}\n\n/**\n * Helper function to obtain an oauth2 authorization code\n * @param {String} redirectURL oauth2 redirect uri\n * @param {String} codeChallenge PKCE code challenge\n * @param {String} codeChallengeMethod PKCE code challenge method\n * @returns {String} oauth2 authorization code or null\n */\nasync function getAuthCode(redirectURL, codeChallenge, codeChallengeMethod) {\n try {\n const bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${adminClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${codeChallenge}&code_challenge_method=${codeChallengeMethod}`;\n const config = {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n };\n const response = await authorize(bodyFormData, config);\n if (response.status < 200 || response.status > 399) {\n printMessage('error getting auth code', 'error');\n printMessage(\n 'likely cause: mismatched parameters with OAuth client config',\n 'error'\n );\n return null;\n }\n const redirectLocationURL = response.request.res.responseUrl;\n const queryObject = url.parse(redirectLocationURL, true).query;\n if ('code' in queryObject) {\n return queryObject.code;\n }\n printMessage('auth code not found', 'error');\n return null;\n } catch (error) {\n printMessage(`error getting auth code - ${error.message}`, 'error');\n printMessage(error.response.data, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to obtain oauth2 access token\n * @returns {String} empty string or null\n */\nasync function getAccessToken() {\n try {\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n const authCode = await getAuthCode(redirectURL, challenge, challengeMethod);\n if (authCode == null) {\n printMessage('error getting auth code', 'error');\n return null;\n }\n let response = null;\n if (\n storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY\n ) {\n const config = {\n auth: {\n username: adminClientId,\n password: adminClientPassword,\n },\n };\n const bodyFormData = `redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData, config);\n } else {\n const bodyFormData = `client_id=${adminClientId}&redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData);\n }\n if (response.status < 200 || response.status > 399) {\n printMessage(`access token call returned ${response.status}`, 'error');\n return null;\n }\n if ('access_token' in response.data) {\n storage.session.setBearerToken(response.data.access_token);\n return '';\n }\n printMessage(\"can't get access token\", 'error');\n return null;\n } catch (e) {\n printMessage('error getting access token - ', 'error');\n return null;\n }\n}\n\n/**\n * Get tokens\n * @param {boolean} save true to save a connection profile upon successful authentication, false otherwise\n * @returns {boolean} true if tokens were successfully obtained, false otherwise\n */\nexport async function getTokens(save = false) {\n let credsFromParameters = true;\n // if username/password on cli are empty, try to read from connections.json\n if (\n storage.session.getUsername() == null &&\n storage.session.getPassword() == null\n ) {\n credsFromParameters = false;\n const conn = await getConnectionProfile();\n if (conn) {\n storage.session.setTenant(conn.tenant);\n storage.session.setUsername(conn.username);\n storage.session.setPassword(conn.password);\n storage.session.setAuthenticationService(conn.authenticationService);\n storage.session.setAuthenticationHeaderOverrides(\n conn.authenticationHeaderOverrides\n );\n } else {\n return false;\n }\n }\n await authenticate();\n if (\n storage.session.getCookieValue() &&\n !storage.session.getBearerToken() &&\n (storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY ||\n storage.session.getDeploymentType() ===\n global.FORGEOPS_DEPLOYMENT_TYPE_KEY)\n ) {\n await getAccessToken();\n }\n if (save && storage.session.getCookieValue() && credsFromParameters) {\n // valid cookie, which means valid username/password combo. Save it in connections.json\n saveConnectionProfile();\n return true;\n }\n if (!storage.session.getCookieValue()) {\n return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;;;;;AAKA,IAAMA,mBAAmB,GAAG,eAA5B;AACA,IAAMC,mBAAmB,GAAG,sCAA5B;AAEA,IAAMC,aAAa,GAAG,iBAAtB;AAEA,IAAIC,aAAa,GAAG,gBAApB;AAEA;AACA;AACA;AACA;;SACeC,a;;;AASf;AACA;AACA;AACA;AACA;;;;qCAbA,aAA+B;IAC7B,IAAI;MACF,OAAO,OAAO,IAAAC,4BAAA,GAAP,EAAwBC,IAAxB,CAA6BC,UAApC;IACD,CAFD,CAEE,OAAOC,KAAP,EAAc;MACd,IAAAC,qBAAA,uCAA2CD,KAA3C,GAAoD,OAApD;MACA,OAAO,IAAP;IACD;EACF,C;;;;AAOD,SAAS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AAO,KAAP;IACD;;IACD,OAAO,IAAP;EACD,C"}
@@ -173,7 +173,9 @@ function _getConnectionProfileByHost() {
173
173
  username: profile.username ? profile.username : null,
174
174
  password: profile.encodedPassword ? yield dataProtection.decrypt(profile.encodedPassword) : null,
175
175
  key: profile.logApiKey ? profile.logApiKey : null,
176
- secret: profile.logApiSecret ? profile.logApiSecret : null
176
+ secret: profile.logApiSecret ? profile.logApiSecret : null,
177
+ authenticationService: profile.authenticationService ? profile.authenticationService : null,
178
+ authenticationHeaderOverrides: profile.authenticationHeaderOverrides ? profile.authenticationHeaderOverrides : {}
177
179
  };
178
180
  } catch (e) {
179
181
  (0, _Console.printMessage)("Can not read saved connection info, please specify credentials on command line: ".concat(e), 'error');
@@ -230,10 +232,21 @@ function _saveConnectionProfile() {
230
232
  }
231
233
 
232
234
  if (_SessionStorage.default.session.getUsername()) existingData['username'] = _SessionStorage.default.session.getUsername();
233
- if (_SessionStorage.default.session.getPassword()) existingData['encodedPassword'] = yield dataProtection.encrypt(_SessionStorage.default.session.getPassword()); // Buffer.from(storage.session.getPassword()).toString('base64');
234
-
235
+ if (_SessionStorage.default.session.getPassword()) existingData['encodedPassword'] = yield dataProtection.encrypt(_SessionStorage.default.session.getPassword());
235
236
  if (_SessionStorage.default.session.getLogApiKey()) existingData['logApiKey'] = _SessionStorage.default.session.getLogApiKey();
236
- if (_SessionStorage.default.session.getLogApiSecret()) existingData['logApiSecret'] = _SessionStorage.default.session.getLogApiSecret();
237
+ if (_SessionStorage.default.session.getLogApiSecret()) existingData['logApiSecret'] = _SessionStorage.default.session.getLogApiSecret(); // advanced settings
238
+
239
+ if (_SessionStorage.default.session.getAuthenticationService()) {
240
+ existingData['authenticationService'] = _SessionStorage.default.session.getAuthenticationService();
241
+ (0, _Console.printMessage)('Advanced setting: Authentication Service: ' + _SessionStorage.default.session.getAuthenticationService(), 'info');
242
+ }
243
+
244
+ if (_SessionStorage.default.session.getAuthenticationHeaderOverrides()) {
245
+ existingData['authenticationHeaderOverrides'] = _SessionStorage.default.session.getAuthenticationHeaderOverrides();
246
+ (0, _Console.printMessage)('Advanced setting: Authentication Header Overrides: ', 'info');
247
+ (0, _Console.printMessage)(_SessionStorage.default.session.getAuthenticationHeaderOverrides(), 'info');
248
+ }
249
+
237
250
  connectionsData[_SessionStorage.default.session.getTenant()] = existingData;
238
251
 
239
252
  _fs.default.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));
@@ -292,7 +305,9 @@ function _describeConnectionProfile() {
292
305
  username: 'Username',
293
306
  password: 'Password',
294
307
  key: 'Log API Key',
295
- secret: 'Log API Secret'
308
+ secret: 'Log API Secret',
309
+ authenticationService: 'Authentication Service',
310
+ authenticationHeaderOverrides: 'Authentication Header Overrides'
296
311
  };
297
312
  var table = (0, _Console.createObjectTable)(profile, keyMap);
298
313
  (0, _Console.printMessage)(table.toString(), 'data');
@@ -1 +1 @@
1
- {"version":3,"file":"ConnectionProfileOps.js","names":["dataProtection","DataProtection","fileOptions","indentation","getConnectionProfilesPath","storage","session","process","env","FRODO_CONNECTION_PROFILES_PATH_KEY","os","homedir","findConnectionProfile","connectionProfiles","host","tenant","includes","profile","listConnectionProfiles","long","filename","data","fs","readFileSync","connectionsData","JSON","parse","table","createTable","Object","keys","forEach","c","push","username","logApiKey","printMessage","toString","e","message","initConnectionProfiles","folderName","path","dirname","existsSync","mkdirSync","recursive","writeFileSync","stringify","convert","conn","password","encodedPassword","encrypt","getConnectionProfileByHost","decrypt","key","secret","logApiSecret","getConnectionProfile","getTenant","saveConnectionProfile","existingData","statSync","getUsername","getPassword","getLogApiKey","getLogApiSecret","deleteConnectionProfile","stat","err","code","describeConnectionProfile","showSecrets","keyMap","createObjectTable"],"sources":["ops/ConnectionProfileOps.ts"],"sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport storage from '../storage/SessionStorage';\nimport DataProtection from './utils/DataProtection';\nimport { createObjectTable, createTable, printMessage } from './utils/Console';\nimport { FRODO_CONNECTION_PROFILES_PATH_KEY } from '../storage/StaticStorage';\n\nconst dataProtection = new DataProtection();\n\nconst fileOptions = {\n indentation: 4,\n};\n\n/**\n * Get connection profiles file name\n * @returns {String} connection profiles file name\n */\nexport function getConnectionProfilesPath(): string {\n return (\n storage.session.getConnectionProfilesPath() ||\n process.env[FRODO_CONNECTION_PROFILES_PATH_KEY] ||\n `${os.homedir()}/.frodo/.frodorc`\n );\n}\n\n/**\n * Find connection profile\n * @param {Object} connectionProfiles connection profile object\n * @param {String} host tenant host url or unique substring\n * @returns {Object} connection profile object or null\n */\nfunction findConnectionProfile(connectionProfiles, host) {\n for (const tenant in connectionProfiles) {\n if (tenant.includes(host)) {\n const profile = connectionProfiles[tenant];\n profile.tenant = tenant;\n return profile;\n }\n }\n return null;\n}\n\n/**\n * List connection profiles\n * @param {boolean} long Long list format with details\n */\nexport function listConnectionProfiles(long = false) {\n const filename = getConnectionProfilesPath();\n try {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n if (long) {\n const table = createTable(['Host', 'Username', 'Log API Key']);\n Object.keys(connectionsData).forEach((c) => {\n table.push([\n c,\n connectionsData[c].username,\n connectionsData[c].logApiKey,\n ]);\n });\n printMessage(table.toString(), 'data');\n } else {\n Object.keys(connectionsData).forEach((c) => {\n printMessage(`${c}`, 'data');\n });\n }\n printMessage(\n 'Any unique substring of a saved host can be used as the value for host parameter in all commands',\n 'info'\n );\n } catch (e) {\n printMessage(`No connections found in ${filename} (${e.message})`, 'error');\n }\n}\n\n/**\n * Initialize connection profiles\n */\nexport function initConnectionProfiles() {\n // create connections.json file if it doesn't exist\n const filename = getConnectionProfilesPath();\n const folderName = path.dirname(filename);\n if (!fs.existsSync(folderName)) {\n fs.mkdirSync(folderName, { recursive: true });\n if (!fs.existsSync(filename)) {\n fs.writeFileSync(\n filename,\n JSON.stringify({}, null, fileOptions.indentation)\n );\n }\n }\n // encrypt the password from clear text to aes-256-GCM\n else {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n let convert = false;\n Object.keys(connectionsData).forEach(async (conn) => {\n if (connectionsData[conn].password) {\n convert = true;\n connectionsData[conn].encodedPassword = await dataProtection.encrypt(\n connectionsData[conn].password\n ); // Buffer.from(connectionsData[conn].password).toString('base64');\n delete connectionsData[conn].password;\n }\n });\n if (convert) {\n fs.writeFileSync(\n filename,\n JSON.stringify(connectionsData, null, fileOptions.indentation)\n );\n }\n }\n}\n\n/**\n * Get connection profile by host\n * @param {String} host host tenant host url or unique substring\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfileByHost(host) {\n try {\n const filename = getConnectionProfilesPath();\n const connectionsData = JSON.parse(fs.readFileSync(filename, 'utf8'));\n const profile = findConnectionProfile(connectionsData, host);\n if (!profile) {\n printMessage(\n `Profile for ${host} not found. Please specify credentials on command line`,\n 'error'\n );\n return null;\n }\n return {\n tenant: profile.tenant,\n username: profile.username ? profile.username : null,\n password: profile.encodedPassword\n ? await dataProtection.decrypt(profile.encodedPassword)\n : null,\n key: profile.logApiKey ? profile.logApiKey : null,\n secret: profile.logApiSecret ? profile.logApiSecret : null,\n };\n } catch (e) {\n printMessage(\n `Can not read saved connection info, please specify credentials on command line: ${e}`,\n 'error'\n );\n return null;\n }\n}\n\n/**\n * Get connection profile\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfile() {\n return getConnectionProfileByHost(storage.session.getTenant());\n}\n\n/**\n * Save connection profile\n */\nexport async function saveConnectionProfile() {\n const filename = getConnectionProfilesPath();\n printMessage(`Saving creds in ${filename}...`);\n let connectionsData = {};\n let existingData = {};\n try {\n fs.statSync(filename);\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n if (connectionsData[storage.session.getTenant()]) {\n existingData = connectionsData[storage.session.getTenant()];\n printMessage(\n `Updating connection profile ${storage.session.getTenant()}`\n );\n } else\n printMessage(`Adding connection profile ${storage.session.getTenant()}`);\n } catch (e) {\n printMessage(\n `Creating connection profiles file ${filename} with ${storage.session.getTenant()}`\n );\n }\n if (storage.session.getUsername())\n existingData['username'] = storage.session.getUsername();\n if (storage.session.getPassword())\n existingData['encodedPassword'] = await dataProtection.encrypt(\n storage.session.getPassword()\n ); // Buffer.from(storage.session.getPassword()).toString('base64');\n if (storage.session.getLogApiKey())\n existingData['logApiKey'] = storage.session.getLogApiKey();\n if (storage.session.getLogApiSecret())\n existingData['logApiSecret'] = storage.session.getLogApiSecret();\n connectionsData[storage.session.getTenant()] = existingData;\n\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n}\n\n/**\n * Delete connection profile\n * @param {String} host host tenant host url or unique substring\n */\nexport function deleteConnectionProfile(host) {\n const filename = getConnectionProfilesPath();\n let connectionsData = {};\n fs.stat(filename, (err) => {\n if (err == null) {\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n const profile = findConnectionProfile(connectionsData, host);\n if (profile) {\n printMessage(`Deleting connection profile ${profile.tenant}`);\n delete connectionsData[profile.tenant];\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n } else if (err.code === 'ENOENT') {\n printMessage(`Connection profile file ${filename} not found`);\n } else {\n printMessage(\n `Error in deleting connection profile: ${err.code}`,\n 'error'\n );\n }\n });\n}\n\nexport async function describeConnectionProfile(host, showSecrets) {\n const profile = await getConnectionProfileByHost(host);\n if (profile) {\n if (!showSecrets) {\n delete profile.password;\n delete profile.secret;\n }\n if (!profile.key) {\n delete profile.key;\n delete profile.secret;\n }\n const keyMap = {\n tenant: 'Host',\n username: 'Username',\n password: 'Password',\n key: 'Log API Key',\n secret: 'Log API Secret',\n };\n const table = createObjectTable(profile, keyMap);\n printMessage(table.toString(), 'data');\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;AAEA,IAAMA,cAAc,GAAG,IAAIC,uBAAJ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lBD,MAkBO;MACL,IAAAD,qBAAA,kCAAsCtB,IAAtC;IACD;EACF,C"}
1
+ {"version":3,"file":"ConnectionProfileOps.js","names":["dataProtection","DataProtection","fileOptions","indentation","getConnectionProfilesPath","storage","session","process","env","FRODO_CONNECTION_PROFILES_PATH_KEY","os","homedir","findConnectionProfile","connectionProfiles","host","tenant","includes","profile","listConnectionProfiles","long","filename","data","fs","readFileSync","connectionsData","JSON","parse","table","createTable","Object","keys","forEach","c","push","username","logApiKey","printMessage","toString","e","message","initConnectionProfiles","folderName","path","dirname","existsSync","mkdirSync","recursive","writeFileSync","stringify","convert","conn","password","encodedPassword","encrypt","getConnectionProfileByHost","decrypt","key","secret","logApiSecret","authenticationService","authenticationHeaderOverrides","getConnectionProfile","getTenant","saveConnectionProfile","existingData","statSync","getUsername","getPassword","getLogApiKey","getLogApiSecret","getAuthenticationService","getAuthenticationHeaderOverrides","deleteConnectionProfile","stat","err","code","describeConnectionProfile","showSecrets","keyMap","createObjectTable"],"sources":["ops/ConnectionProfileOps.ts"],"sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport storage from '../storage/SessionStorage';\nimport DataProtection from './utils/DataProtection';\nimport { createObjectTable, createTable, printMessage } from './utils/Console';\nimport { FRODO_CONNECTION_PROFILES_PATH_KEY } from '../storage/StaticStorage';\n\nconst dataProtection = new DataProtection();\n\nconst fileOptions = {\n indentation: 4,\n};\n\n/**\n * Get connection profiles file name\n * @returns {String} connection profiles file name\n */\nexport function getConnectionProfilesPath(): string {\n return (\n storage.session.getConnectionProfilesPath() ||\n process.env[FRODO_CONNECTION_PROFILES_PATH_KEY] ||\n `${os.homedir()}/.frodo/.frodorc`\n );\n}\n\n/**\n * Find connection profile\n * @param {Object} connectionProfiles connection profile object\n * @param {String} host tenant host url or unique substring\n * @returns {Object} connection profile object or null\n */\nfunction findConnectionProfile(connectionProfiles, host) {\n for (const tenant in connectionProfiles) {\n if (tenant.includes(host)) {\n const profile = connectionProfiles[tenant];\n profile.tenant = tenant;\n return profile;\n }\n }\n return null;\n}\n\n/**\n * List connection profiles\n * @param {boolean} long Long list format with details\n */\nexport function listConnectionProfiles(long = false) {\n const filename = getConnectionProfilesPath();\n try {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n if (long) {\n const table = createTable(['Host', 'Username', 'Log API Key']);\n Object.keys(connectionsData).forEach((c) => {\n table.push([\n c,\n connectionsData[c].username,\n connectionsData[c].logApiKey,\n ]);\n });\n printMessage(table.toString(), 'data');\n } else {\n Object.keys(connectionsData).forEach((c) => {\n printMessage(`${c}`, 'data');\n });\n }\n printMessage(\n 'Any unique substring of a saved host can be used as the value for host parameter in all commands',\n 'info'\n );\n } catch (e) {\n printMessage(`No connections found in ${filename} (${e.message})`, 'error');\n }\n}\n\n/**\n * Initialize connection profiles\n */\nexport function initConnectionProfiles() {\n // create connections.json file if it doesn't exist\n const filename = getConnectionProfilesPath();\n const folderName = path.dirname(filename);\n if (!fs.existsSync(folderName)) {\n fs.mkdirSync(folderName, { recursive: true });\n if (!fs.existsSync(filename)) {\n fs.writeFileSync(\n filename,\n JSON.stringify({}, null, fileOptions.indentation)\n );\n }\n }\n // encrypt the password from clear text to aes-256-GCM\n else {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n let convert = false;\n Object.keys(connectionsData).forEach(async (conn) => {\n if (connectionsData[conn].password) {\n convert = true;\n connectionsData[conn].encodedPassword = await dataProtection.encrypt(\n connectionsData[conn].password\n ); // Buffer.from(connectionsData[conn].password).toString('base64');\n delete connectionsData[conn].password;\n }\n });\n if (convert) {\n fs.writeFileSync(\n filename,\n JSON.stringify(connectionsData, null, fileOptions.indentation)\n );\n }\n }\n}\n\n/**\n * Get connection profile by host\n * @param {String} host host tenant host url or unique substring\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfileByHost(host) {\n try {\n const filename = getConnectionProfilesPath();\n const connectionsData = JSON.parse(fs.readFileSync(filename, 'utf8'));\n const profile = findConnectionProfile(connectionsData, host);\n if (!profile) {\n printMessage(\n `Profile for ${host} not found. Please specify credentials on command line`,\n 'error'\n );\n return null;\n }\n return {\n tenant: profile.tenant,\n username: profile.username ? profile.username : null,\n password: profile.encodedPassword\n ? await dataProtection.decrypt(profile.encodedPassword)\n : null,\n key: profile.logApiKey ? profile.logApiKey : null,\n secret: profile.logApiSecret ? profile.logApiSecret : null,\n authenticationService: profile.authenticationService\n ? profile.authenticationService\n : null,\n authenticationHeaderOverrides: profile.authenticationHeaderOverrides\n ? profile.authenticationHeaderOverrides\n : {},\n };\n } catch (e) {\n printMessage(\n `Can not read saved connection info, please specify credentials on command line: ${e}`,\n 'error'\n );\n return null;\n }\n}\n\n/**\n * Get connection profile\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfile() {\n return getConnectionProfileByHost(storage.session.getTenant());\n}\n\n/**\n * Save connection profile\n */\nexport async function saveConnectionProfile() {\n const filename = getConnectionProfilesPath();\n printMessage(`Saving creds in ${filename}...`);\n let connectionsData = {};\n let existingData = {};\n try {\n fs.statSync(filename);\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n if (connectionsData[storage.session.getTenant()]) {\n existingData = connectionsData[storage.session.getTenant()];\n printMessage(\n `Updating connection profile ${storage.session.getTenant()}`\n );\n } else\n printMessage(`Adding connection profile ${storage.session.getTenant()}`);\n } catch (e) {\n printMessage(\n `Creating connection profiles file ${filename} with ${storage.session.getTenant()}`\n );\n }\n if (storage.session.getUsername())\n existingData['username'] = storage.session.getUsername();\n if (storage.session.getPassword())\n existingData['encodedPassword'] = await dataProtection.encrypt(\n storage.session.getPassword()\n );\n if (storage.session.getLogApiKey())\n existingData['logApiKey'] = storage.session.getLogApiKey();\n if (storage.session.getLogApiSecret())\n existingData['logApiSecret'] = storage.session.getLogApiSecret();\n\n // advanced settings\n if (storage.session.getAuthenticationService()) {\n existingData['authenticationService'] =\n storage.session.getAuthenticationService();\n printMessage(\n 'Advanced setting: Authentication Service: ' +\n storage.session.getAuthenticationService(),\n 'info'\n );\n }\n if (storage.session.getAuthenticationHeaderOverrides()) {\n existingData['authenticationHeaderOverrides'] =\n storage.session.getAuthenticationHeaderOverrides();\n printMessage('Advanced setting: Authentication Header Overrides: ', 'info');\n printMessage(storage.session.getAuthenticationHeaderOverrides(), 'info');\n }\n\n connectionsData[storage.session.getTenant()] = existingData;\n\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n}\n\n/**\n * Delete connection profile\n * @param {String} host host tenant host url or unique substring\n */\nexport function deleteConnectionProfile(host) {\n const filename = getConnectionProfilesPath();\n let connectionsData = {};\n fs.stat(filename, (err) => {\n if (err == null) {\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n const profile = findConnectionProfile(connectionsData, host);\n if (profile) {\n printMessage(`Deleting connection profile ${profile.tenant}`);\n delete connectionsData[profile.tenant];\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n } else if (err.code === 'ENOENT') {\n printMessage(`Connection profile file ${filename} not found`);\n } else {\n printMessage(\n `Error in deleting connection profile: ${err.code}`,\n 'error'\n );\n }\n });\n}\n\nexport async function describeConnectionProfile(host, showSecrets) {\n const profile = await getConnectionProfileByHost(host);\n if (profile) {\n if (!showSecrets) {\n delete profile.password;\n delete profile.secret;\n }\n if (!profile.key) {\n delete profile.key;\n delete profile.secret;\n }\n const keyMap = {\n tenant: 'Host',\n username: 'Username',\n password: 'Password',\n key: 'Log API Key',\n secret: 'Log API Secret',\n authenticationService: 'Authentication Service',\n authenticationHeaderOverrides: 'Authentication Header Overrides',\n };\n const table = createObjectTable(profile, keyMap);\n printMessage(table.toString(), 'data');\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;AAEA,IAAMA,cAAc,GAAG,IAAIC,uBA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/C,GAEE,OAFF;IAID;EACF,CApBD;AAqBD;;SAEqBC,yB;;;;;iDAAf,WAAyC9D,IAAzC,EAA+C+D,WAA/C,EAA4D;IACjE,IAAM5D,OAAO,SAASqC,0BAA0B,CAACxC,IAAD,CAAhD;;IACA,IAAIG,OAAJ,EAAa;MACX,IAAI,CAAC4D,WAAL,EAAkB;QAChB,OAAO5D,OAAO,CAACkC,QAAf;QACA,OAAOlC,OAAO,CAACwC,MAAf;MACD;;MACD,IAAI,CAACxC,OAAO,CAACuC,GAAb,EAAkB;QAChB,OAAOvC,OAAO,CAACuC,GAAf;QACA,OAAOvC,OAAO,CAACwC,MAAf;MACD;;MACD,IAAMqB,MAAM,GAAG;QACb/D,MAAM,EAAE,MADK;QAEbmB,QAAQ,EAAE,UAFG;QAGbiB,QAAQ,EAAE,UAHG;QAIbK,GAAG,EAAE,aAJQ;QAKbC,MAAM,EAAE,gBALK;QAMbE,qBAAqB,EAAE,wBANV;QAObC,6BAA6B,EAAE;MAPlB,CAAf;MASA,IAAMjC,KAAK,GAAG,IAAAoD,0BAAA,EAAkB9D,OAAlB,EAA2B6D,MAA3B,CAAd;MACA,IAAA1C,qBAAA,EAAaT,KAAK,CAACU,QAAN,EAAb,EAA+B,MAA/B;IACD,CApBD,MAoBO;MACL,IAAAD,qBAAA,kCAAsCtB,IAAtC;IACD;EACF,C"}
@@ -16,7 +16,9 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
16
16
  var _dirname = _path.default.dirname((0, _url.fileURLToPath)(require('url').pathToFileURL(__filename).toString()));
17
17
 
18
18
  var pkg = JSON.parse(_fs.default.readFileSync(_path.default.resolve(_dirname, '../../package.json'), 'utf8'));
19
- var _sessionStorage = {};
19
+ var _sessionStorage = {
20
+ authenticationHeaderOverrides: {}
21
+ };
20
22
  var _default = {
21
23
  session: {
22
24
  setItem: (key, value) => _sessionStorage[key] = value,
@@ -37,6 +39,10 @@ var _default = {
37
39
  getCookieName: () => _sessionStorage['cookieName'],
38
40
  setCookieValue: value => _sessionStorage['cookieValue'] = value,
39
41
  getCookieValue: () => _sessionStorage['cookieValue'],
42
+ setAuthenticationService: value => _sessionStorage['authenticationService'] = value,
43
+ getAuthenticationService: () => _sessionStorage['authenticationService'],
44
+ setAuthenticationHeaderOverrides: value => _sessionStorage['authenticationHeaderOverrides'] = value,
45
+ getAuthenticationHeaderOverrides: () => _sessionStorage['authenticationHeaderOverrides'],
40
46
  setBearerToken: value => _sessionStorage['bearerToken'] = value,
41
47
  getBearerToken: () => _sessionStorage['bearerToken'],
42
48
  setLogApiKey: value => _sessionStorage['logApiKey'] = value,
@@ -1 +1 @@
1
- {"version":3,"file":"SessionStorage.js","names":["__dirname","path","dirname","fileURLToPath","pkg","JSON","parse","fs","readFileSync","resolve","_sessionStorage","session","setItem","key","value","getItem","removeItem","raw","setUsername","getUsername","setPassword","getPassword","setTenant","getTenant","setDeploymentType","getDeploymentType","setRealm","getRealm","setCookieName","getCookieName","setCookieValue","getCookieValue","setBearerToken","getBearerToken","setLogApiKey","getLogApiKey","setLogApiSecret","getLogApiSecret","setAmVersion","getAmVersion","setFrodoVersion","getFrodoVersion","version","process","setAllowInsecureConnection","getAllowInsecureConnection","setConnectionProfilesPath","getConnectionProfilesPath","setMasterKeyPath","getMasterKeyPath","setPrintHandler","printHandler","getPrintHandler","setCreateProgressHandler","handler","getCreateProgressHandler","setUpdateProgressHandler","getUpdateProgressHandler","setStopProgressHandler","getStopProgressHandler"],"sources":["storage/SessionStorage.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\nconst _sessionStorage = {};\n\nexport default {\n session: {\n setItem: (key, value) => (_sessionStorage[key] = value),\n getItem: (key) => _sessionStorage[key],\n removeItem: (key) => delete _sessionStorage[key],\n raw: _sessionStorage,\n setUsername: (value) => (_sessionStorage['username'] = value),\n getUsername: () => _sessionStorage['username'],\n setPassword: (value) => (_sessionStorage['password'] = value),\n getPassword: () => _sessionStorage['password'],\n setTenant: (value) => (_sessionStorage['tenant'] = value),\n getTenant: () => _sessionStorage['tenant'],\n setDeploymentType: (value) => (_sessionStorage['deploymentType'] = value),\n getDeploymentType: () => _sessionStorage['deploymentType'],\n setRealm: (value) => (_sessionStorage['realm'] = value),\n getRealm: () => _sessionStorage['realm'],\n setCookieName: (value) => (_sessionStorage['cookieName'] = value),\n getCookieName: () => _sessionStorage['cookieName'],\n setCookieValue: (value) => (_sessionStorage['cookieValue'] = value),\n getCookieValue: () => _sessionStorage['cookieValue'],\n setBearerToken: (value) => (_sessionStorage['bearerToken'] = value),\n getBearerToken: () => _sessionStorage['bearerToken'],\n setLogApiKey: (value) => (_sessionStorage['logApiKey'] = value),\n getLogApiKey: () => _sessionStorage['logApiKey'],\n setLogApiSecret: (value) => (_sessionStorage['logApiSecret'] = value),\n getLogApiSecret: () => _sessionStorage['logApiSecret'],\n setAmVersion: (value) => (_sessionStorage['amVersion'] = value),\n getAmVersion: () => _sessionStorage['amVersion'],\n setFrodoVersion: (value) => (_sessionStorage['frodoVersion'] = value),\n getFrodoVersion: () =>\n _sessionStorage['frodoVersion'] || `v${pkg.version} [${process.version}]`,\n setAllowInsecureConnection: (value) =>\n (_sessionStorage['insecure'] = value),\n getAllowInsecureConnection: () => _sessionStorage['insecure'],\n setConnectionProfilesPath: (value) =>\n (_sessionStorage['connectionProfilesPath'] = value),\n getConnectionProfilesPath: () => _sessionStorage['connectionProfilesPath'],\n setMasterKeyPath: (value) => (_sessionStorage['masterKeyPath'] = value),\n getMasterKeyPath: () => _sessionStorage['masterKeyPath'],\n setPrintHandler: (printHandler) =>\n (_sessionStorage['printHandler'] = printHandler),\n getPrintHandler: () => _sessionStorage['printHandler'],\n setCreateProgressHandler: (handler) =>\n (_sessionStorage['createProgressHandler'] = handler),\n getCreateProgressHandler: () => _sessionStorage['createProgressHandler'],\n setUpdateProgressHandler: (handler) =>\n (_sessionStorage['updateProgressHandler'] = handler),\n getUpdateProgressHandler: () => _sessionStorage['updateProgressHandler'],\n setStopProgressHandler: (handler) =>\n (_sessionStorage['stopProgressHandler'] = handler),\n getStopProgressHandler: () => _sessionStorage['stopProgressHandler'],\n },\n};\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;;;AAEA,IAAMA,QAAS,GAAGC,aAAA,CAAKC,OAAL,CAAa,IAAAC,kBAAA,sDAAb,CAAlB;;AAEA,IAAMC,GAAG,GAAGC,IAAI,CAACC,KAAL,CACVC,WAAA,CAAGC,YAAH,CAAgBP,aAAA,CAAKQ,OAAL,CAAaT,QAAb,EAAwB,oBAAxB,CAAhB,EAA+D,MAA/D,CADU,CAAZ;AAIA,IAAMU,eAAe,GAAG,EAAxB;eAEe;EACbC,OAAO,EAAE;IACPC,OAAO,EAAE,CAACC,GAAD,EAAMC,KAAN,KAAiBJ,eAAe,CAACG,GAAD,CAAf,GAAuBC,KAD1C;IAEPC,OAAO,EAAGF,GAAD,IAASH,eAAe,CAACG,GAAD,CAF1B;IAGPG,UAAU,EAAGH,GAAD,IAAS,OAAOH,eAAe,CAACG,GAAD,CAHpC;IAIPI,GAAG,EAAEP,eAJE;IAKPQ,WAAW,EAAGJ,KAAD,IAAYJ,eAAe,CAAC,UAAD,CAAf,GAA8BI,KALhD;IAMPK,WAAW,EAAE,MAAMT,eAAe,CAAC,UAAD,CAN3B;IAOPU,WAAW,EAAGN,KAAD,IAAYJ,eAAe,CAAC,UAAD,CAAf,GAA8BI,KAPhD;IAQPO,WAAW,EAAE,MAAMX,eAAe,CAAC,UAAD,CAR3B;IASPY,SAAS,EAAGR,KAAD,IAAYJ,eAAe,CAAC,QAAD,CAAf,GAA4BI,KAT5C;IAUPS,SAAS,EAAE,MAAMb,eAAe,CAAC,QAAD,CAVzB;IAWPc,iBAAiB,EAAGV,KAAD,IAAYJ,eAAe,CAAC,gBAAD,CAAf,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KAAD,IACzBJ,eAAe,CAAC,UAAD,CAAf,GAA8BI,KA/B1B;IAgCP+B,0BAA0B,EAAE,MAAMnC,eAAe,CAAC,UAAD,CAhC1C;IAiCPoC,yBAAyB,EAAGhC,KAAD,IACxBJ,eAAe,CAAC,wBAAD,CAAf,GAA4CI,KAlCxC;IAmCPiC,yBAAyB,EAAE,MAAMrC,eAAe,CAAC,wBAAD,CAnCzC;IAoCPsC,gBAAgB,EAAGlC,KAAD,IAAYJ,eAAe,CAAC,eAAD,CAAf,GAAmCI,KApC1D;IAqCPmC,gBAAgB,EAAE,MAAMvC,eAAe,CAAC,eAAD,CArChC;IAsCPwC,eAAe,EAAGC,YAAD,IACdzC,eAAe,CAAC,cAAD,CAAf,GAAkCyC,YAvC9B;IAwCPC,eAAe,EAAE,MAAM1C,eAAe,CAAC,cAAD,CAxC/B;IAyCP2C,wBAAwB,EAAGC,OAAD,IACvB5C,eAAe,CAAC,uBAAD,CAAf,GAA2C4C,OA1CvC;IA2CPC,wBAAwB,EAAE,MAAM7C,eAAe,CAAC,uBAAD,CA3CxC;IA4CP8C,wBAAwB,EAAGF,OAAD,IACvB5C,eAAe,CAAC,uBAAD,CAAf,GAA2C4C,OA7CvC;IA8CPG,wBAAwB,EAAE,MAAM/C,eAAe,CAAC,uBAAD,CA9CxC;IA+CPgD,sBAAsB,EAAGJ,OAAD,IACrB5C,eAAe,CAAC,qBAAD,CAAf,GAAyC4C,OAhDrC;IAiDPK,sBAAsB,EAAE,MAAMjD,eAAe,CAAC,qBAAD;EAjDtC;AADI,C"}
1
+ {"version":3,"file":"SessionStorage.js","names":["__dirname","path","dirname","fileURLToPath","pkg","JSON","parse","fs","readFileSync","resolve","_sessionStorage","authenticationHeaderOverrides","session","setItem","key","value","getItem","removeItem","raw","setUsername","getUsername","setPassword","getPassword","setTenant","getTenant","setDeploymentType","getDeploymentType","setRealm","getRealm","setCookieName","getCookieName","setCookieValue","getCookieValue","setAuthenticationService","getAuthenticationService","setAuthenticationHeaderOverrides","getAuthenticationHeaderOverrides","setBearerToken","getBearerToken","setLogApiKey","getLogApiKey","setLogApiSecret","getLogApiSecret","setAmVersion","getAmVersion","setFrodoVersion","getFrodoVersion","version","process","setAllowInsecureConnection","getAllowInsecureConnection","setConnectionProfilesPath","getConnectionProfilesPath","setMasterKeyPath","getMasterKeyPath","setPrintHandler","printHandler","getPrintHandler","setCreateProgressHandler","handler","getCreateProgressHandler","setUpdateProgressHandler","getUpdateProgressHandler","setStopProgressHandler","getStopProgressHandler"],"sources":["storage/SessionStorage.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\nconst _sessionStorage = {\n authenticationHeaderOverrides: {},\n};\n\nexport default {\n session: {\n setItem: (key, value) => (_sessionStorage[key] = value),\n getItem: (key) => _sessionStorage[key],\n removeItem: (key) => delete _sessionStorage[key],\n raw: _sessionStorage,\n setUsername: (value) => (_sessionStorage['username'] = value),\n getUsername: () => _sessionStorage['username'],\n setPassword: (value) => (_sessionStorage['password'] = value),\n getPassword: () => _sessionStorage['password'],\n setTenant: (value) => (_sessionStorage['tenant'] = value),\n getTenant: () => _sessionStorage['tenant'],\n setDeploymentType: (value) => (_sessionStorage['deploymentType'] = value),\n getDeploymentType: () => _sessionStorage['deploymentType'],\n setRealm: (value) => (_sessionStorage['realm'] = value),\n getRealm: () => _sessionStorage['realm'],\n setCookieName: (value) => (_sessionStorage['cookieName'] = value),\n getCookieName: () => _sessionStorage['cookieName'],\n setCookieValue: (value) => (_sessionStorage['cookieValue'] = value),\n getCookieValue: () => _sessionStorage['cookieValue'],\n setAuthenticationService: (value) =>\n (_sessionStorage['authenticationService'] = value),\n getAuthenticationService: () => _sessionStorage['authenticationService'],\n setAuthenticationHeaderOverrides: (value) =>\n (_sessionStorage['authenticationHeaderOverrides'] = value),\n getAuthenticationHeaderOverrides: () =>\n _sessionStorage['authenticationHeaderOverrides'],\n setBearerToken: (value) => (_sessionStorage['bearerToken'] = value),\n getBearerToken: () => _sessionStorage['bearerToken'],\n setLogApiKey: (value) => (_sessionStorage['logApiKey'] = value),\n getLogApiKey: () => _sessionStorage['logApiKey'],\n setLogApiSecret: (value) => (_sessionStorage['logApiSecret'] = value),\n getLogApiSecret: () => _sessionStorage['logApiSecret'],\n setAmVersion: (value) => (_sessionStorage['amVersion'] = value),\n getAmVersion: () => _sessionStorage['amVersion'],\n setFrodoVersion: (value) => (_sessionStorage['frodoVersion'] = value),\n getFrodoVersion: () =>\n _sessionStorage['frodoVersion'] || `v${pkg.version} [${process.version}]`,\n setAllowInsecureConnection: (value) =>\n (_sessionStorage['insecure'] = value),\n getAllowInsecureConnection: () => _sessionStorage['insecure'],\n setConnectionProfilesPath: (value) =>\n (_sessionStorage['connectionProfilesPath'] = value),\n getConnectionProfilesPath: () => _sessionStorage['connectionProfilesPath'],\n setMasterKeyPath: (value) => (_sessionStorage['masterKeyPath'] = value),\n getMasterKeyPath: () => _sessionStorage['masterKeyPath'],\n setPrintHandler: (printHandler) =>\n (_sessionStorage['printHandler'] = printHandler),\n getPrintHandler: () => _sessionStorage['printHandler'],\n setCreateProgressHandler: (handler) =>\n (_sessionStorage['createProgressHandler'] = handler),\n getCreateProgressHandler: () => _sessionStorage['createProgressHandler'],\n setUpdateProgressHandler: (handler) =>\n (_sessionStorage['updateProgressHandler'] = handler),\n getUpdateProgressHandler: () => _sessionStorage['updateProgressHandler'],\n setStopProgressHandler: (handler) =>\n (_sessionStorage['stopProgressHandler'] = handler),\n getStopProgressHandler: () => _sessionStorage['stopProgressHandler'],\n },\n};\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;;;AAEA,IAAMA,QAAS,GAAGC,aAAA,CAAKC,OAAL,CAAa,IAAAC,kBAAA,sDAAb,CAAlB;;AAEA,IAAMC,GAAG,GAAGC,IAAI,CAACC,KAA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,MAAMxC,eAAe,CAAC,UAAD,CAvC1C;IAwCPyC,yBAAyB,EAAGpC,KAAD,IACxBL,eAAe,CAAC,wBAAD,CAAf,GAA4CK,KAzCxC;IA0CPqC,yBAAyB,EAAE,MAAM1C,eAAe,CAAC,wBAAD,CA1CzC;IA2CP2C,gBAAgB,EAAGtC,KAAD,IAAYL,eAAe,CAAC,eAAD,CAAf,GAAmCK,KA3C1D;IA4CPuC,gBAAgB,EAAE,MAAM5C,eAAe,CAAC,eAAD,CA5ChC;IA6CP6C,eAAe,EAAGC,YAAD,IACd9C,eAAe,CAAC,cAAD,CAAf,GAAkC8C,YA9C9B;IA+CPC,eAAe,EAAE,MAAM/C,eAAe,CAAC,cAAD,CA/C/B;IAgDPgD,wBAAwB,EAAGC,OAAD,IACvBjD,eAAe,CAAC,uBAAD,CAAf,GAA2CiD,OAjDvC;IAkDPC,wBAAwB,EAAE,MAAMlD,eAAe,CAAC,uBAAD,CAlDxC;IAmDPmD,wBAAwB,EAAGF,OAAD,IACvBjD,eAAe,CAAC,uBAAD,CAAf,GAA2CiD,OApDvC;IAqDPG,wBAAwB,EAAE,MAAMpD,eAAe,CAAC,uBAAD,CArDxC;IAsDPqD,sBAAsB,EAAGJ,OAAD,IACrBjD,eAAe,CAAC,qBAAD,CAAf,GAAyCiD,OAvDrC;IAwDPK,sBAAsB,EAAE,MAAMtD,eAAe,CAAC,qBAAD;EAxDtC;AADI,C"}
@@ -2,6 +2,7 @@ import util from 'util';
2
2
  import { generateAmApi } from './BaseApi';
3
3
  import storage from '../storage/SessionStorage';
4
4
  const authenticateUrlTemplate = '%s/json%s/authenticate';
5
+ const authenticateWithServiceUrlTemplate = `${authenticateUrlTemplate}?authIndexType=service&authIndexValue=%s`;
5
6
  const apiVersion = 'resource=2.0, protocol=1.0';
6
7
 
7
8
  const getApiConfig = () => ({
@@ -25,7 +26,7 @@ export function getRealmUrl(realm) {
25
26
  return realmPath;
26
27
  }
27
28
  export async function step(data = {}, config = {}) {
28
- const urlString = util.format(authenticateUrlTemplate, storage.session.getTenant(), getRealmUrl('/'));
29
+ const urlString = storage.session.getAuthenticationService() ? util.format(authenticateWithServiceUrlTemplate, storage.session.getTenant(), getRealmUrl('/'), storage.session.getAuthenticationService()) : util.format(authenticateUrlTemplate, storage.session.getTenant(), getRealmUrl('/'));
29
30
  return generateAmApi(getApiConfig()).post(urlString, data, config);
30
31
  }
31
32
  //# sourceMappingURL=AuthenticateApi.js.map
@@ -108,7 +108,9 @@ export function generateAmApi(resource, requestOverride = {}) {
108
108
  baseURL: `${storage.session.getTenant()}/json`,
109
109
  timeout,
110
110
  ...requestOverride,
111
- headers,
111
+ headers: { ...headers,
112
+ ...storage.session.getAuthenticationHeaderOverrides()
113
+ },
112
114
  httpAgent: getHttpAgent(),
113
115
  httpsAgent: getHttpsAgent(),
114
116
  proxy: getProxy()
@@ -142,7 +144,9 @@ export function generateOauth2Api(resource, requestOverride = {}) {
142
144
  baseURL: `${storage.session.getTenant()}/json${resource.path}`,
143
145
  timeout,
144
146
  ...requestOverride,
145
- headers,
147
+ headers: { ...headers,
148
+ ...storage.session.getAuthenticationHeaderOverrides()
149
+ },
146
150
  httpAgent: getHttpAgent(),
147
151
  httpsAgent: getHttpsAgent(),
148
152
  proxy: getProxy()
@@ -108,7 +108,9 @@ async function determineDeploymentType() {
108
108
  try {
109
109
  await authorize(bodyFormData, config);
110
110
  } catch (e) {
111
- if (e.response && e.response.status === 302) {
111
+ var _e$response, _e$response$headers, _e$response$headers$l;
112
+
113
+ if (((_e$response = e.response) === null || _e$response === void 0 ? void 0 : _e$response.status) === 302 && ((_e$response$headers = e.response.headers) === null || _e$response$headers === void 0 ? void 0 : (_e$response$headers$l = _e$response$headers.location) === null || _e$response$headers$l === void 0 ? void 0 : _e$response$headers$l.indexOf('code=')) > -1) {
112
114
  printMessage('ForgeRock Identity Cloud ', 'info', false);
113
115
  deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;
114
116
  } else {
@@ -116,7 +118,9 @@ async function determineDeploymentType() {
116
118
  bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${forgeopsClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;
117
119
  await authorize(bodyFormData, config);
118
120
  } catch (ex) {
119
- if (ex.response.status === 302) {
121
+ var _ex$response, _ex$response$headers, _ex$response$headers$;
122
+
123
+ if (((_ex$response = ex.response) === null || _ex$response === void 0 ? void 0 : _ex$response.status) === 302 && ((_ex$response$headers = ex.response.headers) === null || _ex$response$headers === void 0 ? void 0 : (_ex$response$headers$ = _ex$response$headers.location) === null || _ex$response$headers$ === void 0 ? void 0 : _ex$response$headers$.indexOf('code=')) > -1) {
120
124
  adminClientId = forgeopsClientId;
121
125
  printMessage('ForgeOps deployment ', 'info', false);
122
126
  deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;
@@ -195,16 +199,21 @@ async function authenticate() {
195
199
  printMessage('+++ likely cause, bad credentials!!! +++', 'error');
196
200
  return null;
197
201
  } catch (e) {
198
- if (e.response && e.response.status === 401) {
202
+ var _e$response2;
203
+
204
+ if (((_e$response2 = e.response) === null || _e$response2 === void 0 ? void 0 : _e$response2.status) === 401) {
199
205
  printMessage(`error authenticating - ${e.message}`, 'error');
200
206
  printMessage('+++ likely cause, bad credentials +++', 'error');
201
207
  }
202
208
 
203
- if (e.message && e.message === 'self signed certificate') {
209
+ if (e.message === 'self signed certificate') {
204
210
  printMessage(`error authenticating - ${e.message}`, 'error');
205
211
  printMessage('+++ use -k, --insecure option to allow +++', 'error');
206
212
  } else {
213
+ var _e$response3;
214
+
207
215
  printMessage(`error authenticating - ${e.message}`, 'error');
216
+ printMessage((_e$response3 = e.response) === null || _e$response3 === void 0 ? void 0 : _e$response3.data, 'error');
208
217
  }
209
218
 
210
219
  return null;
@@ -320,6 +329,8 @@ export async function getTokens(save = false) {
320
329
  storage.session.setTenant(conn.tenant);
321
330
  storage.session.setUsername(conn.username);
322
331
  storage.session.setPassword(conn.password);
332
+ storage.session.setAuthenticationService(conn.authenticationService);
333
+ storage.session.setAuthenticationHeaderOverrides(conn.authenticationHeaderOverrides);
323
334
  } else {
324
335
  return false;
325
336
  }
@@ -123,7 +123,9 @@ export async function getConnectionProfileByHost(host) {
123
123
  username: profile.username ? profile.username : null,
124
124
  password: profile.encodedPassword ? await dataProtection.decrypt(profile.encodedPassword) : null,
125
125
  key: profile.logApiKey ? profile.logApiKey : null,
126
- secret: profile.logApiSecret ? profile.logApiSecret : null
126
+ secret: profile.logApiSecret ? profile.logApiSecret : null,
127
+ authenticationService: profile.authenticationService ? profile.authenticationService : null,
128
+ authenticationHeaderOverrides: profile.authenticationHeaderOverrides ? profile.authenticationHeaderOverrides : {}
127
129
  };
128
130
  } catch (e) {
129
131
  printMessage(`Can not read saved connection info, please specify credentials on command line: ${e}`, 'error');
@@ -162,10 +164,21 @@ export async function saveConnectionProfile() {
162
164
  }
163
165
 
164
166
  if (storage.session.getUsername()) existingData['username'] = storage.session.getUsername();
165
- if (storage.session.getPassword()) existingData['encodedPassword'] = await dataProtection.encrypt(storage.session.getPassword()); // Buffer.from(storage.session.getPassword()).toString('base64');
166
-
167
+ if (storage.session.getPassword()) existingData['encodedPassword'] = await dataProtection.encrypt(storage.session.getPassword());
167
168
  if (storage.session.getLogApiKey()) existingData['logApiKey'] = storage.session.getLogApiKey();
168
- if (storage.session.getLogApiSecret()) existingData['logApiSecret'] = storage.session.getLogApiSecret();
169
+ if (storage.session.getLogApiSecret()) existingData['logApiSecret'] = storage.session.getLogApiSecret(); // advanced settings
170
+
171
+ if (storage.session.getAuthenticationService()) {
172
+ existingData['authenticationService'] = storage.session.getAuthenticationService();
173
+ printMessage('Advanced setting: Authentication Service: ' + storage.session.getAuthenticationService(), 'info');
174
+ }
175
+
176
+ if (storage.session.getAuthenticationHeaderOverrides()) {
177
+ existingData['authenticationHeaderOverrides'] = storage.session.getAuthenticationHeaderOverrides();
178
+ printMessage('Advanced setting: Authentication Header Overrides: ', 'info');
179
+ printMessage(storage.session.getAuthenticationHeaderOverrides(), 'info');
180
+ }
181
+
169
182
  connectionsData[storage.session.getTenant()] = existingData;
170
183
  fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));
171
184
  }
@@ -216,7 +229,9 @@ export async function describeConnectionProfile(host, showSecrets) {
216
229
  username: 'Username',
217
230
  password: 'Password',
218
231
  key: 'Log API Key',
219
- secret: 'Log API Secret'
232
+ secret: 'Log API Secret',
233
+ authenticationService: 'Authentication Service',
234
+ authenticationHeaderOverrides: 'Authentication Header Overrides'
220
235
  };
221
236
  const table = createObjectTable(profile, keyMap);
222
237
  printMessage(table.toString(), 'data');
@@ -5,7 +5,9 @@ import { fileURLToPath } from 'url';
5
5
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
6
 
7
7
  const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8'));
8
- const _sessionStorage = {};
8
+ const _sessionStorage = {
9
+ authenticationHeaderOverrides: {}
10
+ };
9
11
  export default {
10
12
  session: {
11
13
  setItem: (key, value) => _sessionStorage[key] = value,
@@ -26,6 +28,10 @@ export default {
26
28
  getCookieName: () => _sessionStorage['cookieName'],
27
29
  setCookieValue: value => _sessionStorage['cookieValue'] = value,
28
30
  getCookieValue: () => _sessionStorage['cookieValue'],
31
+ setAuthenticationService: value => _sessionStorage['authenticationService'] = value,
32
+ getAuthenticationService: () => _sessionStorage['authenticationService'],
33
+ setAuthenticationHeaderOverrides: value => _sessionStorage['authenticationHeaderOverrides'] = value,
34
+ getAuthenticationHeaderOverrides: () => _sessionStorage['authenticationHeaderOverrides'],
29
35
  setBearerToken: value => _sessionStorage['bearerToken'] = value,
30
36
  getBearerToken: () => _sessionStorage['bearerToken'],
31
37
  setLogApiKey: value => _sessionStorage['logApiKey'] = value,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rockcarver/frodo-lib",
3
- "version": "0.12.3",
3
+ "version": "0.12.4",
4
4
  "type": "commonjs",
5
5
  "main": "./cjs/index.js",
6
6
  "module": "./esm/index.mjs",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/AuthenticateApi.ts"],"names":[],"mappings":"AAaA,wBAAgB,WAAW,CAAC,KAAK,KAAA,UAUhC;AAED,wBAAsB,IAAI,CAAC,IAAI,KAAK,EAAE,MAAM,KAAK,oDAOhD","file":"AuthenticateApi.d.ts","sourcesContent":["import util from 'util';\nimport { generateAmApi } from './BaseApi';\nimport storage from '../storage/SessionStorage';\n\nconst authenticateUrlTemplate = '%s/json%s/authenticate';\n\nconst apiVersion = 'resource=2.0, protocol=1.0';\nconst getApiConfig = () => ({\n apiVersion,\n});\n\nconst realmPathTemplate = '/realms/%s';\n\nexport function getRealmUrl(realm) {\n let localRealm = realm;\n if (localRealm.startsWith('/') && localRealm.length > 1) {\n localRealm = localRealm.substring(1);\n }\n let realmPath = util.format(realmPathTemplate, 'root');\n if (localRealm !== '/') {\n realmPath += util.format(realmPathTemplate, localRealm);\n }\n return realmPath;\n}\n\nexport async function step(data = {}, config = {}) {\n const urlString = util.format(\n authenticateUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/')\n );\n return generateAmApi(getApiConfig()).post(urlString, data, config);\n}\n"]}
1
+ {"version":3,"sources":["../src/api/AuthenticateApi.ts"],"names":[],"mappings":"AAcA,wBAAgB,WAAW,CAAC,KAAK,KAAA,UAUhC;AAED,wBAAsB,IAAI,CAAC,IAAI,KAAK,EAAE,MAAM,KAAK,oDAchD","file":"AuthenticateApi.d.ts","sourcesContent":["import util from 'util';\nimport { generateAmApi } from './BaseApi';\nimport storage from '../storage/SessionStorage';\n\nconst authenticateUrlTemplate = '%s/json%s/authenticate';\nconst authenticateWithServiceUrlTemplate = `${authenticateUrlTemplate}?authIndexType=service&authIndexValue=%s`;\n\nconst apiVersion = 'resource=2.0, protocol=1.0';\nconst getApiConfig = () => ({\n apiVersion,\n});\n\nconst realmPathTemplate = '/realms/%s';\n\nexport function getRealmUrl(realm) {\n let localRealm = realm;\n if (localRealm.startsWith('/') && localRealm.length > 1) {\n localRealm = localRealm.substring(1);\n }\n let realmPath = util.format(realmPathTemplate, 'root');\n if (localRealm !== '/') {\n realmPath += util.format(realmPathTemplate, localRealm);\n }\n return realmPath;\n}\n\nexport async function step(data = {}, config = {}) {\n const urlString = storage.session.getAuthenticationService()\n ? util.format(\n authenticateWithServiceUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/'),\n storage.session.getAuthenticationService()\n )\n : util.format(\n authenticateUrlTemplate,\n storage.session.getTenant(),\n getRealmUrl('/')\n );\n return generateAmApi(getApiConfig()).post(urlString, data, config);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/BaseApi.ts"],"names":[],"mappings":"AAqFA;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCA2B3D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCA0B/D;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,eAAe,KAAK,iCAuBlD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,eAAe,KAAK,iCAwBtD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,eAAe,KAAK,iCAmBlD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCAyB5D","file":"BaseApi.d.ts","sourcesContent":["import Agent from 'agentkeepalive';\nimport axios, { AxiosProxyConfig } from 'axios';\nimport axiosRetry from 'axios-retry';\nimport HttpsProxyAgent from 'https-proxy-agent';\nimport url from 'url';\nimport fs from 'fs';\nimport storage from '../storage/SessionStorage';\nimport { getTenantURL } from './utils/ApiUtils';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\naxiosRetry(axios, {\n retries: 3,\n shouldResetTimeout: true,\n retryCondition: (_error) => true, // retry no matter what\n});\n\n// all agents\nconst timeout = 30000;\n\n// agentkeepalive\nconst maxSockets = 100;\nconst maxFreeSockets = 10;\nconst freeSocketTimeout = 30000;\n\nconst userAgent = `${pkg.name}/${pkg.version}`;\nlet httpAgent, httpsAgent;\n\nfunction getHttpAgent() {\n if (httpAgent) return httpAgent;\n httpAgent = new Agent({\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpAgent;\n}\n\n/**\n * Helper method to create properly configured httpsAgent\n * @returns {any} appropriate httpsAgent\n */\nfunction getHttpsAgent() {\n if (httpsAgent) return httpsAgent;\n const options = {\n rejectUnauthorized: !storage.session.getAllowInsecureConnection(),\n };\n const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;\n if (httpsProxy) {\n // https://github.com/axios/axios/issues/3459\n console.error(`Using proxy ${httpsProxy}`['yellow']);\n const parsed = url.parse(httpsProxy);\n options['host'] = parsed.hostname;\n options['port'] = parsed.port;\n options['protocol'] = parsed.protocol;\n options.rejectUnauthorized = !storage.session.getAllowInsecureConnection();\n httpsAgent = HttpsProxyAgent(options);\n return httpsAgent;\n }\n httpsAgent = new Agent.HttpsAgent({\n ...options,\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpsAgent;\n}\n\n/**\n * Get Proxy config\n * @returns {AxiosProxyConfig | false} axios proxy config or false\n */\nfunction getProxy(): AxiosProxyConfig | false {\n if (process.env.HTTPS_PROXY || process.env.https_proxy) return false;\n return null;\n}\n\n/**\n * Generates an AM Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateAmApi(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.getCookieName()}=${storage.session.getCookieValue()}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json`,\n timeout,\n ...requestOverride,\n headers,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an OAuth2 Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateOauth2Api(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.raw['cookieName']}=${storage.session.raw['cookieValue']}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json${resource.path}`,\n timeout,\n ...requestOverride,\n headers,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an IDM Axios API instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateIdmApi(requestOverride = {}) {\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers: {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n },\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a LogKeys API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogKeysApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a Log API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'X-API-Key': storage.session.getLogApiKey(),\n 'X-API-Secret': storage.session.getLogApiSecret(),\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an ESV Axios API instance for Environment Secrets and Variables\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateESVApi(resource, requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n"]}
1
+ {"version":3,"sources":["../src/api/BaseApi.ts"],"names":[],"mappings":"AAqFA;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCA8B3D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCA6B/D;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,eAAe,KAAK,iCAuBlD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,eAAe,KAAK,iCAwBtD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,eAAe,KAAK,iCAmBlD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,QAAQ,KAAA,EAAE,eAAe,KAAK,iCAyB5D","file":"BaseApi.d.ts","sourcesContent":["import Agent from 'agentkeepalive';\nimport axios, { AxiosProxyConfig } from 'axios';\nimport axiosRetry from 'axios-retry';\nimport HttpsProxyAgent from 'https-proxy-agent';\nimport url from 'url';\nimport fs from 'fs';\nimport storage from '../storage/SessionStorage';\nimport { getTenantURL } from './utils/ApiUtils';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\naxiosRetry(axios, {\n retries: 3,\n shouldResetTimeout: true,\n retryCondition: (_error) => true, // retry no matter what\n});\n\n// all agents\nconst timeout = 30000;\n\n// agentkeepalive\nconst maxSockets = 100;\nconst maxFreeSockets = 10;\nconst freeSocketTimeout = 30000;\n\nconst userAgent = `${pkg.name}/${pkg.version}`;\nlet httpAgent, httpsAgent;\n\nfunction getHttpAgent() {\n if (httpAgent) return httpAgent;\n httpAgent = new Agent({\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpAgent;\n}\n\n/**\n * Helper method to create properly configured httpsAgent\n * @returns {any} appropriate httpsAgent\n */\nfunction getHttpsAgent() {\n if (httpsAgent) return httpsAgent;\n const options = {\n rejectUnauthorized: !storage.session.getAllowInsecureConnection(),\n };\n const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;\n if (httpsProxy) {\n // https://github.com/axios/axios/issues/3459\n console.error(`Using proxy ${httpsProxy}`['yellow']);\n const parsed = url.parse(httpsProxy);\n options['host'] = parsed.hostname;\n options['port'] = parsed.port;\n options['protocol'] = parsed.protocol;\n options.rejectUnauthorized = !storage.session.getAllowInsecureConnection();\n httpsAgent = HttpsProxyAgent(options);\n return httpsAgent;\n }\n httpsAgent = new Agent.HttpsAgent({\n ...options,\n maxSockets,\n maxFreeSockets,\n timeout,\n freeSocketTimeout,\n });\n return httpsAgent;\n}\n\n/**\n * Get Proxy config\n * @returns {AxiosProxyConfig | false} axios proxy config or false\n */\nfunction getProxy(): AxiosProxyConfig | false {\n if (process.env.HTTPS_PROXY || process.env.https_proxy) return false;\n return null;\n}\n\n/**\n * Generates an AM Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateAmApi(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.getCookieName()}=${storage.session.getCookieValue()}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json`,\n timeout,\n ...requestOverride,\n headers: {\n ...headers,\n ...storage.session.getAuthenticationHeaderOverrides(),\n },\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an OAuth2 Axios API instance\n * @param {object} resource Takes an object takes a resource object. example:\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either\n * add on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateOauth2Api(resource, requestOverride = {}) {\n let headers = {\n 'User-Agent': userAgent,\n 'Accept-API-Version': resource.apiVersion,\n Cookie: `${storage.session.raw['cookieName']}=${storage.session.raw['cookieValue']}`,\n };\n if (requestOverride['headers']) {\n headers = {\n ...headers,\n ...requestOverride['headers'],\n };\n }\n\n const requestDetails = {\n baseURL: `${storage.session.getTenant()}/json${resource.path}`,\n timeout,\n ...requestOverride,\n headers: {\n ...headers,\n ...storage.session.getAuthenticationHeaderOverrides(),\n },\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an IDM Axios API instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateIdmApi(requestOverride = {}) {\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers: {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n },\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a LogKeys API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogKeysApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates a Log API Axios instance\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateLogApi(requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'X-API-Key': storage.session.getLogApiKey(),\n 'X-API-Secret': storage.session.getLogApiSecret(),\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n\n/**\n * Generates an ESV Axios API instance for Environment Secrets and Variables\n * @param {object} requestOverride Takes an object of AXIOS parameters that can be used to either add\n * on extra information or override default properties https://github.com/axios/axios#request-config\n *\n * @returns {AxiosInstance}\n */\nexport function generateESVApi(resource, requestOverride = {}) {\n const headers = {\n 'User-Agent': userAgent,\n 'Content-Type': 'application/json',\n 'Accept-API-Version': resource.apiVersion,\n };\n const requestDetails = {\n baseURL: getTenantURL(storage.session.getTenant()),\n timeout,\n headers,\n ...requestOverride,\n httpAgent: getHttpAgent(),\n httpsAgent: getHttpsAgent(),\n proxy: getProxy(),\n };\n\n if (storage.session.getBearerToken()) {\n requestDetails.headers[\n 'Authorization'\n ] = `Bearer ${storage.session.getBearerToken()}`;\n }\n\n const request = axios.create(requestDetails);\n\n return request;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/AuthenticateOps.ts"],"names":[],"mappings":"AAySA;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,IAAI,UAAQ,oBAoC3C","file":"AuthenticateOps.d.ts","sourcesContent":["import url from 'url';\nimport { createHash, randomBytes } from 'crypto';\nimport readlineSync from 'readline-sync';\nimport { encodeBase64Url } from '../api/utils/Base64';\nimport storage from '../storage/SessionStorage';\nimport * as global from '../storage/StaticStorage';\nimport { printMessage } from './utils/Console';\nimport { getServerInfo, getServerVersionInfo } from '../api/ServerInfoApi';\nimport { step } from '../api/AuthenticateApi';\nimport { accessToken, authorize } from '../api/OAuth2OIDCApi';\nimport {\n getConnectionProfile,\n saveConnectionProfile,\n} from './ConnectionProfileOps';\n\nconst adminClientPassword = 'doesnotmatter';\nconst redirectUrlTemplate = '/platform/appAuthHelperRedirect.html';\n\nconst idmAdminScope = 'fr:idm:* openid';\n\nlet adminClientId = 'idmAdminClient';\n\n/**\n * Helper function to get cookie name\n * @returns {String} cookie name\n */\nasync function getCookieName() {\n try {\n return (await getServerInfo()).data.cookieName;\n } catch (error) {\n printMessage(`Error getting cookie name: ${error}`, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to determine if this is a setup mfa prompt in the ID Cloud tenant admin login journey\n * @param {Object} payload response from the previous authentication journey step\n * @returns {Object} an object indicating if 2fa is required and the original payload\n */\nfunction checkAndHandle2FA(payload) {\n // let skippable = false;\n if ('callbacks' in payload) {\n for (const element of payload.callbacks) {\n if (element.type === 'HiddenValueCallback') {\n if (element.input[0].value.includes('skip')) {\n // skippable = true;\n element.input[0].value = 'Skip';\n return {\n need2fa: true,\n payload,\n };\n }\n }\n if (element.type === 'NameCallback') {\n if (element.output[0].value.includes('code')) {\n // skippable = false;\n printMessage('2FA is enabled and required for this user...');\n const code = readlineSync.question(`${element.output[0].value}: `);\n element.input[0].value = code;\n return {\n need2fa: true,\n payload,\n };\n }\n }\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n}\n\n/**\n * Helper function to set the default realm by deployment type\n * @param {String} deploymentType deployment type\n */\nfunction determineDefaultRealm(deploymentType) {\n if (storage.session.getRealm() === global.DEFAULT_REALM_KEY) {\n storage.session.setRealm(global.DEPLOYMENT_TYPE_REALM_MAP[deploymentType]);\n }\n}\n\n/**\n * Helper function to determine the deployment type\n * @returns {String} deployment type\n */\nasync function determineDeploymentType() {\n const fidcClientId = 'idmAdminClient';\n const forgeopsClientId = 'idm-admin-ui';\n\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n\n const config = {\n maxRedirects: 0,\n };\n let bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${fidcClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n\n let deploymentType = global.CLASSIC_DEPLOYMENT_TYPE_KEY;\n try {\n await authorize(bodyFormData, config);\n } catch (e) {\n if (e.response && e.response.status === 302) {\n printMessage('ForgeRock Identity Cloud ', 'info', false);\n deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;\n } else {\n try {\n bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${forgeopsClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n await authorize(bodyFormData, config);\n } catch (ex) {\n if (ex.response.status === 302) {\n adminClientId = forgeopsClientId;\n printMessage('ForgeOps deployment ', 'info', false);\n deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;\n } else {\n printMessage('Classic deployment ', 'info', false);\n }\n }\n }\n printMessage('detected.');\n }\n determineDefaultRealm(deploymentType);\n return deploymentType;\n}\n\n/**\n * Helper function to extract the semantic version string from a version info object\n * @param {Object} versionInfo version info object\n * @returns {String} semantic version\n */\nasync function getSemanticVersion(versionInfo) {\n if ('version' in versionInfo) {\n const versionString = versionInfo.version;\n const rx = /([\\d]\\.[\\d]\\.[\\d](\\.[\\d])*)/g;\n const version = versionString.match(rx);\n return version[0];\n }\n throw new Error('Cannot extract semantic version from version info object.');\n}\n\n/**\n * Helper function to authenticate and obtain and store session cookie\n * @returns {String} empty string or null\n */\nasync function authenticate() {\n storage.session.setCookieName(await getCookieName());\n try {\n const config = {\n headers: {\n 'X-OpenAM-Username': storage.session.getUsername(),\n 'X-OpenAM-Password': storage.session.getPassword(),\n },\n };\n const response1 = (await step({}, config)).data;\n const skip2FA = checkAndHandle2FA(response1);\n let response2 = {};\n if (skip2FA.need2fa) {\n response2 = (await step(skip2FA.payload)).data;\n } else {\n response2 = skip2FA.payload;\n }\n if ('tokenId' in response2) {\n storage.session.setCookieValue(response2['tokenId']);\n if (!storage.session.getDeploymentType()) {\n storage.session.setDeploymentType(await determineDeploymentType());\n } else {\n determineDefaultRealm(storage.session.getDeploymentType());\n }\n const versionInfo = (await getServerVersionInfo()).data;\n printMessage(`Connected to ${versionInfo.fullVersion}`);\n const version = await getSemanticVersion(versionInfo);\n storage.session.setAmVersion(version);\n return '';\n }\n printMessage(`error authenticating`, 'error');\n printMessage('+++ likely cause, bad credentials!!! +++', 'error');\n return null;\n } catch (e) {\n if (e.response && e.response.status === 401) {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ likely cause, bad credentials +++', 'error');\n }\n if (e.message && e.message === 'self signed certificate') {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ use -k, --insecure option to allow +++', 'error');\n } else {\n printMessage(`error authenticating - ${e.message}`, 'error');\n }\n return null;\n }\n}\n\n/**\n * Helper function to obtain an oauth2 authorization code\n * @param {String} redirectURL oauth2 redirect uri\n * @param {String} codeChallenge PKCE code challenge\n * @param {String} codeChallengeMethod PKCE code challenge method\n * @returns {String} oauth2 authorization code or null\n */\nasync function getAuthCode(redirectURL, codeChallenge, codeChallengeMethod) {\n try {\n const bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${adminClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${codeChallenge}&code_challenge_method=${codeChallengeMethod}`;\n const config = {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n };\n const response = await authorize(bodyFormData, config);\n if (response.status < 200 || response.status > 399) {\n printMessage('error getting auth code', 'error');\n printMessage(\n 'likely cause: mismatched parameters with OAuth client config',\n 'error'\n );\n return null;\n }\n const redirectLocationURL = response.request.res.responseUrl;\n const queryObject = url.parse(redirectLocationURL, true).query;\n if ('code' in queryObject) {\n return queryObject.code;\n }\n printMessage('auth code not found', 'error');\n return null;\n } catch (error) {\n printMessage(`error getting auth code - ${error.message}`, 'error');\n printMessage(error.response.data, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to obtain oauth2 access token\n * @returns {String} empty string or null\n */\nasync function getAccessToken() {\n try {\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n const authCode = await getAuthCode(redirectURL, challenge, challengeMethod);\n if (authCode == null) {\n printMessage('error getting auth code', 'error');\n return null;\n }\n let response = null;\n if (\n storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY\n ) {\n const config = {\n auth: {\n username: adminClientId,\n password: adminClientPassword,\n },\n };\n const bodyFormData = `redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData, config);\n } else {\n const bodyFormData = `client_id=${adminClientId}&redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData);\n }\n if (response.status < 200 || response.status > 399) {\n printMessage(`access token call returned ${response.status}`, 'error');\n return null;\n }\n if ('access_token' in response.data) {\n storage.session.setBearerToken(response.data.access_token);\n return '';\n }\n printMessage(\"can't get access token\", 'error');\n return null;\n } catch (e) {\n printMessage('error getting access token - ', 'error');\n return null;\n }\n}\n\n/**\n * Get tokens\n * @param {boolean} save true to save a connection profile upon successful authentication, false otherwise\n * @returns {boolean} true if tokens were successfully obtained, false otherwise\n */\nexport async function getTokens(save = false) {\n let credsFromParameters = true;\n // if username/password on cli are empty, try to read from connections.json\n if (\n storage.session.getUsername() == null &&\n storage.session.getPassword() == null\n ) {\n credsFromParameters = false;\n const conn = await getConnectionProfile();\n if (conn) {\n storage.session.setTenant(conn.tenant);\n storage.session.setUsername(conn.username);\n storage.session.setPassword(conn.password);\n } else {\n return false;\n }\n }\n await authenticate();\n if (\n storage.session.getCookieValue() &&\n !storage.session.getBearerToken() &&\n (storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY ||\n storage.session.getDeploymentType() ===\n global.FORGEOPS_DEPLOYMENT_TYPE_KEY)\n ) {\n await getAccessToken();\n }\n if (save && storage.session.getCookieValue() && credsFromParameters) {\n // valid cookie, which means valid username/password combo. Save it in connections.json\n saveConnectionProfile();\n return true;\n }\n if (!storage.session.getCookieValue()) {\n return false;\n }\n return true;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/AuthenticateOps.ts"],"names":[],"mappings":"AAgTA;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,IAAI,UAAQ,oBAwC3C","file":"AuthenticateOps.d.ts","sourcesContent":["import url from 'url';\nimport { createHash, randomBytes } from 'crypto';\nimport readlineSync from 'readline-sync';\nimport { encodeBase64Url } from '../api/utils/Base64';\nimport storage from '../storage/SessionStorage';\nimport * as global from '../storage/StaticStorage';\nimport { printMessage } from './utils/Console';\nimport { getServerInfo, getServerVersionInfo } from '../api/ServerInfoApi';\nimport { step } from '../api/AuthenticateApi';\nimport { accessToken, authorize } from '../api/OAuth2OIDCApi';\nimport {\n getConnectionProfile,\n saveConnectionProfile,\n} from './ConnectionProfileOps';\n\nconst adminClientPassword = 'doesnotmatter';\nconst redirectUrlTemplate = '/platform/appAuthHelperRedirect.html';\n\nconst idmAdminScope = 'fr:idm:* openid';\n\nlet adminClientId = 'idmAdminClient';\n\n/**\n * Helper function to get cookie name\n * @returns {String} cookie name\n */\nasync function getCookieName() {\n try {\n return (await getServerInfo()).data.cookieName;\n } catch (error) {\n printMessage(`Error getting cookie name: ${error}`, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to determine if this is a setup mfa prompt in the ID Cloud tenant admin login journey\n * @param {Object} payload response from the previous authentication journey step\n * @returns {Object} an object indicating if 2fa is required and the original payload\n */\nfunction checkAndHandle2FA(payload) {\n // let skippable = false;\n if ('callbacks' in payload) {\n for (const element of payload.callbacks) {\n if (element.type === 'HiddenValueCallback') {\n if (element.input[0].value.includes('skip')) {\n // skippable = true;\n element.input[0].value = 'Skip';\n return {\n need2fa: true,\n payload,\n };\n }\n }\n if (element.type === 'NameCallback') {\n if (element.output[0].value.includes('code')) {\n // skippable = false;\n printMessage('2FA is enabled and required for this user...');\n const code = readlineSync.question(`${element.output[0].value}: `);\n element.input[0].value = code;\n return {\n need2fa: true,\n payload,\n };\n }\n }\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n }\n // console.info(\"NO2FA\");\n return {\n need2fa: false,\n payload,\n };\n}\n\n/**\n * Helper function to set the default realm by deployment type\n * @param {String} deploymentType deployment type\n */\nfunction determineDefaultRealm(deploymentType) {\n if (storage.session.getRealm() === global.DEFAULT_REALM_KEY) {\n storage.session.setRealm(global.DEPLOYMENT_TYPE_REALM_MAP[deploymentType]);\n }\n}\n\n/**\n * Helper function to determine the deployment type\n * @returns {String} deployment type\n */\nasync function determineDeploymentType() {\n const fidcClientId = 'idmAdminClient';\n const forgeopsClientId = 'idm-admin-ui';\n\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n\n const config = {\n maxRedirects: 0,\n };\n let bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${fidcClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n\n let deploymentType = global.CLASSIC_DEPLOYMENT_TYPE_KEY;\n try {\n await authorize(bodyFormData, config);\n } catch (e) {\n if (\n e.response?.status === 302 &&\n e.response.headers?.location?.indexOf('code=') > -1\n ) {\n printMessage('ForgeRock Identity Cloud ', 'info', false);\n deploymentType = global.CLOUD_DEPLOYMENT_TYPE_KEY;\n } else {\n try {\n bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${forgeopsClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${challenge}&code_challenge_method=${challengeMethod}`;\n await authorize(bodyFormData, config);\n } catch (ex) {\n if (\n ex.response?.status === 302 &&\n ex.response.headers?.location?.indexOf('code=') > -1\n ) {\n adminClientId = forgeopsClientId;\n printMessage('ForgeOps deployment ', 'info', false);\n deploymentType = global.FORGEOPS_DEPLOYMENT_TYPE_KEY;\n } else {\n printMessage('Classic deployment ', 'info', false);\n }\n }\n }\n printMessage('detected.');\n }\n determineDefaultRealm(deploymentType);\n return deploymentType;\n}\n\n/**\n * Helper function to extract the semantic version string from a version info object\n * @param {Object} versionInfo version info object\n * @returns {String} semantic version\n */\nasync function getSemanticVersion(versionInfo) {\n if ('version' in versionInfo) {\n const versionString = versionInfo.version;\n const rx = /([\\d]\\.[\\d]\\.[\\d](\\.[\\d])*)/g;\n const version = versionString.match(rx);\n return version[0];\n }\n throw new Error('Cannot extract semantic version from version info object.');\n}\n\n/**\n * Helper function to authenticate and obtain and store session cookie\n * @returns {String} empty string or null\n */\nasync function authenticate() {\n storage.session.setCookieName(await getCookieName());\n try {\n const config = {\n headers: {\n 'X-OpenAM-Username': storage.session.getUsername(),\n 'X-OpenAM-Password': storage.session.getPassword(),\n },\n };\n const response1 = (await step({}, config)).data;\n const skip2FA = checkAndHandle2FA(response1);\n let response2 = {};\n if (skip2FA.need2fa) {\n response2 = (await step(skip2FA.payload)).data;\n } else {\n response2 = skip2FA.payload;\n }\n if ('tokenId' in response2) {\n storage.session.setCookieValue(response2['tokenId']);\n if (!storage.session.getDeploymentType()) {\n storage.session.setDeploymentType(await determineDeploymentType());\n } else {\n determineDefaultRealm(storage.session.getDeploymentType());\n }\n const versionInfo = (await getServerVersionInfo()).data;\n printMessage(`Connected to ${versionInfo.fullVersion}`);\n const version = await getSemanticVersion(versionInfo);\n storage.session.setAmVersion(version);\n return '';\n }\n printMessage(`error authenticating`, 'error');\n printMessage('+++ likely cause, bad credentials!!! +++', 'error');\n return null;\n } catch (e) {\n if (e.response?.status === 401) {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ likely cause, bad credentials +++', 'error');\n }\n if (e.message === 'self signed certificate') {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage('+++ use -k, --insecure option to allow +++', 'error');\n } else {\n printMessage(`error authenticating - ${e.message}`, 'error');\n printMessage(e.response?.data, 'error');\n }\n return null;\n }\n}\n\n/**\n * Helper function to obtain an oauth2 authorization code\n * @param {String} redirectURL oauth2 redirect uri\n * @param {String} codeChallenge PKCE code challenge\n * @param {String} codeChallengeMethod PKCE code challenge method\n * @returns {String} oauth2 authorization code or null\n */\nasync function getAuthCode(redirectURL, codeChallenge, codeChallengeMethod) {\n try {\n const bodyFormData = `redirect_uri=${redirectURL}&scope=${idmAdminScope}&response_type=code&client_id=${adminClientId}&csrf=${storage.session.getCookieValue()}&decision=allow&code_challenge=${codeChallenge}&code_challenge_method=${codeChallengeMethod}`;\n const config = {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n };\n const response = await authorize(bodyFormData, config);\n if (response.status < 200 || response.status > 399) {\n printMessage('error getting auth code', 'error');\n printMessage(\n 'likely cause: mismatched parameters with OAuth client config',\n 'error'\n );\n return null;\n }\n const redirectLocationURL = response.request.res.responseUrl;\n const queryObject = url.parse(redirectLocationURL, true).query;\n if ('code' in queryObject) {\n return queryObject.code;\n }\n printMessage('auth code not found', 'error');\n return null;\n } catch (error) {\n printMessage(`error getting auth code - ${error.message}`, 'error');\n printMessage(error.response.data, 'error');\n return null;\n }\n}\n\n/**\n * Helper function to obtain oauth2 access token\n * @returns {String} empty string or null\n */\nasync function getAccessToken() {\n try {\n const verifier = encodeBase64Url(randomBytes(32));\n const challenge = encodeBase64Url(\n createHash('sha256').update(verifier).digest()\n );\n const challengeMethod = 'S256';\n const redirectURL = url.resolve(\n storage.session.getTenant(),\n redirectUrlTemplate\n );\n const authCode = await getAuthCode(redirectURL, challenge, challengeMethod);\n if (authCode == null) {\n printMessage('error getting auth code', 'error');\n return null;\n }\n let response = null;\n if (\n storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY\n ) {\n const config = {\n auth: {\n username: adminClientId,\n password: adminClientPassword,\n },\n };\n const bodyFormData = `redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData, config);\n } else {\n const bodyFormData = `client_id=${adminClientId}&redirect_uri=${redirectURL}&grant_type=authorization_code&code=${authCode}&code_verifier=${verifier}`;\n response = await accessToken(bodyFormData);\n }\n if (response.status < 200 || response.status > 399) {\n printMessage(`access token call returned ${response.status}`, 'error');\n return null;\n }\n if ('access_token' in response.data) {\n storage.session.setBearerToken(response.data.access_token);\n return '';\n }\n printMessage(\"can't get access token\", 'error');\n return null;\n } catch (e) {\n printMessage('error getting access token - ', 'error');\n return null;\n }\n}\n\n/**\n * Get tokens\n * @param {boolean} save true to save a connection profile upon successful authentication, false otherwise\n * @returns {boolean} true if tokens were successfully obtained, false otherwise\n */\nexport async function getTokens(save = false) {\n let credsFromParameters = true;\n // if username/password on cli are empty, try to read from connections.json\n if (\n storage.session.getUsername() == null &&\n storage.session.getPassword() == null\n ) {\n credsFromParameters = false;\n const conn = await getConnectionProfile();\n if (conn) {\n storage.session.setTenant(conn.tenant);\n storage.session.setUsername(conn.username);\n storage.session.setPassword(conn.password);\n storage.session.setAuthenticationService(conn.authenticationService);\n storage.session.setAuthenticationHeaderOverrides(\n conn.authenticationHeaderOverrides\n );\n } else {\n return false;\n }\n }\n await authenticate();\n if (\n storage.session.getCookieValue() &&\n !storage.session.getBearerToken() &&\n (storage.session.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY ||\n storage.session.getDeploymentType() ===\n global.FORGEOPS_DEPLOYMENT_TYPE_KEY)\n ) {\n await getAccessToken();\n }\n if (save && storage.session.getCookieValue() && credsFromParameters) {\n // valid cookie, which means valid username/password combo. Save it in connections.json\n saveConnectionProfile();\n return true;\n }\n if (!storage.session.getCookieValue()) {\n return false;\n }\n return true;\n}\n"]}
@@ -23,6 +23,8 @@ export declare function getConnectionProfileByHost(host: any): Promise<{
23
23
  password: any;
24
24
  key: any;
25
25
  secret: any;
26
+ authenticationService: any;
27
+ authenticationHeaderOverrides: any;
26
28
  }>;
27
29
  /**
28
30
  * Get connection profile
@@ -34,6 +36,8 @@ export declare function getConnectionProfile(): Promise<{
34
36
  password: any;
35
37
  key: any;
36
38
  secret: any;
39
+ authenticationService: any;
40
+ authenticationHeaderOverrides: any;
37
41
  }>;
38
42
  /**
39
43
  * Save connection profile
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/ConnectionProfileOps.ts"],"names":[],"mappings":"AAcA;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAMlD;AAmBD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,UAAQ,QA2BlD;AAED;;GAEG;AACH,wBAAgB,sBAAsB,SAkCrC;AAED;;;;GAIG;AACH,wBAAsB,0BAA0B,CAAC,IAAI,KAAA;;;;;;GA4BpD;AAED;;;GAGG;AACH,wBAAsB,oBAAoB;;;;;;GAEzC;AAED;;GAEG;AACH,wBAAsB,qBAAqB,kBAkC1C;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,KAAA,QAwB3C;AAED,wBAAsB,yBAAyB,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA,iBAuBhE","file":"ConnectionProfileOps.d.ts","sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport storage from '../storage/SessionStorage';\nimport DataProtection from './utils/DataProtection';\nimport { createObjectTable, createTable, printMessage } from './utils/Console';\nimport { FRODO_CONNECTION_PROFILES_PATH_KEY } from '../storage/StaticStorage';\n\nconst dataProtection = new DataProtection();\n\nconst fileOptions = {\n indentation: 4,\n};\n\n/**\n * Get connection profiles file name\n * @returns {String} connection profiles file name\n */\nexport function getConnectionProfilesPath(): string {\n return (\n storage.session.getConnectionProfilesPath() ||\n process.env[FRODO_CONNECTION_PROFILES_PATH_KEY] ||\n `${os.homedir()}/.frodo/.frodorc`\n );\n}\n\n/**\n * Find connection profile\n * @param {Object} connectionProfiles connection profile object\n * @param {String} host tenant host url or unique substring\n * @returns {Object} connection profile object or null\n */\nfunction findConnectionProfile(connectionProfiles, host) {\n for (const tenant in connectionProfiles) {\n if (tenant.includes(host)) {\n const profile = connectionProfiles[tenant];\n profile.tenant = tenant;\n return profile;\n }\n }\n return null;\n}\n\n/**\n * List connection profiles\n * @param {boolean} long Long list format with details\n */\nexport function listConnectionProfiles(long = false) {\n const filename = getConnectionProfilesPath();\n try {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n if (long) {\n const table = createTable(['Host', 'Username', 'Log API Key']);\n Object.keys(connectionsData).forEach((c) => {\n table.push([\n c,\n connectionsData[c].username,\n connectionsData[c].logApiKey,\n ]);\n });\n printMessage(table.toString(), 'data');\n } else {\n Object.keys(connectionsData).forEach((c) => {\n printMessage(`${c}`, 'data');\n });\n }\n printMessage(\n 'Any unique substring of a saved host can be used as the value for host parameter in all commands',\n 'info'\n );\n } catch (e) {\n printMessage(`No connections found in ${filename} (${e.message})`, 'error');\n }\n}\n\n/**\n * Initialize connection profiles\n */\nexport function initConnectionProfiles() {\n // create connections.json file if it doesn't exist\n const filename = getConnectionProfilesPath();\n const folderName = path.dirname(filename);\n if (!fs.existsSync(folderName)) {\n fs.mkdirSync(folderName, { recursive: true });\n if (!fs.existsSync(filename)) {\n fs.writeFileSync(\n filename,\n JSON.stringify({}, null, fileOptions.indentation)\n );\n }\n }\n // encrypt the password from clear text to aes-256-GCM\n else {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n let convert = false;\n Object.keys(connectionsData).forEach(async (conn) => {\n if (connectionsData[conn].password) {\n convert = true;\n connectionsData[conn].encodedPassword = await dataProtection.encrypt(\n connectionsData[conn].password\n ); // Buffer.from(connectionsData[conn].password).toString('base64');\n delete connectionsData[conn].password;\n }\n });\n if (convert) {\n fs.writeFileSync(\n filename,\n JSON.stringify(connectionsData, null, fileOptions.indentation)\n );\n }\n }\n}\n\n/**\n * Get connection profile by host\n * @param {String} host host tenant host url or unique substring\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfileByHost(host) {\n try {\n const filename = getConnectionProfilesPath();\n const connectionsData = JSON.parse(fs.readFileSync(filename, 'utf8'));\n const profile = findConnectionProfile(connectionsData, host);\n if (!profile) {\n printMessage(\n `Profile for ${host} not found. Please specify credentials on command line`,\n 'error'\n );\n return null;\n }\n return {\n tenant: profile.tenant,\n username: profile.username ? profile.username : null,\n password: profile.encodedPassword\n ? await dataProtection.decrypt(profile.encodedPassword)\n : null,\n key: profile.logApiKey ? profile.logApiKey : null,\n secret: profile.logApiSecret ? profile.logApiSecret : null,\n };\n } catch (e) {\n printMessage(\n `Can not read saved connection info, please specify credentials on command line: ${e}`,\n 'error'\n );\n return null;\n }\n}\n\n/**\n * Get connection profile\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfile() {\n return getConnectionProfileByHost(storage.session.getTenant());\n}\n\n/**\n * Save connection profile\n */\nexport async function saveConnectionProfile() {\n const filename = getConnectionProfilesPath();\n printMessage(`Saving creds in ${filename}...`);\n let connectionsData = {};\n let existingData = {};\n try {\n fs.statSync(filename);\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n if (connectionsData[storage.session.getTenant()]) {\n existingData = connectionsData[storage.session.getTenant()];\n printMessage(\n `Updating connection profile ${storage.session.getTenant()}`\n );\n } else\n printMessage(`Adding connection profile ${storage.session.getTenant()}`);\n } catch (e) {\n printMessage(\n `Creating connection profiles file ${filename} with ${storage.session.getTenant()}`\n );\n }\n if (storage.session.getUsername())\n existingData['username'] = storage.session.getUsername();\n if (storage.session.getPassword())\n existingData['encodedPassword'] = await dataProtection.encrypt(\n storage.session.getPassword()\n ); // Buffer.from(storage.session.getPassword()).toString('base64');\n if (storage.session.getLogApiKey())\n existingData['logApiKey'] = storage.session.getLogApiKey();\n if (storage.session.getLogApiSecret())\n existingData['logApiSecret'] = storage.session.getLogApiSecret();\n connectionsData[storage.session.getTenant()] = existingData;\n\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n}\n\n/**\n * Delete connection profile\n * @param {String} host host tenant host url or unique substring\n */\nexport function deleteConnectionProfile(host) {\n const filename = getConnectionProfilesPath();\n let connectionsData = {};\n fs.stat(filename, (err) => {\n if (err == null) {\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n const profile = findConnectionProfile(connectionsData, host);\n if (profile) {\n printMessage(`Deleting connection profile ${profile.tenant}`);\n delete connectionsData[profile.tenant];\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n } else if (err.code === 'ENOENT') {\n printMessage(`Connection profile file ${filename} not found`);\n } else {\n printMessage(\n `Error in deleting connection profile: ${err.code}`,\n 'error'\n );\n }\n });\n}\n\nexport async function describeConnectionProfile(host, showSecrets) {\n const profile = await getConnectionProfileByHost(host);\n if (profile) {\n if (!showSecrets) {\n delete profile.password;\n delete profile.secret;\n }\n if (!profile.key) {\n delete profile.key;\n delete profile.secret;\n }\n const keyMap = {\n tenant: 'Host',\n username: 'Username',\n password: 'Password',\n key: 'Log API Key',\n secret: 'Log API Secret',\n };\n const table = createObjectTable(profile, keyMap);\n printMessage(table.toString(), 'data');\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/ConnectionProfileOps.ts"],"names":[],"mappings":"AAcA;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAMlD;AAmBD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,UAAQ,QA2BlD;AAED;;GAEG;AACH,wBAAgB,sBAAsB,SAkCrC;AAED;;;;GAIG;AACH,wBAAsB,0BAA0B,CAAC,IAAI,KAAA;;;;;;;;GAkCpD;AAED;;;GAGG;AACH,wBAAsB,oBAAoB;;;;;;;;GAEzC;AAED;;GAEG;AACH,wBAAsB,qBAAqB,kBAoD1C;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,KAAA,QAwB3C;AAED,wBAAsB,yBAAyB,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA,iBAyBhE","file":"ConnectionProfileOps.d.ts","sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport storage from '../storage/SessionStorage';\nimport DataProtection from './utils/DataProtection';\nimport { createObjectTable, createTable, printMessage } from './utils/Console';\nimport { FRODO_CONNECTION_PROFILES_PATH_KEY } from '../storage/StaticStorage';\n\nconst dataProtection = new DataProtection();\n\nconst fileOptions = {\n indentation: 4,\n};\n\n/**\n * Get connection profiles file name\n * @returns {String} connection profiles file name\n */\nexport function getConnectionProfilesPath(): string {\n return (\n storage.session.getConnectionProfilesPath() ||\n process.env[FRODO_CONNECTION_PROFILES_PATH_KEY] ||\n `${os.homedir()}/.frodo/.frodorc`\n );\n}\n\n/**\n * Find connection profile\n * @param {Object} connectionProfiles connection profile object\n * @param {String} host tenant host url or unique substring\n * @returns {Object} connection profile object or null\n */\nfunction findConnectionProfile(connectionProfiles, host) {\n for (const tenant in connectionProfiles) {\n if (tenant.includes(host)) {\n const profile = connectionProfiles[tenant];\n profile.tenant = tenant;\n return profile;\n }\n }\n return null;\n}\n\n/**\n * List connection profiles\n * @param {boolean} long Long list format with details\n */\nexport function listConnectionProfiles(long = false) {\n const filename = getConnectionProfilesPath();\n try {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n if (long) {\n const table = createTable(['Host', 'Username', 'Log API Key']);\n Object.keys(connectionsData).forEach((c) => {\n table.push([\n c,\n connectionsData[c].username,\n connectionsData[c].logApiKey,\n ]);\n });\n printMessage(table.toString(), 'data');\n } else {\n Object.keys(connectionsData).forEach((c) => {\n printMessage(`${c}`, 'data');\n });\n }\n printMessage(\n 'Any unique substring of a saved host can be used as the value for host parameter in all commands',\n 'info'\n );\n } catch (e) {\n printMessage(`No connections found in ${filename} (${e.message})`, 'error');\n }\n}\n\n/**\n * Initialize connection profiles\n */\nexport function initConnectionProfiles() {\n // create connections.json file if it doesn't exist\n const filename = getConnectionProfilesPath();\n const folderName = path.dirname(filename);\n if (!fs.existsSync(folderName)) {\n fs.mkdirSync(folderName, { recursive: true });\n if (!fs.existsSync(filename)) {\n fs.writeFileSync(\n filename,\n JSON.stringify({}, null, fileOptions.indentation)\n );\n }\n }\n // encrypt the password from clear text to aes-256-GCM\n else {\n const data = fs.readFileSync(filename, 'utf8');\n const connectionsData = JSON.parse(data);\n let convert = false;\n Object.keys(connectionsData).forEach(async (conn) => {\n if (connectionsData[conn].password) {\n convert = true;\n connectionsData[conn].encodedPassword = await dataProtection.encrypt(\n connectionsData[conn].password\n ); // Buffer.from(connectionsData[conn].password).toString('base64');\n delete connectionsData[conn].password;\n }\n });\n if (convert) {\n fs.writeFileSync(\n filename,\n JSON.stringify(connectionsData, null, fileOptions.indentation)\n );\n }\n }\n}\n\n/**\n * Get connection profile by host\n * @param {String} host host tenant host url or unique substring\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfileByHost(host) {\n try {\n const filename = getConnectionProfilesPath();\n const connectionsData = JSON.parse(fs.readFileSync(filename, 'utf8'));\n const profile = findConnectionProfile(connectionsData, host);\n if (!profile) {\n printMessage(\n `Profile for ${host} not found. Please specify credentials on command line`,\n 'error'\n );\n return null;\n }\n return {\n tenant: profile.tenant,\n username: profile.username ? profile.username : null,\n password: profile.encodedPassword\n ? await dataProtection.decrypt(profile.encodedPassword)\n : null,\n key: profile.logApiKey ? profile.logApiKey : null,\n secret: profile.logApiSecret ? profile.logApiSecret : null,\n authenticationService: profile.authenticationService\n ? profile.authenticationService\n : null,\n authenticationHeaderOverrides: profile.authenticationHeaderOverrides\n ? profile.authenticationHeaderOverrides\n : {},\n };\n } catch (e) {\n printMessage(\n `Can not read saved connection info, please specify credentials on command line: ${e}`,\n 'error'\n );\n return null;\n }\n}\n\n/**\n * Get connection profile\n * @returns {Object} connection profile or null\n */\nexport async function getConnectionProfile() {\n return getConnectionProfileByHost(storage.session.getTenant());\n}\n\n/**\n * Save connection profile\n */\nexport async function saveConnectionProfile() {\n const filename = getConnectionProfilesPath();\n printMessage(`Saving creds in ${filename}...`);\n let connectionsData = {};\n let existingData = {};\n try {\n fs.statSync(filename);\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n if (connectionsData[storage.session.getTenant()]) {\n existingData = connectionsData[storage.session.getTenant()];\n printMessage(\n `Updating connection profile ${storage.session.getTenant()}`\n );\n } else\n printMessage(`Adding connection profile ${storage.session.getTenant()}`);\n } catch (e) {\n printMessage(\n `Creating connection profiles file ${filename} with ${storage.session.getTenant()}`\n );\n }\n if (storage.session.getUsername())\n existingData['username'] = storage.session.getUsername();\n if (storage.session.getPassword())\n existingData['encodedPassword'] = await dataProtection.encrypt(\n storage.session.getPassword()\n );\n if (storage.session.getLogApiKey())\n existingData['logApiKey'] = storage.session.getLogApiKey();\n if (storage.session.getLogApiSecret())\n existingData['logApiSecret'] = storage.session.getLogApiSecret();\n\n // advanced settings\n if (storage.session.getAuthenticationService()) {\n existingData['authenticationService'] =\n storage.session.getAuthenticationService();\n printMessage(\n 'Advanced setting: Authentication Service: ' +\n storage.session.getAuthenticationService(),\n 'info'\n );\n }\n if (storage.session.getAuthenticationHeaderOverrides()) {\n existingData['authenticationHeaderOverrides'] =\n storage.session.getAuthenticationHeaderOverrides();\n printMessage('Advanced setting: Authentication Header Overrides: ', 'info');\n printMessage(storage.session.getAuthenticationHeaderOverrides(), 'info');\n }\n\n connectionsData[storage.session.getTenant()] = existingData;\n\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n}\n\n/**\n * Delete connection profile\n * @param {String} host host tenant host url or unique substring\n */\nexport function deleteConnectionProfile(host) {\n const filename = getConnectionProfilesPath();\n let connectionsData = {};\n fs.stat(filename, (err) => {\n if (err == null) {\n const data = fs.readFileSync(filename, 'utf8');\n connectionsData = JSON.parse(data);\n const profile = findConnectionProfile(connectionsData, host);\n if (profile) {\n printMessage(`Deleting connection profile ${profile.tenant}`);\n delete connectionsData[profile.tenant];\n fs.writeFileSync(filename, JSON.stringify(connectionsData, null, 2));\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n } else if (err.code === 'ENOENT') {\n printMessage(`Connection profile file ${filename} not found`);\n } else {\n printMessage(\n `Error in deleting connection profile: ${err.code}`,\n 'error'\n );\n }\n });\n}\n\nexport async function describeConnectionProfile(host, showSecrets) {\n const profile = await getConnectionProfileByHost(host);\n if (profile) {\n if (!showSecrets) {\n delete profile.password;\n delete profile.secret;\n }\n if (!profile.key) {\n delete profile.key;\n delete profile.secret;\n }\n const keyMap = {\n tenant: 'Host',\n username: 'Username',\n password: 'Password',\n key: 'Log API Key',\n secret: 'Log API Secret',\n authenticationService: 'Authentication Service',\n authenticationHeaderOverrides: 'Authentication Header Overrides',\n };\n const table = createObjectTable(profile, keyMap);\n printMessage(table.toString(), 'data');\n } else {\n printMessage(`No connection profile ${host} found`);\n }\n}\n"]}
@@ -3,7 +3,9 @@ declare const _default: {
3
3
  setItem: (key: any, value: any) => any;
4
4
  getItem: (key: any) => any;
5
5
  removeItem: (key: any) => boolean;
6
- raw: {};
6
+ raw: {
7
+ authenticationHeaderOverrides: {};
8
+ };
7
9
  setUsername: (value: any) => any;
8
10
  getUsername: () => any;
9
11
  setPassword: (value: any) => any;
@@ -18,6 +20,10 @@ declare const _default: {
18
20
  getCookieName: () => any;
19
21
  setCookieValue: (value: any) => any;
20
22
  getCookieValue: () => any;
23
+ setAuthenticationService: (value: any) => any;
24
+ getAuthenticationService: () => any;
25
+ setAuthenticationHeaderOverrides: (value: any) => any;
26
+ getAuthenticationHeaderOverrides: () => {};
21
27
  setBearerToken: (value: any) => any;
22
28
  getBearerToken: () => any;
23
29
  setLogApiKey: (value: any) => any;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage/SessionStorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,wBAoDE","file":"SessionStorage.d.ts","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\nconst _sessionStorage = {};\n\nexport default {\n session: {\n setItem: (key, value) => (_sessionStorage[key] = value),\n getItem: (key) => _sessionStorage[key],\n removeItem: (key) => delete _sessionStorage[key],\n raw: _sessionStorage,\n setUsername: (value) => (_sessionStorage['username'] = value),\n getUsername: () => _sessionStorage['username'],\n setPassword: (value) => (_sessionStorage['password'] = value),\n getPassword: () => _sessionStorage['password'],\n setTenant: (value) => (_sessionStorage['tenant'] = value),\n getTenant: () => _sessionStorage['tenant'],\n setDeploymentType: (value) => (_sessionStorage['deploymentType'] = value),\n getDeploymentType: () => _sessionStorage['deploymentType'],\n setRealm: (value) => (_sessionStorage['realm'] = value),\n getRealm: () => _sessionStorage['realm'],\n setCookieName: (value) => (_sessionStorage['cookieName'] = value),\n getCookieName: () => _sessionStorage['cookieName'],\n setCookieValue: (value) => (_sessionStorage['cookieValue'] = value),\n getCookieValue: () => _sessionStorage['cookieValue'],\n setBearerToken: (value) => (_sessionStorage['bearerToken'] = value),\n getBearerToken: () => _sessionStorage['bearerToken'],\n setLogApiKey: (value) => (_sessionStorage['logApiKey'] = value),\n getLogApiKey: () => _sessionStorage['logApiKey'],\n setLogApiSecret: (value) => (_sessionStorage['logApiSecret'] = value),\n getLogApiSecret: () => _sessionStorage['logApiSecret'],\n setAmVersion: (value) => (_sessionStorage['amVersion'] = value),\n getAmVersion: () => _sessionStorage['amVersion'],\n setFrodoVersion: (value) => (_sessionStorage['frodoVersion'] = value),\n getFrodoVersion: () =>\n _sessionStorage['frodoVersion'] || `v${pkg.version} [${process.version}]`,\n setAllowInsecureConnection: (value) =>\n (_sessionStorage['insecure'] = value),\n getAllowInsecureConnection: () => _sessionStorage['insecure'],\n setConnectionProfilesPath: (value) =>\n (_sessionStorage['connectionProfilesPath'] = value),\n getConnectionProfilesPath: () => _sessionStorage['connectionProfilesPath'],\n setMasterKeyPath: (value) => (_sessionStorage['masterKeyPath'] = value),\n getMasterKeyPath: () => _sessionStorage['masterKeyPath'],\n setPrintHandler: (printHandler) =>\n (_sessionStorage['printHandler'] = printHandler),\n getPrintHandler: () => _sessionStorage['printHandler'],\n setCreateProgressHandler: (handler) =>\n (_sessionStorage['createProgressHandler'] = handler),\n getCreateProgressHandler: () => _sessionStorage['createProgressHandler'],\n setUpdateProgressHandler: (handler) =>\n (_sessionStorage['updateProgressHandler'] = handler),\n getUpdateProgressHandler: () => _sessionStorage['updateProgressHandler'],\n setStopProgressHandler: (handler) =>\n (_sessionStorage['stopProgressHandler'] = handler),\n getStopProgressHandler: () => _sessionStorage['stopProgressHandler'],\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/storage/SessionStorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,wBA2DE","file":"SessionStorage.d.ts","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst pkg = JSON.parse(\n fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')\n);\n\nconst _sessionStorage = {\n authenticationHeaderOverrides: {},\n};\n\nexport default {\n session: {\n setItem: (key, value) => (_sessionStorage[key] = value),\n getItem: (key) => _sessionStorage[key],\n removeItem: (key) => delete _sessionStorage[key],\n raw: _sessionStorage,\n setUsername: (value) => (_sessionStorage['username'] = value),\n getUsername: () => _sessionStorage['username'],\n setPassword: (value) => (_sessionStorage['password'] = value),\n getPassword: () => _sessionStorage['password'],\n setTenant: (value) => (_sessionStorage['tenant'] = value),\n getTenant: () => _sessionStorage['tenant'],\n setDeploymentType: (value) => (_sessionStorage['deploymentType'] = value),\n getDeploymentType: () => _sessionStorage['deploymentType'],\n setRealm: (value) => (_sessionStorage['realm'] = value),\n getRealm: () => _sessionStorage['realm'],\n setCookieName: (value) => (_sessionStorage['cookieName'] = value),\n getCookieName: () => _sessionStorage['cookieName'],\n setCookieValue: (value) => (_sessionStorage['cookieValue'] = value),\n getCookieValue: () => _sessionStorage['cookieValue'],\n setAuthenticationService: (value) =>\n (_sessionStorage['authenticationService'] = value),\n getAuthenticationService: () => _sessionStorage['authenticationService'],\n setAuthenticationHeaderOverrides: (value) =>\n (_sessionStorage['authenticationHeaderOverrides'] = value),\n getAuthenticationHeaderOverrides: () =>\n _sessionStorage['authenticationHeaderOverrides'],\n setBearerToken: (value) => (_sessionStorage['bearerToken'] = value),\n getBearerToken: () => _sessionStorage['bearerToken'],\n setLogApiKey: (value) => (_sessionStorage['logApiKey'] = value),\n getLogApiKey: () => _sessionStorage['logApiKey'],\n setLogApiSecret: (value) => (_sessionStorage['logApiSecret'] = value),\n getLogApiSecret: () => _sessionStorage['logApiSecret'],\n setAmVersion: (value) => (_sessionStorage['amVersion'] = value),\n getAmVersion: () => _sessionStorage['amVersion'],\n setFrodoVersion: (value) => (_sessionStorage['frodoVersion'] = value),\n getFrodoVersion: () =>\n _sessionStorage['frodoVersion'] || `v${pkg.version} [${process.version}]`,\n setAllowInsecureConnection: (value) =>\n (_sessionStorage['insecure'] = value),\n getAllowInsecureConnection: () => _sessionStorage['insecure'],\n setConnectionProfilesPath: (value) =>\n (_sessionStorage['connectionProfilesPath'] = value),\n getConnectionProfilesPath: () => _sessionStorage['connectionProfilesPath'],\n setMasterKeyPath: (value) => (_sessionStorage['masterKeyPath'] = value),\n getMasterKeyPath: () => _sessionStorage['masterKeyPath'],\n setPrintHandler: (printHandler) =>\n (_sessionStorage['printHandler'] = printHandler),\n getPrintHandler: () => _sessionStorage['printHandler'],\n setCreateProgressHandler: (handler) =>\n (_sessionStorage['createProgressHandler'] = handler),\n getCreateProgressHandler: () => _sessionStorage['createProgressHandler'],\n setUpdateProgressHandler: (handler) =>\n (_sessionStorage['updateProgressHandler'] = handler),\n getUpdateProgressHandler: () => _sessionStorage['updateProgressHandler'],\n setStopProgressHandler: (handler) =>\n (_sessionStorage['stopProgressHandler'] = handler),\n getStopProgressHandler: () => _sessionStorage['stopProgressHandler'],\n },\n};\n"]}