@mindconnect/mindconnect-nodejs
Version:
MindConnect Library for NodeJS (community based)
189 lines • 6.86 kB
JavaScript
;
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 });
// Copyright (C), Siemens AG 2017
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const url_1 = require("url");
const groupby = require("json-groupby");
exports.convertToTdpArray = (data) => {
const tdpArray = [];
const groupedData = groupby(data, ["timestamp"]);
for (const element in groupedData) {
groupedData[element].forEach((x) => {
delete x["timestamp"];
});
const tdp = {
timestamp: element,
values: groupedData[element]
};
tdpArray.push(tdp);
}
return tdpArray;
};
exports.isUrl = (url) => {
try {
new url_1.URL(url);
return true;
}
catch (e) {
return false;
}
};
exports.getPiamUrl = (gateway, tenant) => {
const piamUrl = gateway.replace("gateway", `${tenant}.piam`);
return piamUrl.endsWith("/") ? piamUrl : piamUrl + "/";
};
const normalizePasskey = (passkey) => {
return passkey.length < 32
? passkey + new Array(33 - passkey.length).join("$")
: passkey.substr(0, 32);
};
exports.encrypt = (user, password, passkey, gateway, tenant) => {
const base64encoded = new Buffer(`${user}:${password}`).toString("base64");
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-ctr", Buffer.from(normalizePasskey(passkey)), iv);
let crypted = cipher.update(`Basic ${base64encoded}`, "utf8", "hex");
crypted += cipher.final("hex");
const encryptedAuth = {
auth: crypted.toString(),
iv: iv.toString("base64"),
gateway: gateway,
tenant: tenant
};
console.log(encryptedAuth);
return encryptedAuth;
};
exports.decrypt = (encryptedAuth, passkey) => {
const decipher = crypto.createDecipheriv("aes-256-ctr", normalizePasskey(passkey), Buffer.from(encryptedAuth.iv, "base64"));
let dec = decipher.update(encryptedAuth.auth, "hex", "utf8");
dec += decipher.final("utf8");
return dec;
};
exports.getAgentDir = (path) => {
let result;
if (fs.existsSync(`${path}/.mc/`)) {
result = `${path}/.mc/`;
}
else if (fs.existsSync(`${process.cwd()}/.mc/`)) {
result = `${process.cwd()}/.mc/`;
}
else {
result = exports.getHomeDotMcDir();
}
return result;
};
exports.getHomeDotMcDir = () => {
return `${os.homedir()}/.mc/`;
};
exports.storeAuth = (encryptedAuth) => {
const homeDir = exports.getHomeDotMcDir();
if (!fs.existsSync(homeDir)) {
fs.mkdirSync(homeDir);
}
const pathName = `${exports.getHomeDotMcDir()}auth.json`;
fs.writeFileSync(pathName, JSON.stringify(encryptedAuth));
};
exports.loadAuth = () => {
const pathName = `${exports.getHomeDotMcDir()}auth.json`;
const buffer = fs.readFileSync(pathName);
return JSON.parse(buffer.toString());
};
exports.getConfigProfile = (config) => {
try {
const result = `${config.content.clientCredentialProfile}`;
if (["SHARED_SECRET", "RSA_3072"].indexOf(result) < 0) {
throw new Error("Configuration profile not supported. The library only supports the shared_secret and RSA_3072 config profiles");
}
return result;
}
catch (err) {
throw new Error("Configuration profile not supported. The library only supports the shared_secret and RSA_3072 config profiles");
}
};
exports.checkCertificate = (config, options) => {
const profile = exports.getConfigProfile(config);
if (profile === "RSA_3072") {
if (!options.cert) {
throw new Error("You have to specify --cert parameter for RSA_3072 agents");
}
if (!fs.existsSync(options.cert)) {
throw new Error(`Can't find file ${options.cert}`);
}
}
return profile === "RSA_3072";
};
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
/**
* retry the function n times (while progressively waiting for the success) until success
* the waiting schema is iteration * timeoutInMiliseconds (default is 300ms)
*
* @param {number} n
* @param {Function} func
* @param {number} [timoutinMilliseconds=300]
* @param {Function} [logFunction]
* @returns
*/
exports.retry = (n, func, timoutinMilliseconds = 300, logFunction) => __awaiter(void 0, void 0, void 0, function* () {
let error;
for (let i = 0; i < n; i++) {
try {
if (logFunction) {
logFunction();
}
if (i > 0) {
yield sleep(i * timoutinMilliseconds);
}
return yield func();
}
catch (err) {
error = err;
}
}
throw error;
});
exports.checkAssetId = (agentId) => {
if (!/[a-f0-9]{32}/gi.test(agentId)) {
throw new Error("You have to pass valid 32 char long asset id");
}
};
exports.throwError = (error) => {
throw new Error(error);
};
exports.toQueryString = (qs) => {
return Object.keys(qs || {})
.filter(key => {
return qs[key] !== undefined;
})
.map(key => {
const value = qs[key] instanceof Date ? qs[key].toISOString() : qs[key];
return encodeURIComponent(key) + "=" + encodeURIComponent(value);
})
.join("&");
};
exports.removeUndefined = (obj) => {
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]);
return obj;
};
function checksumFile(hashName, path) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const hash = crypto.createHash(hashName);
const stream = fs.createReadStream(path);
stream.on("error", err => reject(err));
stream.on("data", chunk => hash.update(chunk));
stream.on("end", () => resolve(hash.digest("hex")));
});
});
}
exports.checksumFile = checksumFile;
//# sourceMappingURL=utils.js.map