index.js 19 KB

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