index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. console.log('nonce', nonce);
  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(dontLogToAll, 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. if (!dontLogToAll && topic !== 'all' && !deleteHash) {
  209. yield this.appendPrivate(true, peerAddr, 'all', hash, undefined, undefined);
  210. }
  211. });
  212. }
  213. retrievePrivate(peerAddr, topic) {
  214. return __awaiter(this, void 0, void 0, function* () {
  215. const nonce = yield this.getNonce();
  216. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  217. _date: new Date().toISOString(),
  218. _nonce: nonce
  219. }));
  220. const topicURL = this.urlBase + '/bank/private/' + encodeURIComponent(peerAddr) + '/' + encodeURIComponent(topic);
  221. const result = yield this.webClient.request({
  222. body: JSON.stringify(retrieveRequest),
  223. headers: {
  224. 'content-type': 'application/json'
  225. },
  226. method: 'POST',
  227. url: topicURL
  228. });
  229. return result;
  230. });
  231. }
  232. subscribePrivate(peerAddr, topic, connectCallback, messageCallback) {
  233. return __awaiter(this, void 0, void 0, function* () {
  234. yield this.connectWebsocket(peerAddr, topic, connectCallback, messageCallback);
  235. });
  236. }
  237. getOrCreateContact(peerId, contactAddr) {
  238. return __awaiter(this, void 0, void 0, function* () {
  239. const contactList = yield this.retrievePrivate(peerId, '📇');
  240. const itemList = yield this.getItemsForCommaList(contactList);
  241. // console.log('contact hash for', contact, type, 'is', contactHash);
  242. const existing = itemList.filter(item => item.addrs && item.addrs.includes(contactAddr))[0];
  243. if (existing != null) {
  244. return existing;
  245. }
  246. const newItem = {
  247. addrs: [
  248. contactAddr
  249. ],
  250. id: util_1.uuid()
  251. };
  252. const newItemHash = yield this.uploadSlimJSON(newItem);
  253. yield this.appendPrivate(true, peerId, '📇', newItemHash);
  254. return newItem;
  255. });
  256. }
  257. getContactById(peerId, contactId) {
  258. return __awaiter(this, void 0, void 0, function* () {
  259. const contactList = yield this.retrievePrivate(peerId, '📇');
  260. const itemList = yield this.getItemsForCommaList(contactList);
  261. const existing = itemList.filter(item => item.id === contactId)[0];
  262. if (!existing) {
  263. throw new Error('Cannot find contact with id ' + contactId);
  264. }
  265. return existing;
  266. });
  267. }
  268. updateContact(peerId, contactId, newProperties) {
  269. return __awaiter(this, void 0, void 0, function* () {
  270. const existing = yield this.getContactById(peerId, contactId);
  271. const newProps = util_1.mergeDeep({}, newProperties);
  272. delete newProps.id;
  273. const newItem = util_1.mergeDeep(existing, newProps);
  274. delete newItem.hash;
  275. const newItemHash = yield this.uploadSlimJSON(newItem);
  276. yield this.appendPrivate(true, peerId, '📇', newItemHash, existing.hash);
  277. return yield this.getContactById(peerId, contactId);
  278. });
  279. }
  280. getContentItemByHash(hash) {
  281. return __awaiter(this, void 0, void 0, function* () {
  282. if (hash.startsWith('/ipfs/')) {
  283. hash = hash.split('/').pop();
  284. }
  285. const contentParams = (yield this.webClient.requestJSON({
  286. method: 'get',
  287. url: this.ipfsUrlBase + '/ipfs/' + hash + '/content.json'
  288. }));
  289. return new content_item_1.ContentItem(hash, contentParams);
  290. });
  291. }
  292. getItemsForCommaList(commaList) {
  293. return __awaiter(this, void 0, void 0, function* () {
  294. const itemHashes = commaList.split(',').filter(x => x.trim() !== '');
  295. const items = yield Promise.all(itemHashes.map(itemId => {
  296. return this.webClient.requestJSON({
  297. method: 'get',
  298. url: this.ipfsUrlBase + '/ipfs/' + itemId,
  299. });
  300. }));
  301. for (const item of items) {
  302. item.hash = itemHashes.shift();
  303. }
  304. return items;
  305. });
  306. }
  307. connectWebsocket(peerAddr, topic, connectCallback, messageCallback) {
  308. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  309. const nonce = yield this.getNonce();
  310. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  311. _date: new Date().toISOString(),
  312. _nonce: nonce,
  313. addr: peerAddr,
  314. topic: topic
  315. }));
  316. const jsonOutput = JSON.stringify(retrieveRequest);
  317. const base64ed = Buffer.from(jsonOutput).toString('base64');
  318. const encoded = encodeURIComponent(base64ed);
  319. const ws = new ws_1.default(this.wsUrlBase + '/bank/ws?arg=' + encoded);
  320. ws.on('open', () => {
  321. connectCallback();
  322. });
  323. ws.on('message', data => {
  324. messageCallback(data);
  325. });
  326. const reconnect = () => {
  327. console.log('reconnect');
  328. try {
  329. ws.terminate();
  330. }
  331. finally {
  332. console.log('reconnecting in 5s');
  333. setTimeout(() => {
  334. this.connectWebsocket(peerAddr, topic, connectCallback, messageCallback);
  335. }, 5000);
  336. }
  337. };
  338. ws.on('error', err => {
  339. console.error('websocket error', err);
  340. });
  341. ws.on('close', err => {
  342. reconnect();
  343. });
  344. resolve();
  345. }));
  346. }
  347. getPriv() {
  348. if (!this.privateKey) {
  349. throw new Error('missing private key');
  350. }
  351. return this.privateKey;
  352. }
  353. makePlaintextPayload(message) {
  354. const messageBytes = Buffer.from(message, 'utf-8');
  355. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  356. yield this.bootstrap();
  357. this.privateKey.sign(messageBytes, (signErr, signatureBytes) => __awaiter(this, void 0, void 0, function* () {
  358. if (signErr) {
  359. reject(signErr);
  360. return;
  361. }
  362. const publicDERBytes = this.privateKey.public.bytes;
  363. this.privateKey.id((idErr, pubHash) => {
  364. if (idErr) {
  365. reject(idErr);
  366. return;
  367. }
  368. const result = {
  369. date: new Date().toISOString(),
  370. msg: util_1.encodeHex(messageBytes),
  371. pub: util_1.encodeHex(publicDERBytes),
  372. pubHash,
  373. sig: util_1.encodeHex(signatureBytes),
  374. };
  375. // console.log('result', result, signatureBytes);
  376. resolve(result);
  377. });
  378. }));
  379. }));
  380. }
  381. }
  382. exports.BankClient = BankClient;
  383. //# sourceMappingURL=index.js.map