index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. getPub() {
  27. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  28. yield this.bootstrap();
  29. this.getPriv().id((idErr, pubHash) => {
  30. if (idErr) {
  31. return reject(idErr);
  32. }
  33. resolve(pubHash);
  34. });
  35. }));
  36. }
  37. bootstrap() {
  38. if (this.bootstrapResult) {
  39. return Promise.resolve(this.bootstrapResult);
  40. }
  41. if (this.bootstrapPromise) {
  42. return this.bootstrapPromise;
  43. }
  44. return this.bootstrapPromise = new Promise((resolve, reject) => {
  45. this.storage.get('notaprivatekey').then(privateKeyFromStorage => {
  46. if (privateKeyFromStorage == null) {
  47. console.log('no private key in storage. generating new');
  48. crypto.keys.generateKeyPair('RSA', 2048, (generateErr, privateKey) => {
  49. if (generateErr) {
  50. return reject(generateErr);
  51. }
  52. privateKey.export('password', (exportErr, exportResult) => {
  53. if (exportErr) {
  54. return reject(exportErr);
  55. }
  56. this.storage.set('notaprivatekey', exportResult).then(err => {
  57. // whatever
  58. }).catch(reject);
  59. this.privateKey = privateKey;
  60. resolve(true);
  61. });
  62. });
  63. }
  64. else {
  65. // console.log('importing privatekey');
  66. crypto.keys.import(privateKeyFromStorage, 'password', (err, importedPrivateKey) => {
  67. if (err) {
  68. return reject(err);
  69. }
  70. this.privateKey = importedPrivateKey;
  71. // console.log(this.getPublicKeyString());
  72. // console.log(privateKeyFromStorage);
  73. resolve(true);
  74. });
  75. }
  76. }).catch(reject);
  77. });
  78. }
  79. getNonce() {
  80. return __awaiter(this, void 0, void 0, function* () {
  81. const nonce = yield this.webClient.request({
  82. method: 'GET',
  83. url: this.urlBase + '/bank/nonce'
  84. });
  85. return Number(nonce);
  86. });
  87. }
  88. getBalance() {
  89. return __awaiter(this, void 0, void 0, function* () {
  90. const nonce = yield this.getNonce();
  91. const retrieveRequest = yield this.makePlaintextPayload(JSON.stringify({
  92. _date: new Date().toISOString(),
  93. _nonce: nonce
  94. }));
  95. const topicURL = this.urlBase + '/bank/getbalance';
  96. const postResponse = yield this.webClient.requestJSON({
  97. body: retrieveRequest,
  98. method: 'POST',
  99. url: topicURL
  100. });
  101. return postResponse.balance;
  102. });
  103. }
  104. upload(params) {
  105. return __awaiter(this, void 0, void 0, function* () {
  106. const url = this.urlBase + '/bank/upload';
  107. const formData = {};
  108. if (params.fileData) {
  109. formData.file = {
  110. value: params.fileData,
  111. options: {
  112. filename: params.fileName
  113. }
  114. };
  115. }
  116. if (params.thumbFileData) {
  117. formData.thumb = {
  118. value: params.thumbFileData,
  119. options: {
  120. filename: params.thumbFileName
  121. }
  122. };
  123. }
  124. if (params.links) {
  125. formData.links = JSON.stringify(params.links);
  126. }
  127. for (const attr of ['title', 'text', 'type']) {
  128. if (params[attr] != null) {
  129. formData[attr] = params[attr];
  130. }
  131. }
  132. const uploadResponse = yield this.webClient.requestJSON({
  133. formData,
  134. method: 'POST',
  135. url
  136. });
  137. return uploadResponse.hash;
  138. });
  139. }
  140. appendBank(bankLink, itemHash) {
  141. return __awaiter(this, void 0, void 0, function* () {
  142. const payload = yield this.makePlaintextPayload(itemHash);
  143. const { address, topic } = this.parseBankLink(bankLink);
  144. const topicURL = this.urlBase + '/bank/private/' + encodeURIComponent(address) + '/' + encodeURIComponent(topic);
  145. yield this.webClient.requestJSON({
  146. body: payload,
  147. method: 'PUT',
  148. url: topicURL
  149. });
  150. });
  151. }
  152. getPriv() {
  153. if (!this.privateKey) {
  154. throw new Error('missing private key');
  155. }
  156. return this.privateKey;
  157. }
  158. makePlaintextPayload(message) {
  159. const messageBytes = new TextEncoder().encode(message);
  160. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  161. yield this.bootstrap();
  162. this.privateKey.sign(messageBytes, (signErr, signatureBytes) => __awaiter(this, void 0, void 0, function* () {
  163. if (signErr) {
  164. reject(signErr);
  165. return;
  166. }
  167. const publicDERBytes = this.privateKey.public.bytes;
  168. this.privateKey.id((idErr, pubHash) => {
  169. if (idErr) {
  170. reject(idErr);
  171. return;
  172. }
  173. const result = {
  174. date: new Date().toISOString(),
  175. msg: util_1.encodeHex(messageBytes),
  176. pub: util_1.encodeHex(publicDERBytes),
  177. pubHash,
  178. sig: util_1.encodeHex(signatureBytes),
  179. };
  180. // console.log('result', result, signatureBytes);
  181. resolve(result);
  182. });
  183. }));
  184. }));
  185. }
  186. parseBankLink(bankLink) {
  187. if (!bankLink.startsWith('bank:')) {
  188. throw new Error('address must start with bank:');
  189. }
  190. const [address, topic] = bankLink.substring(5).split('/');
  191. if (!address || !topic) {
  192. throw new Error('cannot parse address and topic');
  193. }
  194. return { address, topic };
  195. }
  196. }
  197. exports.BankClient = BankClient;
  198. //# sourceMappingURL=index.js.map