@prosopo/database 0.2.29 → 0.2.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ exports.Error = void 0;
4
+ (function(Error) {
5
+ Error["notAuthorised"] = "NotAuthorised";
6
+ Error["transferFailed"] = "TransferFailed";
7
+ Error["setCodeHashFailed"] = "SetCodeHashFailed";
8
+ Error["invalidDestination"] = "InvalidDestination";
9
+ Error["unknownMessage"] = "UnknownMessage";
10
+ Error["providerAccountExists"] = "ProviderAccountExists";
11
+ Error["providerExists"] = "ProviderExists";
12
+ Error["providerAccountDoesNotExist"] = "ProviderAccountDoesNotExist";
13
+ Error["providerDoesNotExist"] = "ProviderDoesNotExist";
14
+ Error["providerInsufficientFunds"] = "ProviderInsufficientFunds";
15
+ Error["providerInactive"] = "ProviderInactive";
16
+ Error["providerUrlUsed"] = "ProviderUrlUsed";
17
+ Error["dappExists"] = "DappExists";
18
+ Error["dappDoesNotExist"] = "DappDoesNotExist";
19
+ Error["dappInactive"] = "DappInactive";
20
+ Error["dappInsufficientFunds"] = "DappInsufficientFunds";
21
+ Error["captchaDataDoesNotExist"] = "CaptchaDataDoesNotExist";
22
+ Error["commitDoesNotExist"] = "CommitDoesNotExist";
23
+ Error["dappUserDoesNotExist"] = "DappUserDoesNotExist";
24
+ Error["noActiveProviders"] = "NoActiveProviders";
25
+ Error["datasetIdSolutionsSame"] = "DatasetIdSolutionsSame";
26
+ Error["codeNotFound"] = "CodeNotFound";
27
+ Error["unknown"] = "Unknown";
28
+ Error["invalidContract"] = "InvalidContract";
29
+ Error["invalidPayee"] = "InvalidPayee";
30
+ Error["invalidCaptchaStatus"] = "InvalidCaptchaStatus";
31
+ Error["noCorrectCaptcha"] = "NoCorrectCaptcha";
32
+ Error["notEnoughActiveProviders"] = "NotEnoughActiveProviders";
33
+ Error["providerFeeTooHigh"] = "ProviderFeeTooHigh";
34
+ Error["commitAlreadyExists"] = "CommitAlreadyExists";
35
+ Error["notAuthor"] = "NotAuthor";
36
+ })(exports.Error || (exports.Error = {}));
37
+ exports.LangError = void 0;
38
+ (function(LangError) {
39
+ LangError["couldNotReadInput"] = "CouldNotReadInput";
40
+ })(exports.LangError || (exports.LangError = {}));
41
+ exports.Payee = void 0;
42
+ (function(Payee) {
43
+ Payee["provider"] = "Provider";
44
+ Payee["dapp"] = "Dapp";
45
+ })(exports.Payee || (exports.Payee = {}));
46
+ exports.DappPayee = void 0;
47
+ (function(DappPayee) {
48
+ DappPayee["provider"] = "Provider";
49
+ DappPayee["dapp"] = "Dapp";
50
+ DappPayee["any"] = "Any";
51
+ })(exports.DappPayee || (exports.DappPayee = {}));
52
+ exports.GovernanceStatus = void 0;
53
+ (function(GovernanceStatus) {
54
+ GovernanceStatus["active"] = "Active";
55
+ GovernanceStatus["inactive"] = "Inactive";
56
+ })(exports.GovernanceStatus || (exports.GovernanceStatus = {}));
57
+ exports.CaptchaStatus = void 0;
58
+ (function(CaptchaStatus) {
59
+ CaptchaStatus["pending"] = "Pending";
60
+ CaptchaStatus["approved"] = "Approved";
61
+ CaptchaStatus["disapproved"] = "Disapproved";
62
+ })(exports.CaptchaStatus || (exports.CaptchaStatus = {}));
@@ -3,7 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const common = require("@prosopo/common");
4
4
  const types = require("@prosopo/types");
