index.js 16 KB

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