UNPKG

@mindconnect/mindconnect-nodejs

Version:

NodeJS Library for Siemens Insights Hub Connectivity - TypeScript SDK for Insights Hub and Industrial IoT - Command Line Interface - Insights Hub Development Proxy (Siemens Insights Hub was formerly known as MindSphere)

187 lines 10 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const console_1 = require("console"); const fs = require("fs"); const http = require("http"); const path = require("path"); const url = require("url"); const utils_1 = require("../../api/utils"); const command_utils_1 = require("./command-utils"); const mime = require("mime-types"); const color = (0, command_utils_1.getColor)("magenta"); exports.default = (program) => { program .command("service-credentials") .alias("sc") .option("-m, --mode [config|list|select|add]", "config | list | select | add", "config") .option("-i, --index <index>", "select credentials with specified index") .option("-y, --type <type>", "type (APP | SERVICE)", "APP") .option("-o, --port <port>", "port for config web server", "4994") .option("-u, --user <user>", "credentials: username") .option("-p, --password <password>", "credendials: password") .option("-g, --gateway <gateway>", "region string or full gateway url (e.g. eu1, eu2 or https://gateway.eu1.mindsphere.io)") .option("-t, --tenant <tenant>", "your tenant name") .option("-s, --usertenant <usertenant>", "your user tenant name") .option("-a, --appName <appName>", "your application name (e.g. cli)") .option("-p, --appVersion <appVersion>", "your application version (e.g. 1.0.0)") .option("-k, --passkey <passkey>", "passkey (you will use this in the commands which require service credentials)") .option("-v, --verbose", "verbose output") .description(color("provide login for commands which require technical user credentials *")) .action((options) => { (() => __awaiter(void 0, void 0, void 0, function* () { try { (0, command_utils_1.homeDirLog)(options.verbose, color); (0, command_utils_1.proxyLog)(options.verbose, color); checkRequiredParamaters(options); options.mode === "config" && (yield serve(options.port)); options.mode === "list" && listEntries(options); options.mode === "select" && selectEntry(options); options.mode === "add" && addEntry(options); } catch (err) { (0, command_utils_1.errorLog)(err, options.verbose); } }))(); }) .on("--help", () => { (0, console_1.log)(`\n Example:\n`); (0, console_1.log)(` mdsp service-credentials --mode config \t\t\t start configuration web server on ${color("http://localhost:4994")}`); (0, console_1.log)(` mdsp service-credentials --mode config --port 10000 \t start configuration web server on ${color("http://localhost:10000")}`); (0, console_1.log)(` mdsp service-credentials --mode list \t\t\t list all configured credentials`); (0, console_1.log)(` mdsp service-credentials --mode select --index <index> \t select credentials with index <index> from the list`); (0, console_1.log)(` mdsp service-credentials --mode add --type APP ... \t\t add new APP credentials`); (0, command_utils_1.serviceCredentialLog)(); }); }; function listEntries(options) { const config = (0, utils_1.getFullConfig)(); for (let index = 0; index < config.credentials.length; index++) { const element = config.credentials[index]; const highlight = element.selected ? color : (x) => { return x; }; const selected = element.selected ? color(" -> ") : " "; console.log(`${selected} ${highlight(index)} ${highlight(element.type)}\t ${element.tenant} ${element.gateway} ${element.createdAt} ${element.appName} ${element.appVersion} ${element.usertenant} `); } (0, command_utils_1.verboseLog)(JSON.stringify(config, null, 2), options.verbose); } function serve(configPort) { return __awaiter(this, void 0, void 0, function* () { const server = http.createServer(); const port = configPort || 4994; server.on("request", (req, res) => __awaiter(this, void 0, void 0, function* () { var _a, _b; const uri = url.parse(req.url || ""); // prettier-ignore try { const filePath = uri.path === "/" ? "index.html" : uri.path; const fullName = path.resolve(`${__dirname}/html/sc/${filePath}`); if (((_a = uri.path) === null || _a === void 0 ? void 0 : _a.startsWith("/sc/config")) && req.method === "GET") { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify((0, utils_1.getFullConfig)())); console.log(`${color(new Date().toISOString())} Acquired the CLI settings`); } else if (((_b = uri.path) === null || _b === void 0 ? void 0 : _b.startsWith("/sc/save")) && req.method === "POST") { const data = []; req.on("data", (chunk) => { data.push(chunk); }); req.on("end", () => { const configuration = JSON.parse(data.join()); (0, utils_1.addAndStoreConfiguration)(configuration); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify((0, utils_1.getFullConfig)())); console.log(`${color(new Date().toISOString())} Stored the configuration. Press ${color("CTRL + C")} to exit`); }); } else if (fs.existsSync(fullName)) { // lgtm [js/path-injection] res.writeHead(200, { "Content-Type": mime.lookup(filePath) }); const stream = fs.createReadStream(fullName); // lgtm [js/path-injection] stream.pipe(res); } else { res.writeHead(404); res.end(); } } catch (error) { res.writeHead(500, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: error.message }, null, 2)); } })); server.listen(port); console.log(`navigate to ${color("http://localhost:" + port)} to configure the CLI`); console.log(`press ${color("CTRL + C")} to exit`); }); } function selectEntry(options) { const config = (0, utils_1.getFullConfig)(); const optionIndex = parseInt(options.index); (optionIndex < 0 || optionIndex > config.credentials.length - 1) && (0, utils_1.throwError)(`the index has to be between 0 and ${config.credentials.length - 1}`); for (let index = 0; index < config.credentials.length; index++) { const element = config.credentials[index]; element.selected = index === parseInt(options.index); } (0, utils_1.checkList)(config.credentials); (0, utils_1.storeAuth)(config); listEntries(options); } function addEntry(options) { const config = (0, utils_1.getFullConfig)(); config.credentials.forEach((x) => (x.selected = false)); const newEntry = { user: options.user, password: options.password, passkey: options.passkey, gateway: options.gateway, tenant: `${options.tenant}`, type: options.type, usertenant: `${options.usertenant || ""}`, appName: `${options.appName || ""}`, appVersion: `${options.appVersion || ""}`, createdAt: new Date().toISOString(), selected: true, }; config.credentials.push(newEntry); (0, utils_1.addAndStoreConfiguration)(config); } function checkRequiredParamaters(options) { !(["config", "list", "select", "add"].indexOf(options.mode) >= 0) && (0, utils_1.throwError)(`invalid mode ${options.mode} (must be config, list, select or add)`); options.mode === "select" && !options.index && (0, utils_1.throwError)("you have to specify a configuration index to select"); options.mode === "add" && options.type !== "APP" && options.type !== "SERVICE" && (0, utils_1.throwError)("the credential type has to be either APP or SERVICE"); options.mode === "add" && options.type === "SERVICE" && (!options.user || !options.tenant || !options.passkey || !options.gateway) && (0, utils_1.throwError)("you have to specify user, tenant, gateway and passkey for SERVICE credentials"); options.mode === "add" && options.type === "SERVICE" && (options.usertenant || options.appName || options.appVersion) && (0, utils_1.throwError)("you must not use appName, appVersion or usertenant option with SERVICE credentials"); options.mode === "add" && options.type === "APP" && (!options.user || !options.tenant || !options.passkey || !options.gateway || !options.usertenant || !options.appName || !options.appVersion) && (0, utils_1.throwError)("you have to specify user, tenant, gateway, passkey, usertenant, appName and appVersion for APP credentials"); } //# sourceMappingURL=mc-service-credentials.js.map