5
5
  const typesDatabase = require("@prosopo/types-database");
6
- const typesReturns = require("@prosopo/captcha-contract/types-returns");
6
+ const captcha = require("../contracts/captcha/dist/types-returns/captcha.cjs");
7
7
  const mongodb = require("mongodb");
8
8
  const is = require("@polkadot/util/is");
9
9
  const mongoose = require("mongoose");
@@ -56,13 +56,10 @@ class ProsopoDatabase extends common.AsyncFactory {
56
56
  };
57
57
  this.connection.once("open", resolve).on("error", (e) => {
58
58
  var _a;
59
+ this.logger.warn(`mongoose connection error`);
60
+ this.logger.error(e);
59
61
  if (attempt === MAX_RETRIES) {
60
- reject(
61
- new common.ProsopoDBError("DATABASE.CONNECT_ERROR", {
62
- context: { url: this.url, error: e, attempt },
63
- logger: this.logger
64
- })
65
- );
62
+ reject(new common.ProsopoEnvError(e, "DATABASE.CONNECT_ERROR", {}, this.url));
66
63
  } else {
67
64
  (_a = this.connection) == null ? void 0 : _a.removeAllListeners("error");
68
65
  }
@@ -81,10 +78,10 @@ class ProsopoDatabase extends common.AsyncFactory {
81
78
  }
82
79
  /** Close connection to the database */
83
80
  async close() {
84
- this.logger.debug(`Closing connection to ${this.url}`);
81
+ this.logger.info(`Closing connection to ${this.url}`);
85
82
  await new Promise(async (resolve, reject) => {
86
83
  mongoose.connection.close().then(() => {
87
- this.logger.debug(`Connection to ${this.url} closed`);
84
+ this.logger.info(`Connection to ${this.url} closed`);
88
85
  resolve();
89
86
  }).catch(reject);
90
87
  });
@@ -96,7 +93,7 @@ class ProsopoDatabase extends common.AsyncFactory {
96
93
  async storeDataset(dataset) {
97
94
  var _a, _b, _c;
98
95
  try {
99
- this.logger.debug(`Storing dataset in database`);
96
+ this.logger.info(`Storing dataset in database`);
100
97
  const parsedDataset = types.DatasetWithIdsAndTreeSchema.parse(dataset);
101
98
  const datasetDoc = {
102
99
  datasetId: parsedDataset.datasetId,
@@ -110,14 +107,14 @@ class ProsopoDatabase extends common.AsyncFactory {
110
107
  { $set: datasetDoc },
111
108
  { upsert: true }
112
109
  ));
113
- const captchaDocs = parsedDataset.captchas.map(({ solution, ...captcha }, index) => ({
114
- ...captcha,
110
+ const captchaDocs = parsedDataset.captchas.map(({ solution, ...captcha2 }, index) => ({
111
+ ...captcha2,
115
112
  datasetId: parsedDataset.datasetId,
116
113
  datasetContentId: parsedDataset.datasetContentId,
117
114
  index,
118
115
  solved: !!(solution == null ? void 0 : solution.length)
119
116
  }));
120
- this.logger.debug(`Inserting captcha records`);
117
+ this.logger.info(`Inserting captcha records`);
121
118
  if (captchaDocs.length) {
122
119
  await ((_b = this.tables) == null ? void 0 : _b.captcha.bulkWrite(
123
120
  captchaDocs.map((captchaDoc) => ({
@@ -129,15 +126,15 @@ class ProsopoDatabase extends common.AsyncFactory {
129
126
  }))
130
127
  ));
131
128
  }
132
- const captchaSolutionDocs = parsedDataset.captchas.filter(({ solution }) => solution == null ? void 0 : solution.length).map((captcha) => ({
133
- captchaId: captcha.captchaId,
134
- captchaContentId: captcha.captchaContentId,
135
- solution: captcha.solution,
136
- salt: captcha.salt,
129
+ const captchaSolutionDocs = parsedDataset.captchas.filter(({ solution }) => solution == null ? void 0 : solution.length).map((captcha2) => ({
130
+ captchaId: captcha2.captchaId,
131
+ captchaContentId: captcha2.captchaContentId,
132
+ solution: captcha2.solution,
133
+ salt: captcha2.salt,
137
134
  datasetId: parsedDataset.datasetId,
138
135
  datasetContentId: parsedDataset.datasetContentId
139
136
  }));
140
- this.logger.debug(`Inserting solution records`);
137
+ this.logger.info(`Inserting solution records`);
141
138
  if (captchaSolutionDocs.length) {
142
139
  await ((_c = this.tables) == null ? void 0 : _c.solution.bulkWrite(
143
140
  captchaSolutionDocs.map((captchaSolutionDoc) => ({
@@ -149,22 +146,11 @@ class ProsopoDatabase extends common.AsyncFactory {
149
146
  }))
150
147
  ));
151
148
  }
152
- this.logger.debug(`Dataset stored in database`);
149
+ this.logger.info(`Dataset stored in database`);
153
150
  } catch (err) {
154
- throw new common.ProsopoDBError("DATABASE.DATASET_LOAD_FAILED", {
155
- context: { failedFuncName: this.storeDataset.name, error: err },
156
- logger: this.logger
157
- });
151
+ throw new common.ProsopoEnvError(err, "DATABASE.DATASET_LOAD_FAILED");
158
152
  }
159
153
  }
160
- /** @description Get solutions for a dataset
161
- * @param {string} datasetId
162
- */
163
- async getSolutions(datasetId) {
164
- var _a;
165
- const docs = await ((_a = this.tables) == null ? void 0 : _a.solution.find({ datasetId }).lean());
166
- return docs ? docs : [];
167
- }
168
154
  /** @description Get a dataset from the database
169
155
  * @param {string} datasetId
170
156
  */
@@ -200,9 +186,7 @@ class ProsopoDatabase extends common.AsyncFactory {
200
186
  })
201
187
  };
202
188
  }
203
- throw new common.ProsopoDBError("DATABASE.DATASET_GET_FAILED", {
204
- context: { failedFuncName: this.getDataset.name, datasetId }
205
- });
189
+ throw new common.ProsopoEnvError("DATABASE.DATASET_GET_FAILED", void 0, {}, datasetId);
206
190
  }
207
191
  /**
208
192
  * @description Get random captchas that are solved or not solved
@@ -213,9 +197,7 @@ class ProsopoDatabase extends common.AsyncFactory {
213
197
  async getRandomCaptcha(solved, datasetId, size) {
214
198
  var _a;
215
199
  if (!is.isHex(datasetId)) {
216
- throw new common.ProsopoDBError("DATABASE.INVALID_HASH", {
217
- context: { failedFuncName: this.getRandomCaptcha.name, datasetId }
218
- });
200
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.getRandomCaptcha.name, {}, datasetId);
219
201
  }
220
202
  const sampleSize = size ? Math.abs(Math.trunc(size)) : 1;
221
203
  const cursor = (_a = this.tables) == null ? void 0 : _a.captcha.aggregate([
@@ -236,9 +218,16 @@ class ProsopoDatabase extends common.AsyncFactory {
236
218
  if (docs && docs.length) {
237
219
  return docs.map(({ _id, ...keepAttrs }) => keepAttrs);
238
220
  }
239
- throw new common.ProsopoDBError("DATABASE.CAPTCHA_GET_FAILED", {
240
- context: { failedFuncName: this.getRandomCaptcha.name, solved, datasetId, size }
241
- });
221
+ throw new common.ProsopoEnvError(
222
+ "DATABASE.CAPTCHA_GET_FAILED",
223
+ this.getRandomCaptcha.name,
224
+ {},
225
+ {
226
+ solved,
227
+ datasetId,
228
+ size
229
+ }
230
+ );
242
231
  }
243
232
  /**
244
233
  * @description Get captchas by id
@@ -251,28 +240,22 @@ class ProsopoDatabase extends common.AsyncFactory {
251
240
  if (docs && docs.length) {
252
241
  return docs.map(({ _id, ...keepAttrs }) => keepAttrs);
253
242
  }
254
- throw new common.ProsopoDBError("DATABASE.CAPTCHA_GET_FAILED", {
255
- context: { failedFuncName: this.getCaptchaById.name, captchaId }
256
- });
243
+ throw new common.ProsopoEnvError("DATABASE.CAPTCHA_GET_FAILED", this.getCaptchaById.name, {}, captchaId);
257
244
  }
258
245
  /**
259
246
  * @description Update a captcha
260
247
  * @param {Captcha} captcha
261
248
  * @param {string} datasetId the id of the data set
262
249
  */
263
- async updateCaptcha(captcha, datasetId) {
250
+ async updateCaptcha(captcha2, datasetId) {
264
251
  var _a;
265
252
  if (!is.isHex(datasetId)) {
266
- throw new common.ProsopoDBError("DATABASE.INVALID_HASH", {
267
- context: { failedFuncName: this.updateCaptcha.name, datasetId }
268
- });
253
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.updateCaptcha.name, {}, datasetId);
269
254
  }
270
255
  try {
271
- await ((_a = this.tables) == null ? void 0 : _a.captcha.updateOne({ datasetId }, { $set: captcha }, { upsert: false }));
256
+ await ((_a = this.tables) == null ? void 0 : _a.captcha.updateOne({ datasetId }, { $set: captcha2 }, { upsert: false }));
272
257
  } catch (err) {
273
- throw new common.ProsopoDBError("DATABASE.CAPTCHA_UPDATE_FAILED", {
274
- context: { failedFuncName: this.getDatasetDetails.name, error: err }
275
- });
258
+ throw new common.ProsopoEnvError(err);
276
259
  }
277
260
  }
278
261
  /**
@@ -288,17 +271,13 @@ class ProsopoDatabase extends common.AsyncFactory {
288
271
  async getDatasetDetails(datasetId) {
289
272
  var _a;
290
273
  if (!is.isHex(datasetId)) {
291
- throw new common.ProsopoDBError("DATABASE.INVALID_HASH", {
292
- context: { failedFuncName: this.getDatasetDetails.name, datasetId }
293
- });
274
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.getDatasetDetails.name, {}, datasetId);
294
275
  }
295
276
  const doc = await ((_a = this.tables) == null ? void 0 : _a.dataset.findOne({ datasetId }).lean());
296
277
  if (doc) {
297
278
  return doc;
298
279
  }
299
- throw new common.ProsopoDBError("DATABASE.DATASET_GET_FAILED", {
300
- context: { failedFuncName: this.getDatasetDetails.name, datasetId }
301
- });
280
+ throw new common.ProsopoEnvError("DATABASE.DATASET_GET_FAILED", this.getDatasetDetails.name, {}, datasetId);
302
281
  }
303
282
  /**
304
283
  * @description Store a Dapp User's captcha solution commitment
@@ -314,15 +293,15 @@ class ProsopoDatabase extends common.AsyncFactory {
314
293
  commitmentRecord,
315
294
  { upsert: true }
316
295
  ));
317
- const ops = captchas.map((captcha) => ({
296
+ const ops = captchas.map((captcha2) => ({
318
297
  updateOne: {
319
- filter: { commitmentId: commit.id, captchaId: captcha.captchaId },
298
+ filter: { commitmentId: commit.id, captchaId: captcha2.captchaId },
320
299
  update: {
321
300
  $set: {
322
- captchaId: captcha.captchaId,
323
- captchaContentId: captcha.captchaContentId,
324
- salt: captcha.salt,
325
- solution: captcha.solution,
301
+ captchaId: captcha2.captchaId,
302
+ captchaContentId: captcha2.captchaContentId,
303
+ salt: captcha2.salt,
304
+ solution: captcha2.solution,
326
305
  commitmentId: commit.id,
327
306
  processed: false
328
307
  }
@@ -379,9 +358,7 @@ class ProsopoDatabase extends common.AsyncFactory {
379
358
  async storeDappUserPending(userAccount, requestHash, salt, deadlineTimestamp, requestedAtBlock) {
380
359
  var _a;
381
360
  if (!is.isHex(requestHash)) {
382
- throw new common.ProsopoDBError("DATABASE.INVALID_HASH", {
383
- context: { failedFuncName: this.storeDappUserPending.name, requestHash }
384
- });
361
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.storeDappUserPending.name, {}, requestHash);
385
362
  }
386
363
  const pendingRecord = {
387
364
  accountId: userAccount,
@@ -399,17 +376,13 @@ class ProsopoDatabase extends common.AsyncFactory {
399
376
  async getDappUserPending(requestHash) {
400
377
  var _a;
401
378
  if (!is.isHex(requestHash)) {
402
- throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", {
403
- context: { failedFuncName: this.getDappUserPending.name, requestHash }
404
- });
379
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.getDappUserPending.name, {}, requestHash);
405
380
  }
406
381
  const doc = await ((_a = this.tables) == null ? void 0 : _a.pending.findOne({ requestHash }).lean());
407
382
  if (doc) {
408
383
  return doc;
409
384
  }
410
- throw new common.ProsopoEnvError("DATABASE.PENDING_RECORD_NOT_FOUND", {
411
- context: { failedFuncName: this.getDappUserPending.name, requestHash }
412
- });
385
+ throw new common.ProsopoEnvError("DATABASE.PENDING_RECORD_NOT_FOUND", this.getDappUserPending.name);
413
386
  }
414
387
  /**
415
388
  * @description Update a Dapp User's pending record
@@ -417,9 +390,7 @@ class ProsopoDatabase extends common.AsyncFactory {
417
390
  async updateDappUserPendingStatus(userAccount, requestHash, approve) {
418
391
  var _a;
419
392
  if (!is.isHex(requestHash)) {
420
- throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", {
421
- context: { failedFuncName: this.updateDappUserPendingStatus.name, requestHash }
422
- });
393
+ throw new common.ProsopoEnvError("DATABASE.INVALID_HASH", this.updateDappUserPendingStatus.name, {}, requestHash);
423
394
  }
424
395
  await ((_a = this.tables) == null ? void 0 : _a.pending.updateOne(
425
396
  { requestHash },
@@ -486,14 +457,17 @@ class ProsopoDatabase extends common.AsyncFactory {
486
457
  if (docs && docs.length) {
487
458
  return docs[0]._id;
488
459
  }
489
- throw new common.ProsopoDBError("DATABASE.DATASET_WITH_SOLUTIONS_GET_FAILED");
460
+ throw new common.ProsopoEnvError("DATABASE.DATASET_WITH_SOLUTIONS_GET_FAILED");
490
461
  }
491
462
  async getRandomSolvedCaptchasFromSingleDataset(datasetId, size) {
492
463
  var _a;
493
464
  if (!is.isHex(datasetId)) {
494
- throw new common.ProsopoDBError("DATABASE.INVALID_HASH", {
495
- context: { failedFuncName: this.getRandomSolvedCaptchasFromSingleDataset.name, datasetId }
496
- });
465
+ throw new common.ProsopoEnvError(
466
+ "DATABASE.INVALID_HASH",
467
+ this.getRandomSolvedCaptchasFromSingleDataset.name,
468
+ {},
469
+ datasetId
470
+ );
497
471
  }
498
472
  const sampleSize = size ? Math.abs(Math.trunc(size)) : 1;
499
473
  const cursor = (_a = this.tables) == null ? void 0 : _a.solution.aggregate([
@@ -511,9 +485,7 @@ class ProsopoDatabase extends common.AsyncFactory {
511
485
  if (docs && docs.length) {
512
486
  return docs;
513
487
  }
514
- throw new common.ProsopoDBError("DATABASE.SOLUTION_GET_FAILED", {
515
- context: { failedFuncName: this.getRandomSolvedCaptchasFromSingleDataset.name, datasetId, size }
516
- });
488
+ throw new common.ProsopoEnvError("DATABASE.SOLUTION_GET_FAILED");
517
489
  }
518
490
  /**
519
491
  * @description Get dapp user solution by ID
@@ -531,9 +503,7 @@ class ProsopoDatabase extends common.AsyncFactory {
531
503
  if (doc) {
532
504
  return doc;
533
505
  }
534
- throw new common.ProsopoDBError("DATABASE.SOLUTION_GET_FAILED", {
535
- context: { failedFuncName: this.getCaptchaById.name, commitmentId }
536
- });
506
+ throw new common.ProsopoEnvError("DATABASE.SOLUTION_GET_FAILED", this.getCaptchaById.name, {}, commitmentId);
537
507
  }
538
508
  /**
539
509
  * @description Get dapp user commitment by user account
@@ -563,11 +533,11 @@ class ProsopoDatabase extends common.AsyncFactory {
563
533
  try {
564
534
  await ((_b = (_a = this.tables) == null ? void 0 : _a.commitment) == null ? void 0 : _b.findOneAndUpdate(
565
535
  { id: commitmentId },
566
- { $set: { status: typesReturns.CaptchaStatus.approved } },
536
+ { $set: { status: captcha.CaptchaStatus.approved } },
567
537
  { upsert: false }
568
538
  ).lean());
569
539
  } catch (err) {
570
- throw new common.ProsopoDBError("DATABASE.SOLUTION_APPROVE_FAILED", { context: { error: err, commitmentId } });
540
+ throw new common.ProsopoEnvError(err, "DATABASE.SOLUTION_APPROVE_FAILED", {}, commitmentId);
571
541
  }
572
542
  }
573
543
  /**
@@ -579,7 +549,7 @@ class ProsopoDatabase extends common.AsyncFactory {
579
549
  try {
580
550
  await ((_b = (_a = this.tables) == null ? void 0 : _a.usersolution) == null ? void 0 : _b.updateMany({ captchaId: { $in: captchaIds } }, { $set: { processed: true } }, { upsert: false }).lean());
581
551
  } catch (err) {
582
- throw new common.ProsopoDBError("DATABASE.SOLUTION_FLAG_FAILED", { context: { error: err, captchaIds } });
552
+ throw new common.ProsopoEnvError(err, "DATABASE.SOLUTION_FLAG_FAILED", {}, captchaIds);
583
553
  }
584
554
  }
585
555
  /**
@@ -592,7 +562,7 @@ class ProsopoDatabase extends common.AsyncFactory {
592
562
  const distinctCommitmentIds = [...new Set(commitmentIds)];
593
563
  await ((_b = (_a = this.tables) == null ? void 0 : _a.commitment) == null ? void 0 : _b.updateMany({ id: { $in: distinctCommitmentIds } }, { $set: { processed: true } }, { upsert: false }).lean());
594
564
  } catch (err) {
595
- throw new common.ProsopoDBError("DATABASE.COMMITMENT_FLAG_FAILED", { context: { error: err, commitmentIds } });
565
+ throw new common.ProsopoEnvError(err, "DATABASE.COMMITMENT_FLAG_FAILED", {}, commitmentIds);
596
566
  }
597
567
  }
598
568
  /**
@@ -605,7 +575,7 @@ class ProsopoDatabase extends common.AsyncFactory {
605
575
  const distinctCommitmentIds = [...new Set(commitmentIds)];
606
576
  await ((_b = (_a = this.tables) == null ? void 0 : _a.commitment) == null ? void 0 : _b.updateMany({ id: { $in: distinctCommitmentIds } }, { $set: { batched: true } }, { upsert: false }).lean());
607
577
  } catch (err) {
608
- throw new common.ProsopoDBError("DATABASE.COMMITMENT_FLAG_FAILED", { context: { error: err, commitmentIds } });
578
+ throw new common.ProsopoEnvError(err, "DATABASE.COMMITMENT_FLAG_FAILED", {}, commitmentIds);
609
579
  }
610
580
  }
611
581
  /**
@@ -1,7 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const index = require("./databases/index.cjs");
4
- require("./eventsDatabase/index.cjs");
5
- const eventsDatabase = require("./eventsDatabase/eventsDatabase.cjs");
6
4
  exports.Databases = index.Databases;
7
- exports.saveCaptchaEvent = eventsDatabase.saveCaptchaEvent;
@@ -1,3 +1,3 @@
1
1
  import { StoredEvents } from '@prosopo/types';
2
- export declare const saveCaptchaEvent: (events: StoredEvents, accountId: string, atlasUri: string) => Promise<void>;
2
+ export declare const saveCaptchaEvent: (events: StoredEvents, accountId: string, atlasUri: string) => Promise<unknown>;
3
3
  //# sourceMappingURL=eventsDatabase.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"eventsDatabase.d.ts","sourceRoot":"","sources":["../../src/eventsDatabase/eventsDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AA8C7C,eAAO,MAAM,gBAAgB,WAAkB,YAAY,aAAa,MAAM,YAAY,MAAM,kBAc/F,CAAA"}
1
+ {"version":3,"file":"eventsDatabase.d.ts","sourceRoot":"","sources":["../../src/eventsDatabase/eventsDatabase.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,YAAY,EAAE,MAAM,gBAAgB,CAAA;AA+ChE,eAAO,MAAM,gBAAgB,WAAkB,YAAY,aAAa,MAAM,YAAY,MAAM,qBAiC/F,CAAA"}
@@ -1,4 +1,7 @@
1
+ import { ProsopoDBError, getLoggerDefault } from '@prosopo/common';
1
2
  import mongoose from 'mongoose';
3
+ const logger = getLoggerDefault();
4
+ const MAX_RETRIES = 3;
2
5
  const captchaEventSchema = new mongoose.Schema({
3
6
  touchEvents: [
4
7
  {
@@ -18,34 +21,55 @@ const captchaEventSchema = new mongoose.Schema({
18
21
  {
19
22
  key: String,
20
23
  timestamp: Number,
21
- isShiftKey: Boolean,
22
- isCtrlKey: Boolean,
24
+ isShiftKey: { type: Boolean, required: false },
25
+ isCtrlKey: { type: Boolean, required: false },
23
26
  },
24
27
  ],
25
28
  accountId: String,
26
29
  });
27
- const CaptchaEvent = mongoose.model('CaptchaEvent', captchaEventSchema);
30
+ let CaptchaEvent;
31
+ try {
32
+ CaptchaEvent = mongoose.model('CaptchaEvent');
33
+ }
34
+ catch (error) {
35
+ CaptchaEvent = mongoose.model('CaptchaEvent', captchaEventSchema);
36
+ }
28
37
  const addCaptchaEventRecord = async (record) => {
29
38
  try {
30
39
  const newRecord = new CaptchaEvent(record);
31
40
  await newRecord.save();
32
- console.log('Record added successfully');
41
+ logger.info('Record added successfully');
33
42
  }
34
43
  catch (error) {
35
- console.error('Error adding record to the database:', error);
44
+ logger.error('Error adding record to the database:', error);
36
45
  }
37
46
  };
38
47
  export const saveCaptchaEvent = async (events, accountId, atlasUri) => {
39
- await mongoose
40
- .connect(atlasUri)
41
- .then(() => console.log('Connected to MongoDB Atlas'))
42
- .catch((err) => console.error('Error connecting to MongoDB:', err));
43
- const captchaEventData = {
44
- ...events,
45
- accountId,
46
- };
47
- addCaptchaEventRecord(captchaEventData)
48
- .then(() => console.log('Captcha event data saved'))
49
- .catch((error) => console.error('Error saving captcha event data:', error));
48
+ return new Promise((resolve, reject) => {
49
+ const connection = mongoose.createConnection(atlasUri);
50
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
51
+ connection.once('open', resolve).on('error', (e) => {
52
+ logger.warn(`Mongoose connection error`);
53
+ logger.error(e);
54
+ if (attempt === MAX_RETRIES) {
55
+ reject(new ProsopoDBError('DATABASE.CONNECT_ERROR', {
56
+ context: { failedFuncName: saveCaptchaEvent.name, db: 'events database' },
57
+ logger: logger,
58
+ }));
59
+ }
60
+ else {
61
+ connection?.removeAllListeners('error');
62
+ }
63
+ });
64
+ }
65
+ const captchaEventData = {
66
+ ...events,
67
+ accountId,
68
+ };
69
+ addCaptchaEventRecord(captchaEventData)
70
+ .then(() => logger.info('Captcha event data saved'))
71
+ .catch((error) => logger.error('Error saving captcha event data:', error))
72
+ .finally(() => connection.close());
73
+ });
50
74
  };
51
75
  //# sourceMappingURL=eventsDatabase.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"eventsDatabase.js","sourceRoot":"","sources":["../../src/eventsDatabase/eventsDatabase.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,UAAU,CAAA;AAE/B,MAAM,kBAAkB,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC;IAC3C,WAAW,EAAE;QACT;YACI,CAAC,EAA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BAAqB,CAAC,gBAAgB,CAAC;aAClC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;aACnD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;aACzE,OAAO,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAA;IAC1C,CAAC,CAAC,CAAA;AACN,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prosopo/database",
3
- "version": "0.2.29",
3
+ "version": "0.2.32",
4
4
  "description": "Prosopo database plugins for provider",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -37,11 +37,11 @@
37
37
  "homepage": "https://github.com/prosopo/captcha#readme",
38
38
  "dependencies": {
39
39
  "@polkadot/util": "^12.5.1",
40
- "@prosopo/captcha-contract": "0.2.29",
41
- "@prosopo/common": "0.2.29",
42
- "@prosopo/config": "0.2.29",
43
- "@prosopo/types": "0.2.29",
44
- "@prosopo/types-database": "0.2.29",
40
+ "@prosopo/captcha-contract": "0.2.32",
41
+ "@prosopo/common": "0.2.32",
42
+ "@prosopo/config": "0.2.32",
43
+ "@prosopo/types": "0.2.32",
44
+ "@prosopo/types-database": "0.2.32",
45
45
  "mongodb": "5.8.0",
46
46
  "mongodb-memory-server": "^8.7.2",
47
47
  "mongoose": "^7.3.3"
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const mongoose = require("mongoose");
4
- const captchaEventSchema = new mongoose.Schema({
5
- touchEvents: [
6
- {
7
- x: Number,
8
- y: Number,
9
- timestamp: Number
10
- }
11
- ],
12
- mouseEvents: [
13
- {
14
- x: Number,
15
- y: Number,
16
- timestamp: Number
17
- }
18
- ],
19
- keyboardEvents: [
20
- {
21
- key: String,
22
- timestamp: Number,
23
- isShiftKey: Boolean,
24
- isCtrlKey: Boolean
25
- }
26
- ],
27
- accountId: String
28
- });
29
- const CaptchaEvent = mongoose.model("CaptchaEvent", captchaEventSchema);
30
- const addCaptchaEventRecord = async (record) => {
31
- try {
32
- const newRecord = new CaptchaEvent(record);
33
- await newRecord.save();
34
- console.log("Record added successfully");
35
- } catch (error) {
36
- console.error("Error adding record to the database:", error);
37
- }
38
- };
39
- const saveCaptchaEvent = async (events, accountId, atlasUri) => {
40
- await mongoose.connect(atlasUri).then(() => console.log("Connected to MongoDB Atlas")).catch((err) => console.error("Error connecting to MongoDB:", err));
41
- const captchaEventData = {
42
- ...events,
43
- accountId
44
- };
45
- addCaptchaEventRecord(captchaEventData).then(() => console.log("Captcha event data saved")).catch((error) => console.error("Error saving captcha event data:", error));
46
- };
47
- exports.saveCaptchaEvent = saveCaptchaEvent;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const eventsDatabase = require("./eventsDatabase.cjs");
4
- exports.saveCaptchaEvent = eventsDatabase.saveCaptchaEvent;