index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 util = require("util");
  16. const storage_1 = require("./storage");
  17. const TextEncoder = util.TextEncoder;
  18. const util_1 = require("./util");
  19. const webclient_node_1 = __importDefault(require("./webclient-node"));
  20. class BankClient {
  21. constructor(urlBase, storage = new storage_1.Storage('bankClient'), webClient = new webclient_node_1.default()) {
  22. this.urlBase = urlBase;
  23. this.storage = storage;
  24. this.webClient = webClient;
  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. const uploadResponse = yield this.webClient.requestJSON({
  152. formData,
  153. method: 'POST',
  154. url
  155. });
  156. return uploadResponse.hash;
  157. });
  158. }
  159. appendBank(bankAddress, bankTopic, itemHash) {
  160. return __awaiter(this, void 0, void 0, function* () {
  161. const payload = yield this.makePlaintextPayload(itemHash);
  162. const topicURL = this.urlBase + '/bank/private/' + encodeURIComponent(bankAddress) + '/' + encodeURIComponent(bankTopic);
  163. yield this.webClient.requestJSON({
  164. body: payload,
  165. method: 'PUT',
  166. url: topicURL
  167. });
  168. });
  169. }
  170. getPriv() {
  171. if (!this.privateKey) {
  172. throw new Error('missing private key');
  173. }
  174. return this.privateKey;
  175. }
  176. makePlaintextPayload(message) {
  177. const messageBytes = new TextEncoder().encode(message);
  178. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  179. yield this.bootstrap();
  180. this.privateKey.sign(messageBytes, (signErr, signatureBytes) => __awaiter(this, void 0, void 0, function* () {
  181. if (signErr) {
  182. reject(signErr);
  183. return;
  184. }
  185. const publicDERBytes = this.privateKey.public.bytes;
  186. this.privateKey.id((idErr, pubHash) => {
  187. if (idErr) {
  188. reject(idErr);
  189. return;
  190. }
  191. const result = {
  192. date: new Date().toISOString(),
  193. msg: util_1.encodeHex(messageBytes),
  194. pub: util_1.encodeHex(publicDERBytes),
  195. pubHash,
  196. sig: util_1.encodeHex(signatureBytes),
  197. };
  198. // console.log('result', result, signatureBytes);
  199. resolve(result);
  200. });
  201. }));
  202. }));
  203. }
  204. }
  205. exports.BankClient = BankClient;
  206. //# sourceMappingURL=index.js.map