index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. var __importDefault = (this && this.__importDefault) || function (mod) {
  11. return (mod && mod.__esModule) ? mod : { "default": mod };
  12. };
  13. Object.defineProperty(exports, "__esModule", { value: true });
  14. const crypto = require("libp2p-crypto");
  15. const ws_1 = __importDefault(require("ws"));
  16. const content_item_1 = require("./content-item");
  17. const util_1 = require("./util");
  18. class BankClient {
  19. constructor(urlBase, ipfsUrlBase, storage, webClient) {
  20. this.urlBase = urlBase;
  21. this.ipfsUrlBase = ipfsUrlBase;
  22. this.storage = storage;
  23. this.webClient = webClient;
  24. this.wsUrlBase = urlBase.replace(/^http/i, 'ws');
  25. }
  26. static parseBankLink(bankLink) {
  27. if (!bankLink.startsWith('bank:')) {
  28. throw new Error('address must start with bank:');
  29. }
  30. const deprefixed = bankLink.substring(5);
  31. let host;
  32. let address;
  33. let topic;
  34. if (deprefixed[0] === '/' && deprefixed[1] === '/') {
  35. [host, address, topic] = deprefixed.substring(2).split('/');
  36. }
  37. else {
  38. [address, topic] = deprefixed.split('/');
  39. }
  40. if (!address || !topic) {
  41. throw new Error('cannot parse address and topic');
  42. }
  43. return { host, address, topic };
  44. }
  45. getPub() {
  46. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  47. yield this.bootstrap();
  48. this.getPriv().id((idErr, pubHash) => {
  49. if (idErr) {
  50. return reject(idErr);
  51. }
  52. resolve(pubHash);
  53. });
  54. }));
  55. }
  56. bootstrap() {
  57. if (this.bootstrapResult) {
  58. return Promise.resolve(this.bootstrapResult);
  59. }
  60. if (this.bootstrapPromise) {
  61. return this.bootstrapPromise;
  62. }
  63. return this.bootstrapPromise = new Promise((resolve, reject) => {
  64. this.storage.get('notaprivatekey').then(privateKeyFromStorage => {
  65. if (privateKeyFromStorage == null) {
  66. console.log('no private key in storage. generating new');
  67. crypto.keys.generateKeyPair('RSA', 2048, (generateErr, privateKey) => {
  68. if (generateErr) {
  69. return reject(generateErr);
  70. }
  71. privateKey.export('password', (exportErr, exportResult) => {
  72. if (exportErr) {
  73. return reject(exportErr);
  74. }
  75. this.storage.set('notaprivatekey', exportResult).then(err => {
  76. // whatever
  77. }).catch(reject);
  78. this.privateKey = privateKey;
  79. resolve(true);
  80. });
  81. });
  82. }
  83. else {
  84. // console.log('importing privatekey');
  85. crypto.keys.import(privateKeyFromStorage, 'password', (err, importedPrivateKey) => {
  86. if (err) {
  87. return reject(err);
  88. }
  89. this.privateKey = importedPrivateKey;
  90. // console.log(this.getPublicKeyString());
  91. // console.log(privateKeyFromStorage);
  92. resolve(true);
  93. });
  94. }
  95. }).catch(reject);
  96. });
  97. }
  98. getNonce() {
  99. return __awaiter(this, void 0, void 0, function* () {
  100. const nonce = yield this.webClient.request({
  101. method: 'GET',
  102. url: this.urlBase + '/bank/nonce'
  103. });
  104. return Number(nonce);
  105. });
  106. }
  107. getBalance() {
  108. return __awaiter(this, void 0, void 0, function* () {
  109. const nonce = yield this.getNonce();
  110. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  111. _date: new Date().toISOString(),
  112. _nonce: nonce
  113. }));
  114. const topicURL = this.urlBase + '/bank/getbalance';
  115. const postResponse = yield this.webClient.requestJSON({
  116. body: retrieveRequest,
  117. method: 'POST',
  118. url: topicURL
  119. });
  120. return postResponse.balance;
  121. });
  122. }
  123. upload(params) {
  124. return __awaiter(this, void 0, void 0, function* () {
  125. const url = this.urlBase + '/bank/upload';
  126. const formData = {};
  127. if (params.fileData) {
  128. formData.file = {
  129. value: params.fileData,
  130. options: {
  131. filename: params.fileName
  132. }
  133. };
  134. }
  135. if (params.thumbFileData) {
  136. formData.thumb = {
  137. value: params.thumbFileData,
  138. options: {
  139. filename: params.thumbFileName
  140. }
  141. };
  142. }
  143. if (params.links) {
  144. formData.links = JSON.stringify(params.links);
  145. }
  146. for (const attr of ['title', 'text', 'type']) {
  147. if (params[attr] != null) {
  148. formData[attr] = params[attr];
  149. }
  150. }
  151. // console.log('formData', formData);
  152. const uploadResponse = yield this.webClient.requestJSON({
  153. formData,
  154. method: 'POST',
  155. url
  156. });
  157. // console.log('uploadResponse', uploadResponse);
  158. return uploadResponse.hash;
  159. });
  160. }
  161. uploadSlimJSON(item) {
  162. return __awaiter(this, void 0, void 0, function* () {
  163. const url = this.urlBase + '/bank/upload/slim';
  164. const uploadResponse = yield this.webClient.requestJSON({
  165. body: item,
  166. method: 'POST',
  167. url
  168. });
  169. // console.log('uploadResponse', uploadResponse);
  170. return uploadResponse.hash;
  171. });
  172. }
  173. uploadSlimText(item) {
  174. return __awaiter(this, void 0, void 0, function* () {
  175. const url = this.urlBase + '/bank/upload/slim';
  176. const uploadResponse = JSON.parse(yield this.webClient.request({
  177. body: item,
  178. headers: {
  179. 'content-type': 'text/plain'
  180. },
  181. method: 'POST',
  182. url
  183. }));
  184. // console.log('uploadResponse', uploadResponse);
  185. return uploadResponse.hash;
  186. });
  187. }
  188. appendPrivate(slim, peerAddr, topic, hash, replaceHash, deleteHash) {
  189. return __awaiter(this, void 0, void 0, function* () {
  190. const nonce = yield this.getNonce();
  191. const payload = yield this.makePlaintextPayload(JSON.stringify({
  192. _date: new Date().toISOString(),
  193. _nonce: nonce,
  194. deleteHash,
  195. hash,
  196. replaceHash,
  197. }));
  198. const topicURL = this.urlBase + '/bank/private/' + encodeURIComponent(peerAddr) + '/' + encodeURIComponent(topic);
  199. const result = yield this.webClient.request({
  200. body: JSON.stringify(payload),
  201. headers: {
  202. 'content-type': 'application/json'
  203. },
  204. method: 'PUT',
  205. url: topicURL
  206. });
  207. if (!slim && topic !== 'all' && !deleteHash) {
  208. yield this.appendPrivate(slim, peerAddr, 'all', hash, undefined, undefined);
  209. }
  210. });
  211. }
  212. retrievePrivate(peerAddr, topic) {
  213. return __awaiter(this, void 0, void 0, function* () {
  214. const nonce = yield this.getNonce();
  215. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  216. _date: new Date().toISOString(),
  217. _nonce: nonce
  218. }));
  219. const topicURL = this.urlBase + '/bank/private/' + encodeURIComponent(peerAddr) + '/' + encodeURIComponent(topic);
  220. const result = yield this.webClient.request({
  221. body: JSON.stringify(retrieveRequest),
  222. headers: {
  223. 'content-type': 'application/json'
  224. },
  225. method: 'POST',
  226. url: topicURL
  227. });
  228. return result;
  229. });
  230. }
  231. subscribePrivate(peerAddr, topic, connectCallback, messageCallback) {
  232. return __awaiter(this, void 0, void 0, function* () {
  233. yield this.connectWebsocket(peerAddr, topic, connectCallback, messageCallback);
  234. });
  235. }
  236. getOrCreateContact(peerId, contactAddr) {
  237. return __awaiter(this, void 0, void 0, function* () {
  238. const contactList = yield this.retrievePrivate(peerId, '📇');
  239. const itemList = yield this.getItemsForCommaList(contactList);
  240. // console.log('contact hash for', contact, type, 'is', contactHash);
  241. const existing = itemList.filter(item => item.addrs && item.addrs.includes(contactAddr))[0];
  242. if (existing != null) {
  243. return existing;
  244. }
  245. const newItem = {
  246. addrs: [
  247. contactAddr
  248. ],
  249. id: util_1.uuid()
  250. };
  251. const newItemHash = yield this.uploadSlimJSON(newItem);
  252. yield this.appendPrivate(true, peerId, '📇', newItemHash);
  253. return newItem;
  254. });
  255. }
  256. getContactById(peerId, contactId) {
  257. return __awaiter(this, void 0, void 0, function* () {
  258. const contactList = yield this.retrievePrivate(peerId, '📇');
  259. const itemList = yield this.getItemsForCommaList(contactList);
  260. const existing = itemList.filter(item => item.id === contactId)[0];
  261. if (!existing) {
  262. throw new Error('Cannot find contact with id ' + contactId);
  263. }
  264. return existing;
  265. });
  266. }
  267. updateContact(peerId, contactId, newProperties) {
  268. return __awaiter(this, void 0, void 0, function* () {
  269. const existing = yield this.getContactById(peerId, contactId);
  270. const newProps = util_1.mergeDeep({}, newProperties);
  271. delete newProps.id;
  272. const newItem = util_1.mergeDeep(existing, newProps);
  273. delete newItem.hash;
  274. const newItemHash = yield this.uploadSlimJSON(newItem);
  275. yield this.appendPrivate(true, peerId, '📇', newItemHash, existing.hash);
  276. return yield this.getContactById(peerId, contactId);
  277. });
  278. }
  279. getContentItemByHash(hash) {
  280. return __awaiter(this, void 0, void 0, function* () {
  281. if (hash.startsWith('/ipfs/')) {
  282. hash = hash.split('/').pop();
  283. }
  284. const contentParams = (yield this.webClient.requestJSON({
  285. method: 'get',
  286. url: this.ipfsUrlBase + '/ipfs/' + hash + '/content.json'
  287. }));
  288. return new content_item_1.ContentItem(hash, contentParams);
  289. });
  290. }
  291. getItemsForCommaList(commaList) {
  292. return __awaiter(this, void 0, void 0, function* () {
  293. const itemHashes = commaList.split(',').filter(x => x.trim() !== '');
  294. const items = yield Promise.all(itemHashes.map(itemId => {
  295. return this.webClient.requestJSON({
  296. method: 'get',
  297. url: this.ipfsUrlBase + '/ipfs/' + itemId,
  298. });
  299. }));
  300. for (const item of items) {
  301. item.hash = itemHashes.shift();
  302. }
  303. return items;
  304. });
  305. }
  306. connectWebsocket(peerAddr, topic, connectCallback, messageCallback) {
  307. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  308. const nonce = yield this.getNonce();
  309. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  310. _date: new Date().toISOString(),
  311. _nonce: nonce,
  312. addr: peerAddr,
  313. topic: topic
  314. }));
  315. const jsonOutput = JSON.stringify(retrieveRequest);
  316. const base64ed = Buffer.from(jsonOutput).toString('base64');
  317. const encoded = encodeURIComponent(base64ed);
  318. const ws = new ws_1.default(this.wsUrlBase + '/bank/ws?arg=' + encoded);
  319. ws.on('open', () => {
  320. connectCallback();
  321. });
  322. ws.on('message', data => {
  323. messageCallback(data);
  324. });
  325. const reconnect = () => {
  326. console.log('reconnect');
  327. try {
  328. ws.terminate();
  329. }
  330. finally {
  331. console.log('reconnecting in 5s');
  332. setTimeout(() => {
  333. this.connectWebsocket(peerAddr, topic, connectCallback, messageCallback);
  334. }, 5000);
  335. }
  336. };
  337. ws.on('error', err => {
  338. console.error('websocket error', err);
  339. });
  340. ws.on('close', err => {
  341. reconnect();
  342. });
  343. resolve();
  344. }));
  345. }
  346. getPriv() {
  347. if (!this.privateKey) {
  348. throw new Error('missing private key');
  349. }
  350. return this.privateKey;
  351. }
  352. makePlaintextPayload(message) {
  353. const messageBytes = Buffer.from(message, 'utf-8');
  354. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  355. yield this.bootstrap();
  356. this.privateKey.sign(messageBytes, (signErr, signatureBytes) => __awaiter(this, void 0, void 0, function* () {
  357. if (signErr) {
  358. reject(signErr);
  359. return;
  360. }
  361. const publicDERBytes = this.privateKey.public.bytes;
  362. this.privateKey.id((idErr, pubHash) => {
  363. if (idErr) {
  364. reject(idErr);
  365. return;
  366. }
  367. const result = {
  368. date: new Date().toISOString(),
  369. msg: util_1.encodeHex(messageBytes),
  370. pub: util_1.encodeHex(publicDERBytes),
  371. pubHash,
  372. sig: util_1.encodeHex(signatureBytes),
  373. };
  374. // console.log('result', result, signatureBytes);
  375. resolve(result);
  376. });
  377. }));
  378. }));
  379. }
  380. }
  381. exports.BankClient = BankClient;
  382. //# sourceMappingURL=index.js.map