UNPKG

aladinnetwork-blockstack

Version:

The Aladin Javascript library for authentication, identity, and storage.

295 lines 9.91 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const url_1 = __importDefault(require("url")); const bitcoinjs_lib_1 = require("bitcoinjs-lib"); const config_1 = require("./config"); const logger_1 = require("./logger"); /** * @ignore */ exports.ALADIN_HANDLER = 'aladin'; /** * Time * @private * @ignore */ function nextYear() { return new Date(new Date().setFullYear(new Date().getFullYear() + 1)); } exports.nextYear = nextYear; /** * Time * @private * @ignore */ function nextMonth() { return new Date(new Date().setMonth(new Date().getMonth() + 1)); } exports.nextMonth = nextMonth; /** * Time * @private * @ignore */ function nextHour() { return new Date(new Date().setHours(new Date().getHours() + 1)); } exports.nextHour = nextHour; /** * Query Strings * @private * @ignore */ function updateQueryStringParameter(uri, key, value) { const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i'); const separator = uri.indexOf('?') !== -1 ? '&' : '?'; if (uri.match(re)) { return uri.replace(re, `$1${key}=${value}$2`); } else { return `${uri}${separator}${key}=${value}`; } } exports.updateQueryStringParameter = updateQueryStringParameter; /** * Versioning * @param {string} v1 - the left half of the version inequality * @param {string} v2 - right half of the version inequality * @returns {bool} iff v1 >= v2 * @private * @ignore */ function isLaterVersion(v1, v2) { if (v1 === undefined) { v1 = '0.0.0'; } if (v2 === undefined) { v2 = '0.0.0'; } const v1tuple = v1.split('.').map(x => parseInt(x, 10)); const v2tuple = v2.split('.').map(x => parseInt(x, 10)); for (let index = 0; index < v2.length; index++) { if (index >= v1.length) { v2tuple.push(0); } if (v1tuple[index] < v2tuple[index]) { return false; } } return true; } exports.isLaterVersion = isLaterVersion; /** * Time * @private * @ignore */ function hexStringToECPair(skHex) { const ecPairOptions = { network: config_1.config.network.layer1, compressed: true }; if (skHex.length === 66) { if (skHex.slice(64) !== '01') { throw new Error('Improperly formatted private-key hex string. 66-length hex usually ' + 'indicates compressed key, but last byte must be == 1'); } return bitcoinjs_lib_1.ECPair.fromPrivateKey(Buffer.from(skHex.slice(0, 64), 'hex'), ecPairOptions); } else if (skHex.length === 64) { ecPairOptions.compressed = false; return bitcoinjs_lib_1.ECPair.fromPrivateKey(Buffer.from(skHex, 'hex'), ecPairOptions); } else { throw new Error('Improperly formatted private-key hex string: length should be 64 or 66.'); } } exports.hexStringToECPair = hexStringToECPair; /** * * @ignore */ function ecPairToHexString(secretKey) { const ecPointHex = secretKey.privateKey.toString('hex'); if (secretKey.compressed) { return `${ecPointHex}01`; } else { return ecPointHex; } } exports.ecPairToHexString = ecPairToHexString; /** * Time * @private * @ignore */ function ecPairToAddress(keyPair) { return bitcoinjs_lib_1.address.toBase58Check(bitcoinjs_lib_1.crypto.hash160(keyPair.publicKey), keyPair.network.pubKeyHash); } exports.ecPairToAddress = ecPairToAddress; /** * UUIDs * @private * @ignore */ function makeUUID4() { let d = new Date().getTime(); if (typeof performance !== 'undefined' && typeof performance.now === 'function') { d += performance.now(); // use high-precision timer if available } return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } exports.makeUUID4 = makeUUID4; /** * Checks if both urls pass the same origin check & are absolute * @param {[type]} uri1 first uri to check * @param {[type]} uri2 second uri to check * @return {Boolean} true if they pass the same origin check * @private * @ignore */ function isSameOriginAbsoluteUrl(uri1, uri2) { const parsedUri1 = url_1.default.parse(uri1); const parsedUri2 = url_1.default.parse(uri2); const port1 = parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80); const port2 = parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80); const match = { scheme: parsedUri1.protocol === parsedUri2.protocol, hostname: parsedUri1.hostname === parsedUri2.hostname, port: port1 === port2, absolute: (uri1.includes('http://') || uri1.includes('https://')) && (uri2.includes('http://') || uri2.includes('https://')) }; return match.scheme && match.hostname && match.port && match.absolute; } exports.isSameOriginAbsoluteUrl = isSameOriginAbsoluteUrl; /** * Returns the global scope `Window`, `WorkerGlobalScope`, or `NodeJS.Global` if available in the * currently executing environment. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self * @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self * @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope * * This could be switched to `globalThis` once it is standardized and widely available. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis */ function getGlobalScope() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } // This function is meant to be called when accessing APIs that are typically only available in // web-browser/DOM environments, but we also want to support situations where running in Node.js // environment, and a polyfill was added to the Node.js `global` object scope without adding the // `window` global object as well. if (typeof global !== 'undefined') { return global; } throw new Error('Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available'); } function getAPIUsageErrorMessage(scopeObject, apiName, usageDesc) { if (usageDesc) { return `Use of '${usageDesc}' requires \`${apiName}\` which is unavailable on the '${scopeObject}' object within the currently executing environment.`; } else { return `\`${apiName}\` is unavailable on the '${scopeObject}' object within the currently executing environment.`; } } /** * Returns an object from the global scope (`Window` or `WorkerGlobalScope`) if it * is available within the currently executing environment. * When executing within the Node.js runtime these APIs are unavailable and will be * `undefined` unless the API is provided via polyfill. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self * @ignore */ function getGlobalObject(name, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) { let globalScope; try { globalScope = getGlobalScope(); if (globalScope) { const obj = globalScope[name]; if (obj) { return obj; } } } catch (error) { logger_1.Logger.error(`Error getting object '${name}' from global scope '${globalScope}': ${error}`); } if (throwIfUnavailable) { const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc); logger_1.Logger.error(errMsg); throw new Error(errMsg); } if (returnEmptyObject) { return {}; } return undefined; } exports.getGlobalObject = getGlobalObject; /** * Returns a specified subset of objects from the global scope (`Window` or `WorkerGlobalScope`) * if they are available within the currently executing environment. * When executing within the Node.js runtime these APIs are unavailable will be `undefined` * unless the API is provided via polyfill. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self * @ignore */ function getGlobalObjects(names, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) { let globalScope; try { globalScope = getGlobalScope(); } catch (error) { logger_1.Logger.error(`Error getting global scope: ${error}`); if (throwIfUnavailable) { const errMsg = getAPIUsageErrorMessage(globalScope, names[0], usageDesc); logger_1.Logger.error(errMsg); throw errMsg; } else if (returnEmptyObject) { globalScope = {}; } } const result = {}; for (let i = 0; i < names.length; i++) { const name = names[i]; try { if (globalScope) { const obj = globalScope[name]; if (obj) { result[name] = obj; } else if (throwIfUnavailable) { const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc); logger_1.Logger.error(errMsg); throw new Error(errMsg); } else if (returnEmptyObject) { result[name] = {}; } } } catch (error) { if (throwIfUnavailable) { const errMsg = getAPIUsageErrorMessage(globalScope, name, usageDesc); logger_1.Logger.error(errMsg); throw new Error(errMsg); } } } return result; } exports.getGlobalObjects = getGlobalObjects; //# sourceMappingURL=utils.js.map