3box
Version:
Interact with user data
319 lines (259 loc) • 9.6 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _wallet = require("@ethersproject/wallet");
var fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
var Multihash = require('multihashes');
var sha256 = require('js-sha256').sha256;
var ENC_BLOCK_SIZE = 24;
var MAGIC_ERC1271_VALUE = '0x20c13b0b';
var pad = function pad(val) {
var blockSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ENC_BLOCK_SIZE;
var blockDiff = (blockSize - val.length % blockSize) % blockSize;
return "".concat(val).concat('\0'.repeat(blockDiff));
};
var unpad = function unpad(padded) {
return padded.replace(/\0+$/, '');
};
var HTTPError = function HTTPError(status, message) {
var e = new Error(message);
e.statusCode = status;
return e;
};
var getMessageConsent = function getMessageConsent(did, timestamp) {
var msg = 'Create a new 3Box profile' + '\n\n' + '- \n' + 'Your unique profile ID is ' + did;
if (timestamp) msg += ' \n' + 'Timestamp: ' + timestamp;
return msg;
};
var safeSend = function safeSend(provider, data) {
var send = (Boolean(provider.sendAsync) ? provider.sendAsync : provider.send).bind(provider);
return new Promise(function (resolve, reject) {
send(data, function (err, result) {
if (err) reject(err);else if (result.error) reject(result.error);else resolve(result.result);
});
});
};
var encodeRpcCall = function encodeRpcCall(method, params, fromAddress) {
return {
jsonrpc: '2.0',
id: 1,
method: method,
params: params,
fromAddress: fromAddress
};
};
var callRpc = /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(provider, method, params, fromAddress) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", safeSend(provider, encodeRpcCall(method, params, fromAddress)));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function callRpc(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
}();
module.exports = {
getMessageConsent: getMessageConsent,
callRpc: callRpc,
openBoxConsent: function () {
var _openBoxConsent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(fromAddress, ethereum) {
var text, msg, params, method, res, recoveredAddr;
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
text = 'This app wants to view and update your 3Box profile.';
if (!ethereum.isAuthereum) {
_context2.next = 3;
break;
}
return _context2.abrupt("return", ethereum.signMessageWithSigningKey(text));
case 3:
msg = '0x' + Buffer.from(text, 'utf8').toString('hex');
params = [msg, fromAddress];
method = 'personal_sign';
_context2.next = 8;
return callRpc(ethereum, method, params, fromAddress);
case 8:
res = _context2.sent;
if (!fromAddress) {
_context2.next = 13;
break;
}
recoveredAddr = (0, _wallet.verifyMessage)(text, res).toLowerCase();
if (!(fromAddress !== recoveredAddr)) {
_context2.next = 13;
break;
}
throw new Error('Provider returned signature from different account than requested');
case 13:
return _context2.abrupt("return", res);
case 14:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function openBoxConsent(_x5, _x6) {
return _openBoxConsent.apply(this, arguments);
}
return openBoxConsent;
}(),
openSpaceConsent: function () {
var _openSpaceConsent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(fromAddress, ethereum, name) {
var text, msg, params, method, res, recoveredAddr;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
text = "Allow this app to open your ".concat(name, " space.");
if (!ethereum.isAuthereum) {
_context3.next = 3;
break;
}
return _context3.abrupt("return", ethereum.signMessageWithSigningKey(text));
case 3:
msg = '0x' + Buffer.from(text, 'utf8').toString('hex');
params = [msg, fromAddress];
method = 'personal_sign';
_context3.next = 8;
return callRpc(ethereum, method, params, fromAddress);
case 8:
res = _context3.sent;
if (!fromAddress) {
_context3.next = 13;
break;
}
recoveredAddr = (0, _wallet.verifyMessage)(text, res).toLowerCase();
if (!(fromAddress !== recoveredAddr)) {
_context3.next = 13;
break;
}
throw new Error('Provider returned signature from different account than requested');
case 13:
return _context3.abrupt("return", res);
case 14:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function openSpaceConsent(_x7, _x8, _x9) {
return _openSpaceConsent.apply(this, arguments);
}
return openSpaceConsent;
}(),
fetchJson: function () {
var _fetchJson = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(url, body) {
var opts, r, res;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (body) {
opts = {
body: JSON.stringify(body),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
}
_context4.next = 3;
return fetch(url, opts);
case 3:
r = _context4.sent;
if (!r.ok) {
_context4.next = 11;
break;
}
_context4.next = 7;
return r.json();
case 7:
res = _context4.sent;
return _context4.abrupt("return", res);
case 11:
_context4.t0 = HTTPError;
_context4.t1 = r.status;
_context4.next = 15;
return r.json();
case 15:
_context4.t2 = _context4.sent.message;
throw (0, _context4.t0)(_context4.t1, _context4.t2);
case 17:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function fetchJson(_x10, _x11) {
return _fetchJson.apply(this, arguments);
}
return fetchJson;
}(),
fetchText: function () {
var _fetchText = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(url, opts) {
var r;
return _regenerator["default"].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return fetch(url, opts);
case 2:
r = _context5.sent;
if (!r.ok) {
_context5.next = 7;
break;
}
return _context5.abrupt("return", r.text());
case 7:
throw HTTPError(r.status, "Invalid response (".concat(r.status, ") for query at ").concat(url));
case 8:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
function fetchText(_x12, _x13) {
return _fetchText.apply(this, arguments);
}
return fetchText;
}(),
throwIfUndefined: function throwIfUndefined(arg, name) {
if (arg === undefined || arg === null) {
throw new Error("".concat(name, " is a required argument"));
}
},
throwIfNotEqualLenArrays: function throwIfNotEqualLenArrays(arr1, arr2) {
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
throw new Error('One or more arguments are not an array');
}
if (arr1.length !== arr2.length) {
throw new Error('Arrays must be of the same length');
}
},
sha256Multihash: function sha256Multihash(str) {
var digest = Buffer.from(sha256.digest(str));
return Multihash.encode(digest, 'sha2-256').toString('hex');
},
randInt: function randInt(max) {
return Math.floor(Math.random() * max);
},
sha256: sha256,
pad: pad,
unpad: unpad
};