Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

scatterjs-core

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

scatterjs-core - npm Package Compare versions

Comparing version 1.0.0 to 1.1.0

434

dist/index.js

@@ -1,280 +0,248 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _PluginRepository = require('./plugins/PluginRepository');
var _PluginRepository2 = _interopRequireDefault(_PluginRepository);
var _SocketService = require('./services/SocketService');
var _SocketService2 = _interopRequireDefault(_SocketService);
var _Plugin = require('./Plugins/Plugin');
var _Plugin2 = _interopRequireDefault(_Plugin);
var _PluginTypes = require('./Plugins/PluginTypes');
var PluginTypes = _interopRequireWildcard(_PluginTypes);
var _Blockchains = require('./models/Blockchains');
var _Network = require('./models/Network');
var _Network2 = _interopRequireDefault(_Network);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
import PluginRepository from './plugins/PluginRepository';
import SocketService from './services/SocketService';
import Plugin from './plugins/Plugin';
import * as PluginTypes from './plugins/PluginTypes';
import { Blockchains } from './models/Blockchains';
import Network from './models/Network';
let origin;
const throwNoAuth = () => {
if (!holder.scatter.isExtension && !_SocketService2.default.isConnected()) throw new Error('Connect and Authenticate first - scatter.connect( pluginName )');
if (!holder.scatter.isExtension && !SocketService.isConnected()) throw new Error('Connect and Authenticate first - scatter.connect( pluginName )');
};
const checkForExtension = (resolve, tries = 0) => {
if (tries > 20) return;
if (holder.scatter.isExtension) return resolve(true);
setTimeout(() => checkForExtension(resolve, tries + 1), 100);
if (tries > 20) return;
if (holder.scatter.isExtension) return resolve(true);
setTimeout(() => checkForExtension(resolve, tries + 1), 100);
};
class Index {
constructor() {
this.isExtension = false;
this.identity = null;
}
constructor() {
this.isExtension = false;
this.identity = null;
}
loadPlugin(plugin) {
const noIdFunc = () => {
if (!this.identity) throw new Error('No Identity');
};
loadPlugin(plugin) {
const noIdFunc = () => {
if (!this.identity) throw new Error('No Identity');
};
if (!plugin.isValid()) throw new Error(`${plugin.name} doesn't seem to be a valid ScatterJS plugin.`);
if (!plugin.isValid()) throw new Error(`${plugin.name} doesn't seem to be a valid ScatterJS plugin.`);
PluginRepository.loadPlugin(plugin);
if (plugin.isSignatureProvider()) this[plugin.name] = plugin.signatureProvider(noIdFunc);
}
_PluginRepository2.default.loadPlugin(plugin);
async isInstalled() {
return new Promise(resolve => {
setTimeout(() => {
resolve(false);
}, 3000);
Promise.race([checkForExtension(resolve), SocketService.ping().then(found => {
console.log('found', found);
if (found) resolve(true);
})]);
});
}
if (plugin.isSignatureProvider()) this[plugin.name] = plugin.signatureProvider(noIdFunc);
}
async connect(pluginName, options) {
return new Promise(resolve => {
if (!pluginName || !pluginName.length) throw new Error("You must specify a name for this connection"); // Setting options defaults
isInstalled() {
return (0, _asyncToGenerator3.default)(function* () {
return new _promise2.default(function (resolve) {
setTimeout(function () {
resolve(false);
}, 3000);
options = Object.assign({
initTimeout: 10000,
linkTimeout: 30000
}, options); // Auto failer
_promise2.default.race([checkForExtension(resolve), _SocketService2.default.ping().then(function (found) {
console.log('found', found);
if (found) resolve(true);
})]);
});
})();
}
setTimeout(() => {
resolve(false);
}, options.initTimeout); // Defaults to scatter extension if exists
connect(pluginName, options) {
var _this = this;
checkForExtension(resolve); // Tries to set up Desktop Connection
return (0, _asyncToGenerator3.default)(function* () {
return new _promise2.default(function (resolve) {
if (!pluginName || !pluginName.length) throw new Error("You must specify a name for this connection");
SocketService.init(pluginName, options.linkTimeout);
SocketService.link().then(async authenticated => {
if (!authenticated) return false;
this.identity = await this.getIdentityFromPermissions();
return resolve(true);
});
});
}
// Setting options defaults
options = (0, _assign2.default)({ initTimeout: 10000, linkTimeout: 30000 }, options);
disconnect() {
return SocketService.disconnect();
}
// Auto failer
setTimeout(function () {
resolve(false);
}, options.initTimeout);
isConnected() {
return SocketService.isConnected();
}
// Defaults to scatter extension if exists
checkForExtension(resolve);
getVersion() {
return SocketService.sendApiRequest({
type: 'getVersion',
payload: {}
});
}
// Tries to set up Desktop Connection
_SocketService2.default.init(pluginName, options.linkTimeout);
_SocketService2.default.link().then((() => {
var _ref = (0, _asyncToGenerator3.default)(function* (authenticated) {
if (!authenticated) return false;
_this.identity = yield _this.getIdentityFromPermissions();
return resolve(true);
});
getIdentity(requiredFields) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'getOrRequestIdentity',
payload: {
fields: requiredFields
}
}).then(id => {
if (id) this.identity = id;
return id;
});
}
return function (_x) {
return _ref.apply(this, arguments);
};
})());
});
})();
}
getIdentityFromPermissions() {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'identityFromPermissions',
payload: {}
}).then(id => {
if (id) this.identity = id;
return id;
});
}
disconnect() {
return _SocketService2.default.disconnect();
}
forgetIdentity() {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'forgetIdentity',
payload: {}
}).then(res => {
this.identity = null;
return res;
});
}
isConnected() {
return _SocketService2.default.isConnected();
}
authenticate() {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'authenticate',
payload: {}
});
}
getVersion() {
return _SocketService2.default.sendApiRequest({
type: 'getVersion',
payload: {}
});
}
getArbitrarySignature(publicKey, data, whatfor = '', isHash = false) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'requestArbitrarySignature',
payload: {
publicKey,
data,
whatfor,
isHash
}
});
}
getIdentity(requiredFields) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'getOrRequestIdentity',
payload: {
fields: requiredFields
}
}).then(id => {
if (id) this.identity = id;
return id;
});
}
getPublicKey(blockchain) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'getPublicKey',
payload: {
blockchain
}
});
}
getIdentityFromPermissions() {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'identityFromPermissions',
payload: {}
}).then(id => {
if (id) this.identity = id;
return id;
});
}
linkAccount(publicKey, account, network) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'linkAccount',
payload: {
publicKey,
account,
network
}
});
}
forgetIdentity() {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'forgetIdentity',
payload: {}
}).then(res => {
this.identity = null;
return res;
});
}
suggestNetwork(network) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'requestAddNetwork',
payload: {
network
}
});
}
authenticate() {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'authenticate',
payload: {}
});
}
requestTransfer(network, to, amount, options = {}) {
const payload = {
network,
to,
amount,
options
};
return SocketService.sendApiRequest({
type: 'requestTransfer',
payload
});
}
getArbitrarySignature(publicKey, data, whatfor = '', isHash = false) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'requestArbitrarySignature',
payload: {
publicKey,
data,
whatfor,
isHash
}
});
}
requestSignature(payload) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'requestSignature',
payload
});
}
getPublicKey(blockchain) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'getPublicKey',
payload: { blockchain }
});
}
createTransaction(blockchain, actions, account, network) {
throwNoAuth();
return SocketService.sendApiRequest({
type: 'createTransaction',
payload: {
blockchain,
actions,
account,
network
}
});
}
linkAccount(publicKey, account, network) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'linkAccount',
payload: { publicKey, account, network }
});
}
suggestNetwork(network) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'requestAddNetwork',
payload: {
network
}
});
}
requestSignature(payload) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'requestSignature',
payload
});
}
createTransaction(blockchain, actions, account, network) {
throwNoAuth();
return _SocketService2.default.sendApiRequest({
type: 'createTransaction',
payload: {
blockchain,
actions,
account,
network
}
});
}
}
class Holder {
constructor(_scatter) {
this.scatter = _scatter;
constructor(_scatter) {
console.log(_scatter);
this.scatter = _scatter;
}
plugins(...plugins) {
if (!this.scatter.isExtension) {
plugins.map(plugin => this.scatter.loadPlugin(plugin));
}
}
plugins(...plugins) {
if (!this.scatter.isExtension) {
plugins.map(plugin => this.scatter.loadPlugin(plugin));
}
}
}
let holder = new Holder(new Index());
if (typeof window !== 'undefined') {
// Catching extension instead of Desktop
if (typeof document !== 'undefined') {
const bindScatterClassic = () => {
holder.scatter = window.scatter;
holder.scatter.isExtension = true;
// Catching extension instead of Desktop
if (typeof document !== 'undefined') {
const bindScatterClassic = () => {
holder.scatter = window.scatter;
holder.scatter.isExtension = true;
holder.scatter.connect = () => new _promise2.default(resolve => resolve(true));
};
holder.scatter.connect = () => new Promise(resolve => resolve(true));
};
if (typeof window.scatter !== 'undefined') bindScatterClassic();else document.addEventListener('scatterLoaded', () => bindScatterClassic());
}
if (typeof window.scatter !== 'undefined') bindScatterClassic();else document.addEventListener('scatterLoaded', () => bindScatterClassic());
}
if (!holder.scatter.isExtension) window.scatter = holder.scatter;
window.ScatterJS = holder;
}
holder.Plugin = _Plugin2.default;
holder.Plugin = Plugin;
holder.PluginTypes = PluginTypes;
holder.Blockchains = _Blockchains.Blockchains;
holder.Network = _Network2.default;
holder.SocketService = _SocketService2.default;
module.exports = holder;
exports.default = holder;
holder.Blockchains = Blockchains;
holder.Network = Network;
holder.SocketService = SocketService;
export { Plugin, PluginTypes, Blockchains, Network, SocketService };
export default holder;

@@ -1,19 +0,8 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BlockchainsArray = exports.Blockchains = undefined;
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const Blockchains = exports.Blockchains = {
EOS: 'eos',
ETH: 'eth'
export const Blockchains = {
EOS: 'eos',
ETH: 'eth'
};
const BlockchainsArray = exports.BlockchainsArray = (0, _keys2.default)(Blockchains).map(key => ({ key, value: Blockchains[key] }));
export const BlockchainsArray = Object.keys(Blockchains).map(key => ({
key,
value: Blockchains[key]
}));

@@ -1,57 +0,42 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ErrorCodes = undefined;
var _ErrorTypes = require("./ErrorTypes");
var ErrorTypes = _interopRequireWildcard(_ErrorTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
const ErrorCodes = exports.ErrorCodes = {
NO_SIGNATURE: 402,
FORBIDDEN: 403,
TIMED_OUT: 408,
LOCKED: 423,
UPGRADE_REQUIRED: 426,
TOO_MANY_REQUESTS: 429
import * as ErrorTypes from './ErrorTypes';
export const ErrorCodes = {
NO_SIGNATURE: 402,
FORBIDDEN: 403,
TIMED_OUT: 408,
LOCKED: 423,
UPGRADE_REQUIRED: 426,
TOO_MANY_REQUESTS: 429
};
export default class Error {
constructor(_type, _message, _code = ErrorCodes.LOCKED) {
this.type = _type;
this.message = _message;
this.code = _code;
this.isError = true;
}
class Error {
static locked() {
return new Error(ErrorTypes.LOCKED, "The user's Scatter is locked. They have been notified and should unlock before continuing.");
}
constructor(_type, _message, _code = ErrorCodes.LOCKED) {
this.type = _type;
this.message = _message;
this.code = _code;
this.isError = true;
}
static maliciousEvent() {
return new Error(ErrorTypes.MALICIOUS, "Malicious event discarded.", ErrorCodes.FORBIDDEN);
}
static locked() {
return new Error(ErrorTypes.LOCKED, "The user's Scatter is locked. They have been notified and should unlock before continuing.");
}
static signatureError(_type, _message) {
return new Error(_type, _message, ErrorCodes.NO_SIGNATURE);
}
static maliciousEvent() {
return new Error(ErrorTypes.MALICIOUS, "Malicious event discarded.", ErrorCodes.FORBIDDEN);
}
static requiresUpgrade() {
return new Error(ErrorTypes.UPGRADE_REQUIRED, "The required version is newer than the User's Scatter", ErrorCodes.UPGRADE_REQUIRED);
}
static signatureError(_type, _message) {
return new Error(_type, _message, ErrorCodes.NO_SIGNATURE);
}
static noNetwork() {
return this.signatureError("no_network", "You must bind a network first");
}
static requiresUpgrade() {
return new Error(ErrorTypes.UPGRADE_REQUIRED, "The required version is newer than the User's Scatter", ErrorCodes.UPGRADE_REQUIRED);
}
static usedKeyProvider() {
return new Error(ErrorTypes.MALICIOUS, "Do not use a `keyProvider` with a Scatter. Use a `signProvider` and return only signatures to this object. A malicious person could retrieve your keys otherwise.", ErrorCodes.NO_SIGNATURE);
}
static noNetwork() {
return this.signatureError("no_network", "You must bind a network first");
}
static usedKeyProvider() {
return new Error(ErrorTypes.MALICIOUS, "Do not use a `keyProvider` with a Scatter. Use a `signProvider` and return only signatures to this object. A malicious person could retrieve your keys otherwise.", ErrorCodes.NO_SIGNATURE);
}
}
exports.default = Error;
}

@@ -1,9 +0,4 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const MALICIOUS = exports.MALICIOUS = 'malicious';
const LOCKED = exports.LOCKED = 'locked';
const PROMPT_CLOSED = exports.PROMPT_CLOSED = 'prompt_closed';
const UPGRADE_REQUIRED = exports.UPGRADE_REQUIRED = 'upgrade_required';
export const MALICIOUS = 'malicious';
export const LOCKED = 'locked';
export const PROMPT_CLOSED = 'prompt_closed';
export const UPGRADE_REQUIRED = 'upgrade_required';

@@ -1,66 +0,53 @@

'use strict';
import { Blockchains } from './Blockchains';
export default class Network {
constructor(_name = '', _protocol = 'https', _host = '', _port = 0, blockchain = Blockchains.EOS, chainId = '') {
this.name = _name;
this.protocol = _protocol;
this.host = _host;
this.port = _port;
this.blockchain = blockchain;
this.chainId = chainId.toString();
}
Object.defineProperty(exports, "__esModule", {
value: true
});
static placeholder() {
return new Network();
}
var _stringify = require('babel-runtime/core-js/json/stringify');
static fromJson(json) {
const p = Object.assign(Network.placeholder(), json);
p.chainId = p.chainId ? p.chainId.toString() : '';
return p;
}
var _stringify2 = _interopRequireDefault(_stringify);
static fromUnique(netString) {
const blockchain = netString.split(':')[0];
if (netString.indexOf(':chain:') > -1) return new Network('', '', '', '', blockchain, netString.replace(`${blockchain}:chain:`, ''));
const splits = netString.replace(`${blockchain}:`, '').split(':');
return new Network('', '', splits[0], parseInt(splits[1] || 80), blockchain);
}
var _assign = require('babel-runtime/core-js/object/assign');
unique() {
return (`${this.blockchain}:` + (this.chainId.length ? `chain:${this.chainId}` : `${this.host}:${this.port}`)).toLowerCase();
}
var _assign2 = _interopRequireDefault(_assign);
hostport() {
return `${this.host}${this.port ? ':' : ''}${this.port}`;
}
var _Blockchains = require('./Blockchains');
fullhost() {
return `${this.protocol}://${this.host}${this.port ? ':' : ''}${this.port}`;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
clone() {
return Network.fromJson(JSON.parse(JSON.stringify(this)));
}
class Network {
constructor(_name = '', _protocol = 'https', _host = '', _port = 0, blockchain = _Blockchains.Blockchains.EOS, chainId = '') {
this.name = _name;
this.protocol = _protocol;
this.host = _host;
this.port = _port;
this.blockchain = blockchain;
this.chainId = chainId.toString();
}
isEmpty() {
return !this.host.length;
}
static placeholder() {
return new Network();
}
isValid() {
return this.protocol.length && this.host.length && this.port || this.chainId.length;
}
static fromJson(json) {
const p = (0, _assign2.default)(Network.placeholder(), json);
p.chainId = p.chainId ? p.chainId.toString() : '';
return p;
}
static fromUnique(netString) {
const blockchain = netString.split(':')[0];
if (netString.indexOf(':chain:') > -1) return new Network('', '', '', '', blockchain, netString.replace(`${blockchain}:chain:`, ''));
const splits = netString.replace(`${blockchain}:`, '').split(':');
return new Network('', '', splits[0], parseInt(splits[1] || 80), blockchain);
}
unique() {
return (`${this.blockchain}:` + (this.chainId.length ? `chain:${this.chainId}` : `${this.host}:${this.port}`)).toLowerCase();
}
hostport() {
return `${this.host}${this.port ? ':' : ''}${this.port}`;
}
fullhost() {
return `${this.protocol}://${this.host}${this.port ? ':' : ''}${this.port}`;
}
clone() {
return Network.fromJson(JSON.parse((0, _stringify2.default)(this)));
}
isEmpty() {
return !this.host.length;
}
isValid() {
return this.protocol.length && this.host.length && this.port || this.chainId.length;
}
}
exports.default = Network;
}

@@ -1,46 +0,24 @@

'use strict';
import * as PluginTypes from "./PluginTypes";
export default class Plugin {
constructor(_name = '', _type = '') {
this.name = _name;
this.type = _type;
}
Object.defineProperty(exports, "__esModule", {
value: true
});
static placeholder() {
return new Plugin();
}
var _keys = require('babel-runtime/core-js/object/keys');
static fromJson(json) {
return Object.assign(Plugin.placeholder(), json);
}
var _keys2 = _interopRequireDefault(_keys);
isSignatureProvider() {
return this.type === PluginTypes.BLOCKCHAIN_SUPPORT;
}
var _assign = require('babel-runtime/core-js/object/assign');
isValid() {
return Object.keys(PluginTypes).map(x => PluginTypes[x]).includes(this.type);
}
var _assign2 = _interopRequireDefault(_assign);
var _PluginTypes = require('./PluginTypes');
var PluginTypes = _interopRequireWildcard(_PluginTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Plugin {
constructor(_name = '', _type = '') {
this.name = _name;
this.type = _type;
}
static placeholder() {
return new Plugin();
}
static fromJson(json) {
return (0, _assign2.default)(Plugin.placeholder(), json);
}
isSignatureProvider() {
return this.type === PluginTypes.BLOCKCHAIN_SUPPORT;
}
isValid() {
return (0, _keys2.default)(PluginTypes).map(x => PluginTypes[x]).includes(this.type);
}
}
exports.default = Plugin;
}

@@ -1,23 +0,2 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _PluginTypes = require('./PluginTypes');
var PluginTypes = _interopRequireWildcard(_PluginTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
import * as PluginTypes from './PluginTypes';
/***

@@ -29,41 +8,29 @@ * Setting up for plugin based generators,

class PluginRepositorySingleton {
constructor() {
this.plugins = [];
}
constructor() {
this.plugins = [];
}
loadPlugin(plugin) {
if (!this.plugin(plugin.name)) this.plugins.push(plugin);
}
loadPlugin(plugin) {
if (!this.plugin(plugin.name)) this.plugins.push(plugin);
}
signatureProviders() {
return this.plugins.filter(plugin => plugin.type === PluginTypes.BLOCKCHAIN_SUPPORT);
}
signatureProviders() {
return this.plugins.filter(plugin => plugin.type === PluginTypes.BLOCKCHAIN_SUPPORT);
}
supportedBlockchains() {
return this.signatureProviders().map(plugin => name);
}
supportedBlockchains() {
return this.signatureProviders().map(plugin => name);
}
plugin(name) {
return this.plugins.find(plugin => plugin.name === name);
}
plugin(name) {
return this.plugins.find(plugin => plugin.name === name);
}
async endorsedNetworks() {
return await Promise.all(this.signatureProviders().map(async plugin => await plugin.getEndorsedNetwork()));
}
endorsedNetworks() {
var _this = this;
return (0, _asyncToGenerator3.default)(function* () {
return yield _promise2.default.all(_this.signatureProviders().map((() => {
var _ref = (0, _asyncToGenerator3.default)(function* (plugin) {
return yield plugin.getEndorsedNetwork();
});
return function (_x) {
return _ref.apply(this, arguments);
};
})()));
})();
}
}
const PluginRepository = new PluginRepositorySingleton();
exports.default = PluginRepository;
export default PluginRepository;

@@ -1,6 +0,1 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const BLOCKCHAIN_SUPPORT = exports.BLOCKCHAIN_SUPPORT = 'blockchain_support';
export const BLOCKCHAIN_SUPPORT = 'blockchain_support';

@@ -1,238 +0,196 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _StorageService = require('./StorageService');
var _StorageService2 = _interopRequireDefault(_StorageService);
var _getRandomValues = require('get-random-values');
var _getRandomValues2 = _interopRequireDefault(_getRandomValues);
var _createHash = require('create-hash');
var _createHash2 = _interopRequireDefault(_createHash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
import StorageService from './StorageService';
import getRandomValues from 'get-random-values';
import createHash from 'create-hash';
const host = '127.0.0.1:50005';
let socket = null;
let connected = false;
let paired = false;
let plugin;
let openRequests = [];
let allowReconnects = true;
let reconnectionTimeout = null;
const sha256 = data => (0, _createHash2.default)('sha256').update(data).digest('hex');
const sha256 = data => createHash('sha256').update(data).digest('hex');
const reconnectOnAbnormalDisconnection = () => {
if (!allowReconnects) return;
clearTimeout(reconnectionTimeout);
reconnectionTimeout = setTimeout(() => {
SocketService.link();
}, 1000);
if (!allowReconnects) return;
clearTimeout(reconnectionTimeout);
reconnectionTimeout = setTimeout(() => {
SocketService.link();
}, 1000);
};
const random = () => {
const array = new Uint8Array(24);
(0, _getRandomValues2.default)(array);
return array.join('');
const array = new Uint8Array(24);
getRandomValues(array);
return array.join('');
};
const getOrigin = () => {
let origin;
if (typeof location !== 'undefined') {
if (location.hasOwnProperty('hostname') && location.hostname.length && location.hostname !== 'localhost') origin = location.hostname;else origin = plugin;
} else origin = plugin;
return origin;
};
// StorageService.removeAppKey();
let origin;
if (typeof location !== 'undefined') {
if (location.hasOwnProperty('hostname') && location.hostname.length && location.hostname !== 'localhost') origin = location.hostname;else origin = plugin;
} else origin = plugin;
return origin;
}; // StorageService.removeAppKey();
// StorageService.removeNonce();
let appkey = _StorageService2.default.getAppKey();
let appkey = StorageService.getAppKey();
if (!appkey) appkey = 'appkey:' + random();
const send = (type = null, data = null) => {
if (type === null && data === null) socket.send('40/scatter');else socket.send('42/scatter,' + (0, _stringify2.default)([type, data]));
if (type === null && data === null) socket.send('40/scatter');else socket.send('42/scatter,' + JSON.stringify([type, data]));
};
let pairingPromise = null;
const pair = (passthrough = false) => {
return new _promise2.default((resolve, reject) => {
pairingPromise = { resolve, reject };
send('pair', { data: { appkey, origin: getOrigin(), passthrough }, plugin });
return new Promise((resolve, reject) => {
pairingPromise = {
resolve,
reject
};
send('pair', {
data: {
appkey,
origin: getOrigin(),
passthrough
},
plugin
});
});
};
class SocketService {
export default class SocketService {
static init(_plugin, timeout = 60000) {
plugin = _plugin;
this.timeout = timeout;
}
static init(_plugin, timeout = 60000) {
plugin = _plugin;
this.timeout = timeout;
}
static link() {
return Promise.race([new Promise((resolve, reject) => setTimeout(() => {
if (connected) return;
resolve(false);
static link() {
if (socket) {
socket.disconnect();
socket = null;
}
return _promise2.default.race([new _promise2.default((resolve, reject) => setTimeout(() => {
if (connected) return;
resolve(false);
reconnectOnAbnormalDisconnection();
}, this.timeout)), new Promise((resolve, reject) => {
socket = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`);
if (socket) {
socket.disconnect();
socket = null;
}
socket.onclose = x => resolve(false);
reconnectOnAbnormalDisconnection();
}, this.timeout)), new _promise2.default((resolve, reject) => {
socket = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`);
socket.onerror = err => resolve(false);
socket.onclose = x => {
resolve(false);
};
socket.onopen = x => {
send();
clearTimeout(reconnectionTimeout);
connected = true;
pair(true).then(() => {
resolve(true);
});
};
socket.onerror = err => {
console.error('err', err);
resolve(false);
};
socket.onmessage = msg => {
// Handshaking/Upgrading
if (msg.data.indexOf('42/scatter') === -1) return false; // Real message
socket.onopen = x => {
send();
clearTimeout(reconnectionTimeout);
connected = true;
pair(true).then(() => {
console.log('then pair', connected);
resolve(true);
});
};
const [type, data] = JSON.parse(msg.data.replace('42/scatter,', ''));
socket.onmessage = msg => {
// Handshaking/Upgrading
if (msg.data.indexOf('42/scatter') === -1) return false;
switch (type) {
case 'paired':
return msg_paired(data);
// Real message
const [type, data] = JSON.parse(msg.data.replace('42/scatter,', ''));
case 'rekey':
return msg_rekey();
switch (type) {
case 'paired':
return msg_paired(data);
case 'rekey':
return msg_rekey();
case 'api':
return msg_api(data);
}
};
case 'api':
return msg_api(data);
}
};
const msg_paired = result => {
console.log('paired', result);
paired = result;
const msg_paired = result => {
paired = result;
if (paired) {
const savedKey = _StorageService2.default.getAppKey();
const hashed = appkey.indexOf('appkey:') > -1 ? sha256(appkey) : appkey;
if (paired) {
const savedKey = StorageService.getAppKey();
const hashed = appkey.indexOf('appkey:') > -1 ? sha256(appkey) : appkey;
if (!savedKey || savedKey !== hashed) {
_StorageService2.default.setAppKey(hashed);
appkey = _StorageService2.default.getAppKey();
}
}
if (!savedKey || savedKey !== hashed) {
StorageService.setAppKey(hashed);
appkey = StorageService.getAppKey();
}
}
pairingPromise.resolve(result);
};
pairingPromise.resolve(result);
};
const msg_rekey = () => {
appkey = 'appkey:' + random();
send('rekeyed', { data: { appkey, origin: getOrigin() }, plugin });
};
const msg_rekey = () => {
appkey = 'appkey:' + random();
send('rekeyed', {
data: {
appkey,
origin: getOrigin()
},
plugin
});
};
const msg_api = result => {
const openRequest = openRequests.find(x => x.id === result.id);
if (!openRequest) return;
if (typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result);else openRequest.resolve(result.result);
};
const msg_api = response => {
const openRequest = openRequests.find(x => x.id === response.id);
if (!openRequest) return;
openRequests = openRequests.filter(x => x.id !== response.id);
const isErrorResponse = typeof response.result === 'object' && response.result !== null && response.result.hasOwnProperty('isError');
if (isErrorResponse) openRequest.reject(response.result);else openRequest.resolve(response.result);
}; // socket.on('event', event => {
// console.log('event', event);
// });
//
// socket.on('event', event => {
// console.log('event', event);
// });
//
// socket.on('disconnect', () => {
// console.log('Disconnected')
// connected = false;
// socket = null;
//
// // If bad disconnect, retry connection
// reconnectOnAbnormalDisconnection();
// });
//
// socket.on('connect_error', () => {
// allowReconnects = false;
// resolve(false);
// });
//
// socket.on('rejected', reason => {
// console.error('reason', reason);
// reject(reason);
// });
})]);
}
})]);
}
static isConnected() {
return connected;
}
static isConnected() {
return connected;
}
static disconnect() {
socket.disconnect();
return true;
}
static disconnect() {
if (socket) socket.disconnect();
return true;
}
static sendApiRequest(request) {
return new _promise2.default((resolve, reject) => {
if (request.type === 'identityFromPermissions' && !paired) return resolve(false);
static sendApiRequest(request) {
return new Promise((resolve, reject) => {
if (request.type === 'identityFromPermissions' && !paired) return resolve(false);
pair().then(() => {
if (!paired) return reject({
code: 'not_paired',
message: 'The user did not allow this app to connect to their Scatter'
}); // Request ID used for resolving promises
pair().then(() => {
if (!paired) return reject({ code: 'not_paired', message: 'The user did not allow this app to connect to their Scatter' });
request.id = random(); // Set Application Key
// Request ID used for resolving promises
request.id = random();
request.appkey = appkey; // Nonce used to authenticate this request
// Set Application Key
request.appkey = appkey;
request.nonce = StorageService.getNonce() || 0; // Next nonce used to authenticate the next request
// Nonce used to authenticate this request
request.nonce = _StorageService2.default.getNonce() || 0;
// Next nonce used to authenticate the next request
const nextNonce = random();
request.nextNonce = sha256(nextNonce);
_StorageService2.default.setNonce(nextNonce);
if (request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) request.payload.origin = getOrigin();
openRequests.push((0, _assign2.default)(request, { resolve, reject }));
send('api', { data: request, plugin });
});
const nextNonce = random();
request.nextNonce = sha256(nextNonce);
StorageService.setNonce(nextNonce);
if (request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) request.payload.origin = getOrigin();
openRequests.push(Object.assign(request, {
resolve,
reject
}));
send('api', {
data: request,
plugin
});
}
});
});
}
}
exports.default = SocketService;
}

@@ -1,46 +0,41 @@

'use strict';
let storage = {};
Object.defineProperty(exports, "__esModule", {
value: true
});
let storage = {};
const getWindow = () => {
if (typeof window !== 'undefined') return window;
return {
localStorage: {
setItem: (key, val) => storage[key] = val,
getItem: key => storage[key] || null,
removeItem: key => delete storage[key]
}
};
if (typeof window !== 'undefined') return window;
return {
localStorage: {
setItem: (key, val) => storage[key] = val,
getItem: key => storage[key] || null,
removeItem: key => delete storage[key]
}
};
};
class StorageService {
export default class StorageService {
constructor() {}
constructor() {}
static setAppKey(appkey) {
getWindow().localStorage.setItem('appkey', appkey);
}
static setAppKey(appkey) {
getWindow().localStorage.setItem('appkey', appkey);
}
static getAppKey() {
return getWindow().localStorage.getItem('appkey');
}
static getAppKey() {
return getWindow().localStorage.getItem('appkey');
}
static removeAppKey() {
return getWindow().localStorage.removeItem('appkey');
}
static removeAppKey() {
return getWindow().localStorage.removeItem('appkey');
}
static setNonce(nonce) {
getWindow().localStorage.setItem('nonce', nonce);
}
static setNonce(nonce) {
getWindow().localStorage.setItem('nonce', nonce);
}
static getNonce() {
return getWindow().localStorage.getItem('nonce');
}
static getNonce() {
return getWindow().localStorage.getItem('nonce');
}
static removeNonce() {
return getWindow().localStorage.removeItem('nonce');
}
static removeNonce() {
return getWindow().localStorage.removeItem('nonce');
}
}
exports.default = StorageService;
}
{
"name": "scatterjs-core",
"version": "1.0.0",
"version": "1.1.0",
"main": "dist/index.js",

@@ -11,3 +11,3 @@ "license": "MIT",

},
"gitHead": "66e9c31d54819d6bcee81128e7071e35a831bbca"
"gitHead": "4772f85f3b41e162293463965ad51a48c976bcb2"
}
import PluginRepository from './plugins/PluginRepository';
import SocketService from './services/SocketService';
import Plugin from './Plugins/Plugin';
import * as PluginTypes from './Plugins/PluginTypes';
import Plugin from './plugins/Plugin';
import * as PluginTypes from './plugins/PluginTypes';
import { Blockchains } from './models/Blockchains';

@@ -176,2 +176,10 @@ import Network from './models/Network';

requestTransfer(network, to, amount, options = {}){
const payload = {network, to, amount, options};
return SocketService.sendApiRequest({
type:'requestTransfer',
payload
});
}
requestSignature(payload){

@@ -202,2 +210,3 @@ throwNoAuth();

constructor(_scatter){
console.log(_scatter);
this.scatter = _scatter;

@@ -229,4 +238,3 @@ }

if(!holder.scatter.isExtension)
window.scatter = holder.scatter;
window.ScatterJS = holder;
}

@@ -239,6 +247,5 @@

holder.SocketService = SocketService;
module.exports = holder;
export {Plugin, PluginTypes, Blockchains, Network, SocketService};
export default holder;

@@ -0,0 +0,0 @@

@@ -0,0 +0,0 @@ import * as ErrorTypes from './ErrorTypes'

@@ -0,0 +0,0 @@ export const MALICIOUS = 'malicious';

@@ -0,0 +0,0 @@ import {Blockchains} from './Blockchains';

@@ -0,0 +0,0 @@ import * as PluginTypes from "./PluginTypes";

@@ -0,0 +0,0 @@ import * as PluginTypes from './PluginTypes';

@@ -89,11 +89,5 @@ import StorageService from './StorageService'

socket.onclose = x => {
resolve(false);
};
socket.onclose = x => resolve(false);
socket.onerror = err => resolve(false);
socket.onerror = err => {
console.error('err', err);
resolve(false);
}
socket.onopen = x => {

@@ -104,3 +98,2 @@ send();

pair(true).then(() => {
console.log('then pair', connected);
resolve(true);

@@ -126,3 +119,2 @@ });

const msg_paired = result => {
console.log('paired', result);
paired = result;

@@ -148,35 +140,19 @@

const msg_api = result => {
const openRequest = openRequests.find(x => x.id === result.id);
const msg_api = response => {
const openRequest = openRequests.find(x => x.id === response.id);
if(!openRequest) return;
if(typeof result.result === 'object'
&& result.result !== null
&& result.result.hasOwnProperty('isError')) openRequest.reject(result.result);
else openRequest.resolve(result.result);
openRequests = openRequests.filter(x => x.id !== response.id);
const isErrorResponse = typeof response.result === 'object'
&& response.result !== null
&& response.result.hasOwnProperty('isError');
if(isErrorResponse) openRequest.reject(response.result);
else openRequest.resolve(response.result);
};
//
// socket.on('event', event => {
// console.log('event', event);
// });
//
// socket.on('disconnect', () => {
// console.log('Disconnected')
// connected = false;
// socket = null;
//
// // If bad disconnect, retry connection
// reconnectOnAbnormalDisconnection();
// });
//
// socket.on('connect_error', () => {
// allowReconnects = false;
// resolve(false);
// });
//
// socket.on('rejected', reason => {
// console.error('reason', reason);
// reject(reason);
// });
})

@@ -191,3 +167,3 @@ ])

static disconnect(){
socket.disconnect();
if(socket) socket.disconnect();
return true;

@@ -194,0 +170,0 @@ }

@@ -0,0 +0,0 @@ let storage = {};

@@ -0,0 +0,0 @@ // import ScatterJS from '../src/scatter';

@@ -0,0 +0,0 @@ // import { assert } from 'chai';

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc