UNPKG

@cruxpay/js-sdk

Version:

CruxPay Javascript SDK

218 lines (217 loc) 9.79 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; import * as bitcoin from "bitcoinjs-lib"; import * as cloner from "cloner"; import URL from "url-parse"; import { BaseError, ErrorHelper, PackageErrorCode } from "./error"; import { getLogger } from "./logger"; var log = getLogger(__filename); var httpsPrefixRegex = new RegExp("^https://.+$"); /* istanbul ignore next */ var httpJSONRequest = function (options) { log.debug("network_call:", options); var promise = new Promise(function (resolve, reject) { var _a = translateRequestOptionsToFetchOptions(options), url = _a.url, fetchOptions = _a.fetchOptions; if (!httpsPrefixRegex.test(url)) { throw ErrorHelper.getPackageError(null, PackageErrorCode.InsecureNetworkCall); } fetch(url, fetchOptions) .then(function (res) { if (res.status === 404) { reject(ErrorHelper.getPackageError(null, PackageErrorCode.Response404, url)); } else if (res.status === 401) { reject(ErrorHelper.getPackageError(null, PackageErrorCode.Response401, url)); } else { return res.json(); } }) .then(function (json) { return resolve(json); }) .catch(function (err) { return reject(new BaseError(null, err)); }); }); return promise; }; var translateRequestOptionsToFetchOptions = function (options) { var fetchOptions = Object.assign({}, options); delete fetchOptions.baseUrl; delete fetchOptions.url; var url = ""; if (options.baseUrl) { url += options.baseUrl; } if (options.url) { url += options.url; } if (options.qs) { var str = []; for (var p in options.qs) { if (options.qs.hasOwnProperty(p)) { str.push(p + "=" + options.qs[p]); } } url += "?" + str.join("&"); } if (options.body) { fetchOptions.body = JSON.stringify(options.body); } return { url: url, fetchOptions: fetchOptions }; }; var sanitizePrivKey = function (privKey) { if (privKey.length === 66 && privKey.slice(64) === "01") { privKey = privKey.slice(0, 64); } return privKey; }; var sanitizeUrl = function (url) { var parsedUrl = new URL(url); // TODO: sanitize the pathname var restrictedCharacters = "!@#$^&%*()+=[]{}|:<>?,."; if (parsedUrl.pathname.split("").some(function (ch) { return restrictedCharacters.indexOf(ch) !== -1; })) { throw new BaseError(null, "Url path: " + parsedUrl.pathname + " contains invalid characters"); } return "" + parsedUrl.origin + parsedUrl.pathname; }; var trimTrailingSlash = function (value) { return value.replace(/\/$/, ""); }; var getRandomHexString = function (length) { if (length === void 0) { length = 32; } var randomValues = crypto.getRandomValues(new Uint8Array(length)); var result = ""; var i; for (i = 0; i < randomValues.length; i++) { result = result + (randomValues[i].toString(16).toUpperCase()); } return result; }; var cachedFunctionCall = function (storage, cacheKey, ttl, fn, paramArray, skipConditional) { if (ttl === void 0) { ttl = 300; } return __awaiter(void 0, void 0, void 0, function () { var storageCacheKey, cachedValue, cachedExpiry, _a, newValue, skipCache, _b, stringValue; return __generator(this, function (_c) { switch (_c.label) { case 0: if (!storage) { log.info("cacheStorage is missing, making a direct call"); return [2 /*return*/, fn.apply(fn, paramArray)]; } storageCacheKey = "crux_cache_" + cacheKey; return [4 /*yield*/, storage.getItem(storageCacheKey)]; case 1: cachedValue = _c.sent(); _a = Number; return [4 /*yield*/, storage.getItem(storageCacheKey + ":exp")]; case 2: cachedExpiry = _a.apply(void 0, [_c.sent()]); if (cachedValue && cachedExpiry && (new Date(cachedExpiry) > new Date())) { log.debug("using cachedValue from storage for key " + storageCacheKey); try { return [2 /*return*/, JSON.parse(cachedValue)]; } catch (error) { return [2 /*return*/, cachedValue]; } } return [4 /*yield*/, fn.apply(fn, paramArray)]; case 3: newValue = _c.sent(); _b = skipConditional; if (!_b) return [3 /*break*/, 5]; return [4 /*yield*/, skipConditional(newValue)]; case 4: _b = (_c.sent()); _c.label = 5; case 5: skipCache = _b || false; if (!(newValue && !skipCache)) return [3 /*break*/, 8]; stringValue = typeof newValue === "string" ? newValue : JSON.stringify(newValue); return [4 /*yield*/, storage.setItem(storageCacheKey, stringValue)]; case 6: _c.sent(); return [4 /*yield*/, storage.setItem(storageCacheKey + ":exp", ((ttl * 1000) + Date.now()).toString())]; case 7: _c.sent(); _c.label = 8; case 8: return [2 /*return*/, newValue]; } }); }); }; var cloneValue = function (obj) { return cloner.deep.copy(obj); }; var getKeyPairFromPrivKey = function (privKey) { var privateKey; // Convert the WIF format to hex if (privKey.startsWith("L") || privKey.startsWith("K")) { var keyPair = bitcoin.ECPair.fromWIF(privKey); if (keyPair.privateKey) { privateKey = sanitizePrivKey((keyPair.privateKey).toString("hex")); } else { throw new BaseError(null, "Missing private key in generated EC Pair"); } } else { privateKey = sanitizePrivKey(privKey); } // Try with hex encoding first, then with base64 var publicKey; try { publicKey = bitcoin.ECPair.fromPrivateKey(Buffer.from(privateKey, "hex")).publicKey.toString("hex"); } catch (error) { privateKey = sanitizePrivKey(Buffer.from(privKey, "base64").toString("hex")); try { publicKey = bitcoin.ECPair.fromPrivateKey(Buffer.from(privateKey, "hex")).publicKey.toString("hex"); } catch (error) { throw ErrorHelper.getPackageError(error, PackageErrorCode.InvalidPrivateKeyFormat); } } var address = bitcoin.payments.p2pkh({ pubkey: Buffer.from(publicKey, "hex") }).address; if (!address) { throw new BaseError(null, "No address found corresponding this public key"); } return { address: address, privKey: privateKey, pubKey: publicKey, }; }; export { httpJSONRequest, sanitizePrivKey, sanitizeUrl, cachedFunctionCall, getKeyPairFromPrivKey, getRandomHexString, cloneValue, trimTrailingSlash, };