UNPKG

@jovian/type-tools

Version:

TypeTools is a Typescript library for providing extensible tooling runtime validations and type helpers.

338 lines 18.8 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SecureHttpComm = void 0; var axios = __importStar(require("axios")); var uuid_1 = require("uuid"); var secure_channel_1 = require("./secure-channel"); var globals_ix_1 = require("../../src/common/globals.ix"); var http_shim_1 = require("../http/http.shim"); var SecureHttpComm = (function () { function SecureHttpComm(config) { this.errors = []; if (!config.encryptedChannelPath) { config.encryptedChannelPath = http_shim_1.HTTP.SHIM.ROOT_API_NEW_CHANNEL; } if (!config.encryptedApiPath) { config.encryptedApiPath = http_shim_1.HTTP.SHIM.ROOT_API_SECURE_API; } if (!config.defaultTimeout) { config.defaultTimeout = 3600; } if (!config.defaultChannelExpire && config.defaultChannelExpire !== 0) { config.defaultChannelExpire = 3600; } this.config = config; this.pending = this.initialize(); } SecureHttpComm.prototype.pushError = function (e) { this.error = e; this.errors.push(e); }; SecureHttpComm.prototype.getAccessorHeader = function (token, channelPubKeyB64, channelExp) { var headerResult = secure_channel_1.SecureHandshake.getAccessorHeader(this.config.user, channelPubKeyB64, token, this.config.signing); return headerResult === null || headerResult === void 0 ? void 0 : headerResult.data; }; SecureHttpComm.prototype.initialize = function () { var _this = this; var stackTrace = new Error(); var config = this.config; return (0, globals_ix_1.promise)(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var channelInitResult; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, (0, secure_channel_1.initiateSecureChannel)(__assign(__assign({}, config), { initiateContact: function (authHeader) { return __awaiter(_this, void 0, void 0, function () { var res, trust, _a, _b, pubkey, secureChannelResponse, validResult, e_1; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 4, , 5]); return [4, axios.default.get("".concat(config.endpoint).concat(config.encryptedChannelPath), { timeout: 7000, headers: { Accessor: authHeader } })]; case 1: res = _c.sent(); res.request.stackTrace = stackTrace; if (res.status !== 200) { return [2, (0, globals_ix_1.errorResult)(new Error("Not valid stamp"))]; } _a = this; return [4, (0, secure_channel_1.resolveEntry)('trust', config.trust)]; case 2: trust = _a.trustResolved = _c.sent(); _b = this; return [4, (0, secure_channel_1.resolveEntry)('token', config.token)]; case 3: _b.tokenResolved = _c.sent(); pubkey = trust ? Buffer.from(trust.publicKey, 'base64') : null; secureChannelResponse = res.data.result; if (config.trust) { validResult = secure_channel_1.SecureHandshake.verifyStamp(secureChannelResponse, pubkey); if (!validResult || validResult.bad || !validResult.data) { return [2, (0, globals_ix_1.errorResult)(new Error("Not valid stamp"))]; } } return [2, (0, globals_ix_1.ok)(secureChannelResponse)]; case 4: e_1 = _c.sent(); console.error(e_1.message, stackTrace); return [2, (0, globals_ix_1.errorResult)(e_1)]; case 5: return [2]; } }); }); } }))]; case 1: channelInitResult = _a.sent(); if (channelInitResult.ok) { this.channel = channelInitResult.data; this.channelPublicKeyBase64 = this.channel.localKeyPair.publicKey.toString('base64'); } else { console.error(channelInitResult); } this.pending = null; resolve(true); return [2]; } }); }); }); }; SecureHttpComm.prototype.waitForChannel = function () { return __awaiter(this, void 0, void 0, function () { var res; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.pending) return [3, 2]; return [4, this.pending]; case 1: res = _a.sent(); if (!res) { return [2, false]; } _a.label = 2; case 2: return [2, true]; } }); }); }; SecureHttpComm.prototype.get = function (reqObj) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: reqObj.method = 'GET'; return [4, this.request(reqObj)]; case 1: return [2, _a.sent()]; } }); }); }; SecureHttpComm.prototype.post = function (reqObj) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: reqObj.method = 'POST'; return [4, this.request(reqObj)]; case 1: return [2, _a.sent()]; } }); }); }; SecureHttpComm.prototype.request = function (reqObj) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2, (0, globals_ix_1.promise)(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var timeout, encPayload, revealPath, reqPath, authHeader, encHeaders, finalPath, stackTrace_1, attachResolution; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, this.waitForChannel()]; case 1: if (!(_a.sent())) { this.pushError(new Error("Unable to get channel on endpoint ".concat(this.config.endpoint))); return [2, resolve(null)]; } try { timeout = reqObj.timeout ? reqObj.timeout : this.config.defaultTimeout; encPayload = this.channel.createWrappedPayloadBase64({ id: (0, uuid_1.v4)(), path: reqObj.path, headers: reqObj.headers, body: reqObj.body, }); revealPath = (reqObj.revealPath || this.config.revealPath); reqPath = revealPath ? reqObj.path : this.config.encryptedApiPath; if (!reqObj.path) { reqObj.path = '/'; } if (!reqObj.path.startsWith('/')) { reqObj.path = '/' + reqObj.path; } authHeader = secure_channel_1.SecureHandshake.getAccessorHeader(this.config.user, this.channelPublicKeyBase64, this.tokenResolved, this.config.signing); encHeaders = { 'Accessor': authHeader.data, 'Encrypted-Api': 'yes' }; finalPath = "".concat(this.config.endpoint).concat(reqPath); stackTrace_1 = new Error(); attachResolution = function (prom) { return prom.then(function (res) { var result = _this.unwrapEncryptedResponse(res, stackTrace_1); result.statusCode = res.status; resolve(result); }) .catch(function (e) { if (e.response) { var result = (0, globals_ix_1.errorResult)(_this.handleEncryptedError(e.response, e, stackTrace_1)); result.statusCode = e.response.status; reject(_this.handleEncryptedError(e.response, e, stackTrace_1)); } else { console.error(e); reject(e); } }); }; switch (reqObj.method) { case 'GET': { attachResolution(axios.default.get(finalPath, { timeout: timeout, data: encPayload, headers: encHeaders })); break; } case 'PUT': { attachResolution(axios.default.put(finalPath, encPayload, { timeout: timeout, headers: encHeaders })); break; } case 'POST': { attachResolution(axios.default.post(finalPath, encPayload, { timeout: timeout, headers: encHeaders })); break; } case 'PATCH': { attachResolution(axios.default.patch(finalPath, encPayload, { timeout: timeout, headers: encHeaders })); break; } case 'DELETE': { attachResolution(axios.default.delete(finalPath, { timeout: timeout, data: encPayload, headers: encHeaders })); break; } } } catch (e) { this.pushError(e); resolve(null); } return [2]; } }); }); })]; }); }); }; SecureHttpComm.prototype.handleEncryptedError = function (res, e, stackTrace) { var _a; console.log(res, e); if (res === null || res === void 0 ? void 0 : res.request) { res.request.stackTrace = stackTrace; } if ((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.encrypted) { var decrypted = this.unwrapEncryptedResponse(res, stackTrace); return new Error(decrypted.message); } return e; }; SecureHttpComm.prototype.unwrapEncryptedResponse = function (res, stackTrace) { var _a; res.request.stackTrace = stackTrace; if (!((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.encrypted)) { return res.data; } var responseText = this.channel.decryptSecureChannelPayloadIntoString(res.data.payload); if (res.data.headers) { for (var _i = 0, _b = Object.keys(res.data.headers); _i < _b.length; _i++) { var headerName = _b[_i]; res.headers[headerName] = res.data.headers[headerName]; } } if (!responseText) { return null; } switch (res.data.format) { case 'json': return JSON.parse(responseText); default: return null; } }; return SecureHttpComm; }()); exports.SecureHttpComm = SecureHttpComm; //# sourceMappingURL=secure-http-comm.js.map