wingbot-mongodb 2.17.0 → 2.20.0

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.
@@ -4,17 +4,19 @@
4
4
  'use strict';
5
5
 
6
6
  const mongodb = require('mongodb'); // eslint-disable-line no-unused-vars
7
+ const crypto = require('crypto');
7
8
 
8
- /** @typedef {import('mongodb').IndexOptions} IndexOptions */
9
+ /** @typedef {import('mongodb/lib/db')} Db */
10
+ /** @typedef {import('mongodb/lib/collection')} Collection */
9
11
 
10
12
  class BaseStorage {
11
13
 
12
14
  /**
13
15
  *
14
- * @param {mongodb.Db|{():Promise<mongodb.Db>}} mongoDb
16
+ * @param {Db|{():Promise<Db>}} mongoDb
15
17
  * @param {string} collectionName
16
18
  * @param {{error:Function,log:Function}} [log] - console like logger
17
- * @param {boolean} isCosmo
19
+ * @param {boolean} [isCosmo]
18
20
  * @example
19
21
  *
20
22
  * const { BaseStorage } = require('winbot-mongodb');
@@ -47,18 +49,34 @@ class BaseStorage {
47
49
  this._log = log;
48
50
 
49
51
  /**
50
- * @type {Promise<mongodb.Collection>}
52
+ * @type {Collection|Promise<Collection>}
51
53
  */
52
54
  this._collection = null;
53
55
 
54
56
  this._indexes = [];
57
+
58
+ this.ignoredSignatureKeys = ['_id', 'sign'];
59
+ this._secret = null;
60
+
61
+ this.systemIndexes = ['_id_', '_id'];
62
+
63
+ this._fixtures = [];
64
+ }
65
+
66
+ /**
67
+ * Insert defalt document to DB
68
+ *
69
+ * @param {...any} objects
70
+ */
71
+ addFixtureDoc (...objects) {
72
+ this._fixtures.push(...objects);
55
73
  }
56
74
 
57
75
  /**
58
76
  * Add custom indexing rule
59
77
  *
60
78
  * @param {object} index
61
- * @param {IndexOptions} options
79
+ * @param {mongodb.IndexOptions} options
62
80
  */
63
81
  addIndex (index, options) {
64
82
  if (!options.name) {
@@ -78,6 +96,7 @@ class BaseStorage {
78
96
  let collection;
79
97
 
80
98
  if (this._isCosmo) {
99
+ // @ts-ignore
81
100
  const collections = await db.collections();
82
101
 
83
102
  collection = collections
@@ -103,7 +122,7 @@ class BaseStorage {
103
122
  /**
104
123
  * Returns the collection to operate with
105
124
  *
106
- * @returns {Promise<mongodb.Collection>}
125
+ * @returns {Promise<Collection>}
107
126
  */
108
127
  async _getCollection () {
109
128
  if (this._collection === null) {
@@ -128,29 +147,85 @@ class BaseStorage {
128
147
  existing = [];
129
148
  }
130
149
 
131
- await Promise.all(existing
132
- .filter((e) => !['_id_', '_id'].includes(e.name)
150
+ await existing
151
+ .filter((e) => !this.systemIndexes.includes(e.name)
133
152
  && !indexes.some((i) => e.name === i.options.name))
134
- .map((e) => {
153
+ .reduce((p, e) => {
135
154
  // eslint-disable-next-line no-console
136
155
  this._log.log(`dropping index ${e.name}`);
137
- return collection.dropIndex(e.name)
156
+ return p
157
+ .then(() => collection.dropIndex(e.name))
138
158
  .catch((err) => {
139
159
  // eslint-disable-next-line no-console
140
160
  this._log.error(`dropping index ${e.name} FAILED`, err);
141
161
  });
142
- }));
162
+ }, Promise.resolve());
143
163
 
144
- await Promise.all(indexes
164
+ const updated = await indexes
145
165
  .filter((i) => !existing.some((e) => e.name === i.options.name))
146
- .map((i) => collection
147
- .createIndex(i.index, i.options)
148
- // @ts-ignore
166
+ .reduce((p, i) => {
167
+ this._log.log(`creating index ${i.name}`);
168
+ return p
169
+ .then(() => collection.createIndex(i.index, i.options))
170
+ .catch((e) => {
171
+ this._log.error(`failed to create index ${i.options.name} on ${collection.collectionName}`, e);
172
+ })
173
+ .then(() => true);
174
+ }, Promise.resolve(false));
175
+
176
+ if (updated || existing.every((i) => this.systemIndexes.includes(i.name))) {
177
+ // upsert fixtures
178
+
179
+ await this._fixtures.reduce((p, o) => p
180
+ .then(() => collection.insertOne(o))
181
+ .then(() => this._log.log(`DB> Inserted fixture doc to "${this._collectionName}"`))
149
182
  .catch((e) => {
150
- this._log.error(`failed to create index ${i.options.name} on ${collection.collectionName}`, e);
151
- })));
183
+ if (e.code !== 11000) {
184
+ this._log.error(`DB> failed to insert fixture doc to "${this._collectionName}"`, e);
185
+ }
186
+ }),
187
+ Promise.resolve());
188
+ }
152
189
  }
153
190
 
191
+ async _sign (object) {
192
+ if (!this._secret) {
193
+ return object;
194
+ }
195
+ const secret = await Promise.resolve(this._secret);
196
+ const objToSign = this._objectToSign(object);
197
+ const sign = this._signWithSecret(objToSign, secret);
198
+
199
+ return Object.assign(objToSign, {
200
+ sign
201
+ });
202
+ }
203
+
204
+ _objectToSign (object) {
205
+ const entries = Object.keys(object)
206
+ .filter((key) => !this.ignoredSignatureKeys.includes(key));
207
+
208
+ entries.sort();
209
+
210
+ return entries.reduce((o, key) => {
211
+ let val = object[key];
212
+ if (val instanceof Date) {
213
+ val = val.toISOString();
214
+ }
215
+ return Object.assign(o, { [key]: val });
216
+ }, {});
217
+ }
218
+
219
+ _signWithSecret (objToSign, secret, previous = null) {
220
+ const h = crypto.createHmac('sha3-224', secret)
221
+ .update(JSON.stringify(objToSign));
222
+
223
+ if (previous) {
224
+ h.update(previous);
225
+ }
226
+
227
+ return h.digest('base64');
228
+ }
154
229
  }
155
230
 
156
231
  module.exports = BaseStorage;
@@ -3,8 +3,16 @@
3
3
  */
4
4
  'use strict';
5
5
 
6
- const mongodb = require('mongodb'); // eslint-disable-line no-unused-vars
7
- const { apiAuthorizer } = require('wingbot');
6
+ let apiAuthorizer = () => false;
7
+ try {
8
+ // @ts-ignore
9
+ ({ apiAuthorizer } = module.require('wingbot'));
10
+ } catch (e) {
11
+ // noop
12
+ }
13
+
14
+ /** @typedef {import('mongodb/lib/db')} Db */
15
+ /** @typedef {import('mongodb/lib/collection')} Collection */
8
16
 
9
17
  const CONFIG_ID = 'config';
10
18
 
@@ -17,7 +25,7 @@ class BotConfigStorage {
17
25
 
18
26
  /**
19
27
  *
20
- * @param {mongodb.Db|{():Promise<mongodb.Db>}} mongoDb
28
+ * @param {Db|{():Promise<Db>}} mongoDb
21
29
  * @param {string} collectionName
22
30
  */
23
31
  constructor (mongoDb, collectionName = 'botconfig') {
@@ -25,13 +33,13 @@ class BotConfigStorage {
25
33
  this._collectionName = collectionName;
26
34
 
27
35
  /**
28
- * @type {mongodb.Collection}
36
+ * @type {Collection}
29
37
  */
30
38
  this._collection = null;
31
39
  }
32
40
 
33
41
  /**
34
- * @returns {Promise<mongodb.Collection>}
42
+ * @returns {Promise<Collection>}
35
43
  */
36
44
  async _getCollection () {
37
45
  if (this._collection === null) {
@@ -56,6 +64,7 @@ class BotConfigStorage {
56
64
  const storage = this;
57
65
  return {
58
66
  async updateBot (args, ctx) {
67
+ // @ts-ignore
59
68
  if (!apiAuthorizer(args, ctx, acl)) {
60
69
  return null;
61
70
  }
@@ -74,6 +83,7 @@ class BotConfigStorage {
74
83
  async invalidateConfig () {
75
84
  const c = await this._getCollection();
76
85
 
86
+ // @ts-ignore
77
87
  return c.deleteOne({ _id: CONFIG_ID });
78
88
  }
79
89
 
@@ -95,25 +105,36 @@ class BotConfigStorage {
95
105
  /**
96
106
  * @template T
97
107
  * @param {T} newConfig
108
+ * @param {string} [id]
98
109
  * @returns {Promise<T>}
99
110
  */
100
- async updateConfig (newConfig) {
111
+ async updateConfig (newConfig, id = CONFIG_ID) {
101
112
  Object.assign(newConfig, { timestamp: Date.now() });
102
113
 
103
- const c = await this._getCollection();
104
-
105
- await c.replaceOne({ _id: CONFIG_ID }, newConfig, { upsert: true });
114
+ await this.setConfig(id, newConfig);
106
115
 
107
116
  return newConfig;
108
117
  }
109
118
 
110
119
  /**
120
+ *
121
+ * @param {string} id
122
+ * @param {object} newConfig
123
+ */
124
+ async setConfig (id, newConfig) {
125
+ const c = await this._getCollection();
126
+
127
+ await c.replaceOne({ _id: id }, newConfig, { upsert: true });
128
+ }
129
+
130
+ /**
131
+ * @param {string} [id]
111
132
  * @returns {Promise<object | null>}
112
133
  */
113
- async getConfig () {
134
+ async getConfig (id = CONFIG_ID) {
114
135
  const c = await this._getCollection();
115
136
 
116
- return c.findOne({ _id: CONFIG_ID }, { projection: { _id: 0 } });
137
+ return c.findOne({ _id: id }, { projection: { _id: 0 } });
117
138
  }
118
139
 
119
140
  }
@@ -131,7 +131,7 @@ class BotTokenStorage {
131
131
  }
132
132
  }, {
133
133
  upsert: true,
134
- returnOriginal: false
134
+ returnDocument: 'after'
135
135
  });
136
136
 
137
137
  res = res.value;
@@ -3,12 +3,13 @@
3
3
  */
4
4
  'use strict';
5
5
 
6
- const mongodb = require('mongodb'); // eslint-disable-line no-unused-vars
7
6
  const BaseStorage = require('./BaseStorage');
8
7
 
9
8
  const PAGE_SENDER_TIMESTAMP = 'pageId_1_senderId_1_timestamp_-1';
10
9
  const TIMESTAMP = 'timestamp_1';
11
10
 
11
+ /** @typedef {import('mongodb/lib/db')} Db */
12
+
12
13
  /**
13
14
  * Storage for conversation logs
14
15
  *
@@ -18,12 +19,13 @@ class ChatLogStorage extends BaseStorage {
18
19
 
19
20
  /**
20
21
  *
21
- * @param {mongodb.Db|{():Promise<mongodb.Db>}} mongoDb
22
+ * @param {Db|{():Promise<Db>}} mongoDb
22
23
  * @param {string} collectionName
23
24
  * @param {{error:Function,log:Function}} [log] - console like logger
24
- * @param {boolean} isCosmo
25
+ * @param {boolean} [isCosmo]
26
+ * @param {string|Promise<string>} [secret]
25
27
  */
26
- constructor (mongoDb, collectionName = 'chatlogs', log = console, isCosmo = false) {
28
+ constructor (mongoDb, collectionName = 'chatlogs', log = console, isCosmo = false, secret = null) {
27
29
  super(mongoDb, collectionName, log, isCosmo);
28
30
 
29
31
  this.addIndex({
@@ -43,6 +45,7 @@ class ChatLogStorage extends BaseStorage {
43
45
  }
44
46
 
45
47
  this.muteErrors = true;
48
+ this._secret = secret;
46
49
  }
47
50
 
48
51
  /**
@@ -54,6 +57,7 @@ class ChatLogStorage extends BaseStorage {
54
57
  * @param {number} [limit]
55
58
  * @param {number} [endAt] - iterate backwards to history
56
59
  * @param {number} [startAt] - iterate forward to last interaction
60
+ * @returns {Promise<object[]>}
57
61
  */
58
62
  async getInteractions (senderId, pageId, limit = 10, endAt = null, startAt = null) {
59
63
  const c = await this._getCollection();
@@ -80,14 +84,33 @@ class ChatLogStorage extends BaseStorage {
80
84
  const res = await c.find(q)
81
85
  .limit(limit)
82
86
  .sort({ timestamp: orderBackwards ? 1 : -1 })
83
- .project({ _id: 0, time: 0 })
87
+ .project({ _id: 0 })
84
88
  .toArray();
85
89
 
86
90
  if (!orderBackwards) {
87
91
  res.reverse();
88
92
  }
89
93
 
90
- return res;
94
+ if (!this._secret) {
95
+ return res.map((r) => Object.assign(r, { ok: null }));
96
+ }
97
+
98
+ const secret = await Promise.resolve(this._secret);
99
+
100
+ return res.map((r) => {
101
+ const {
102
+ sign,
103
+ ...log
104
+ } = r;
105
+ const objToSign = this._objectToSign(log);
106
+ const compare = this._signWithSecret(objToSign, secret);
107
+ const ok = compare === sign;
108
+ if (!ok) {
109
+ this._log.error(`ChatLog: found wrong signature at pageId: "${r.pageId}", senderId: "${r.senderId}", at: ${r.timestamp}`, r);
110
+ }
111
+
112
+ return Object.assign(log, { ok });
113
+ });
91
114
  }
92
115
 
93
116
  /**
@@ -102,22 +125,38 @@ class ChatLogStorage extends BaseStorage {
102
125
  log (senderId, responses = [], request = {}, metadata = {}) {
103
126
  const log = {
104
127
  senderId,
105
- time: new Date(request.timestamp || Date.now()),
106
128
  request,
107
- responses
129
+ responses,
130
+ ...metadata
108
131
  };
109
132
 
110
- Object.assign(log, metadata);
111
-
112
- return this._getCollection()
113
- .then((c) => c.insertOne(log))
114
- .catch((err) => {
115
- this._log.error('Failed to store chat log', err, log);
133
+ return this._storeLog(log);
134
+ }
116
135
 
117
- if (!this.muteErrors) {
118
- throw err;
119
- }
136
+ async _storeLog (event) {
137
+ let log = event;
138
+ if (!event.timestamp) {
139
+ Object.assign(event, {
140
+ timestamp: event.request.timestamp || Date.now()
141
+ });
142
+ }
143
+ if (typeof event.pageId === 'undefined') {
144
+ Object.assign(event, {
145
+ pageId: null
120
146
  });
147
+ }
148
+ try {
149
+ const c = await this._getCollection();
150
+ log = await this._sign(log);
151
+ // @ts-ignore
152
+ await c.insertOne(log);
153
+ } catch (e) {
154
+ this._log.error('Failed to store chat log', e, log);
155
+
156
+ if (!this.muteErrors) {
157
+ throw e;
158
+ }
159
+ }
121
160
  }
122
161
 
123
162
  /**
@@ -135,23 +174,15 @@ class ChatLogStorage extends BaseStorage {
135
174
  error (err, senderId, responses = [], request = {}, metadata = {}) {
136
175
  const log = {
137
176
  senderId,
138
- time: new Date(request.timestamp || Date.now()),
139
177
  request,
140
178
  responses,
141
- err: `${err}`
179
+ err: `${err}`,
180
+ ...metadata
142
181
  };
143
182
 
144
183
  Object.assign(log, metadata);
145
184
 
146
- return this._getCollection()
147
- .then((c) => c.insertOne(log))
148
- .catch((storeError) => {
149
- this._log.error('Failed to store chat log', storeError, log);
150
-
151
- if (!this.muteErrors) {
152
- throw storeError;
153
- }
154
- });
185
+ return this._storeLog(log);
155
186
  }
156
187
 
157
188
  }
@@ -381,7 +381,7 @@ class NotificationsStorage {
381
381
  }
382
382
  }, {
383
383
  sort: { enqueue: 1 },
384
- returnOriginal: false
384
+ returnDocument: 'after'
385
385
  });
386
386
  if (found.value) {
387
387
  pop.push(this._mapGenericObject(found.value));
@@ -475,7 +475,7 @@ class NotificationsStorage {
475
475
  }, {
476
476
  $set: data
477
477
  }, {
478
- returnOriginal: false
478
+ returnDocument: 'after'
479
479
  });
480
480
 
481
481
  return this._mapGenericObject(res.value);
@@ -565,7 +565,7 @@ class NotificationsStorage {
565
565
  [eventType]: ts
566
566
  }
567
567
  }, {
568
- returnOriginal: false
568
+ returnDocument: 'after'
569
569
  }))
570
570
  );
571
571
 
@@ -602,7 +602,7 @@ class NotificationsStorage {
602
602
  id: campaign.id
603
603
  }, update, {
604
604
  upsert: true,
605
- returnOriginal: false
605
+ returnDocument: 'after'
606
606
  });
607
607
  ret = this._mapCampaign(res.value);
608
608
  } else {
@@ -661,7 +661,7 @@ class NotificationsStorage {
661
661
  }, {
662
662
  $set: data
663
663
  }, {
664
- returnOriginal: false
664
+ returnDocument: 'after'
665
665
  });
666
666
 
667
667
  return this._mapCampaign(res.value);
@@ -681,7 +681,7 @@ class NotificationsStorage {
681
681
  }, {
682
682
  $set: { startAt: null }
683
683
  }, {
684
- returnOriginal: true
684
+ returnDocument: 'before'
685
685
  });
686
686
 
687
687
  return this._mapCampaign(res.value);
@@ -807,7 +807,7 @@ class NotificationsStorage {
807
807
  }, {
808
808
  $pull: { subs: tag }
809
809
  }, {
810
- returnOriginal: false
810
+ returnDocument: 'after'
811
811
  });
812
812
 
813
813
  if (res.value) {
@@ -36,7 +36,7 @@ class StateStorage extends BaseStorage {
36
36
  * @param {{error:Function,log:Function}} [log] - console like logger
37
37
  * @param {boolean} isCosmo
38
38
  */
39
- constructor (mongoDb, collectionName = 'chatlogs', log = console, isCosmo = false) {
39
+ constructor (mongoDb, collectionName = 'states', log = console, isCosmo = false) {
40
40
  super(mongoDb, collectionName, log, isCosmo);
41
41
 
42
42
  this.addIndex(
@@ -115,7 +115,7 @@ class StateStorage extends BaseStorage {
115
115
  $set
116
116
  }, {
117
117
  upsert: true,
118
- returnOriginal: false,
118
+ returnDocument: 'after',
119
119
  projection: {
120
120
  _id: 0
121
121
  }
package/src/main.js CHANGED
@@ -9,6 +9,7 @@ const BotTokenStorage = require('./BotTokenStorage');
9
9
  const ChatLogStorage = require('./ChatLogStorage');
10
10
  const BotConfigStorage = require('./BotConfigStorage');
11
11
  const AttachmentCache = require('./AttachmentCache');
12
+ const AuditLogStorage = require('./AuditLogStorage');
12
13
  const NotificationsStorage = require('./NotificationsStorage');
13
14
 
14
15
  module.exports = {
@@ -18,5 +19,6 @@ module.exports = {
18
19
  ChatLogStorage,
19
20
  BotConfigStorage,
20
21
  AttachmentCache,
21
- NotificationsStorage
22
+ NotificationsStorage,
23
+ AuditLogStorage
22
24
  };