@tiledesk/tiledesk-server 3.3.5 → 3.5.1

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.
Files changed (75) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/app.js +7 -0
  3. package/deploynew.sh +7 -1
  4. package/docs/activities-client.md +27 -0
  5. package/docs/mcp-oauth2-it.md +279 -0
  6. package/docs/mcp-oauth2.md +279 -0
  7. package/docs/numeric-input-validation.md +91 -0
  8. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server-it.md +155 -0
  9. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server.md +155 -0
  10. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot-it.md +63 -0
  11. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot.md +63 -0
  12. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design-it.md +207 -0
  13. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md +207 -0
  14. package/jobs.js +15 -0
  15. package/models/mcpOAuthConnection.js +131 -0
  16. package/models/request.js +8 -0
  17. package/package.json +1 -1
  18. package/pubmodules/activities/activityMessageUtil.js +137 -0
  19. package/pubmodules/activities/models/activity.js +2 -0
  20. package/pubmodules/activities/routes/activity.js +39 -11
  21. package/pubmodules/activities/test/execution-filter.test.js +133 -0
  22. package/pubmodules/activities/test/execution-messages.test.js +158 -0
  23. package/pubmodules/canned/cannedResponseRoute.js +6 -9
  24. package/pubmodules/events/eventRoute.js +6 -9
  25. package/pubmodules/executions-publisher/index.js +457 -0
  26. package/pubmodules/executions-publisher/test/audit-consumer.test.js +384 -0
  27. package/pubmodules/executions-publisher/test/executions-publisher.test.js +204 -0
  28. package/pubmodules/pubModulesManager.js +12 -0
  29. package/routes/answered.js +7 -3
  30. package/routes/campaigns.js +7 -3
  31. package/routes/department.js +14 -3
  32. package/routes/executions-refire.js +148 -0
  33. package/routes/faq.js +6 -14
  34. package/routes/filesp.js +9 -4
  35. package/routes/kb.js +40 -15
  36. package/routes/lead.js +23 -28
  37. package/routes/logs.js +8 -1
  38. package/routes/mcp.js +11 -8
  39. package/routes/mcpOAuth.js +133 -0
  40. package/routes/mcpOAuthCallback.js +75 -0
  41. package/routes/message.js +3 -1
  42. package/routes/messagesRoot.js +5 -18
  43. package/routes/project.js +57 -12
  44. package/routes/project_user.js +21 -4
  45. package/routes/property.js +18 -20
  46. package/routes/request.js +36 -45
  47. package/routes/roles.js +8 -18
  48. package/routes/segment.js +8 -18
  49. package/routes/subscription.js +4 -5
  50. package/routes/tag.js +6 -9
  51. package/routes/unanswered.js +7 -3
  52. package/routes/user-request.js +29 -34
  53. package/routes/webhook.js +120 -54
  54. package/services/mcpOAuthDiscovery.js +248 -0
  55. package/services/mcpOAuthGoogleScopes.js +55 -0
  56. package/services/mcpOAuthService.js +732 -0
  57. package/services/mcpService.js +111 -15
  58. package/services/requestService.js +4 -2
  59. package/services/webhookService.js +4 -2
  60. package/test/executions-refire.test.js +362 -0
  61. package/test/kbRoute.js +4 -7
  62. package/test/mcpOAuthDiscovery.test.js +331 -0
  63. package/test/mcpOAuthGoogleScopes.test.js +25 -0
  64. package/test/mcpOAuthRoute.test.js +455 -0
  65. package/test/mcpOAuthService.test.js +693 -0
  66. package/test/mcpOAuthUtils.test.js +348 -0
  67. package/test/mcpServiceOAuth.test.js +267 -0
  68. package/test/numericInput.js +137 -0
  69. package/test/requestRoute.js +57 -0
  70. package/test/webhookConversationRoute.js +51 -0
  71. package/utils/logRedactor.js +4 -2
  72. package/utils/mcpOAuthCrypto.js +69 -0
  73. package/utils/mcpOAuthPkce.js +20 -0
  74. package/utils/numericInput.js +200 -0
  75. package/utils/outboundUrlGuard.js +131 -0
@@ -0,0 +1,384 @@
1
+ // During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+
4
+ const { expect } = require('chai');
5
+ const mongoose = require('mongoose');
6
+ const config = require('../../../config/database');
7
+ const Activity = require('../../activities/models/activity');
8
+ const publisher = require('../index');
9
+
10
+ const savedUrl = process.env.EXECUTIONS_AMQP_URL;
11
+ const savedHistory = process.env.ACTIVITY_HISTORY_ENABLED;
12
+
13
+ function fakeChannel() {
14
+ const ch = {
15
+ asserted: [], bound: [], prefetched: null, handler: null, acked: [], nacked: [],
16
+ assertQueue: function (q, o) { ch.asserted.push({ q: q, o: o }); return Promise.resolve({}); },
17
+ bindQueue: function (q, ex, key) { ch.bound.push({ q: q, ex: ex, key: key }); return Promise.resolve(); },
18
+ prefetch: function (n) { ch.prefetched = n; return Promise.resolve(); },
19
+ consume: function (q, fn) { ch.handler = fn; return Promise.resolve({}); },
20
+ ack: function (m) { ch.acked.push(m); },
21
+ nack: function (m, all, requeue) { ch.nacked.push({ m: m, requeue: requeue }); },
22
+ on: function () {}
23
+ };
24
+ return ch;
25
+ }
26
+
27
+ function auditBody(extra) {
28
+ return Object.assign({
29
+ audit_id: 'aud-' + Date.now() + '-' + Math.random(),
30
+ at: '2026-11-10T10:00:00.000Z',
31
+ actor: { user_id: 'u1', email: 'a@b.c', name: 'Raw Name', role: 'owner' },
32
+ id_project: 'proj-audit-test',
33
+ execution_id: 'abcdef123456',
34
+ agent_id: 'agent-1',
35
+ action: 'stop_hard',
36
+ reason: 'too slow',
37
+ details: { mode: 'hard', result: 'accepted', status_before: 'running', status_after: 'stopped' },
38
+ ip: '1.1.1.1',
39
+ user_agent: 'ua',
40
+ actor_name: 'Mario Rossi',
41
+ agent_name: 'Support Bot',
42
+ request_id: 'req-9',
43
+ status_after: 'stopped',
44
+ trigger_type: 'chat'
45
+ }, extra || {});
46
+ }
47
+
48
+ function msg(body) {
49
+ return { content: Buffer.from(typeof body === 'string' ? body : JSON.stringify(body)) };
50
+ }
51
+
52
+ async function deliver(ch, m) {
53
+ await ch.handler(m);
54
+ }
55
+
56
+ describe('executions-publisher audit consumer', function () {
57
+ let ch;
58
+
59
+ before(async function () {
60
+ if (mongoose.connection.readyState === 0) {
61
+ await mongoose.connect(config.databasetest, { useNewUrlParser: true, useUnifiedTopology: true });
62
+ }
63
+ await Activity.init();
64
+ });
65
+
66
+ beforeEach(async function () {
67
+ process.env.ACTIVITY_HISTORY_ENABLED = 'true';
68
+ process.env.EXECUTIONS_AMQP_URL = 'amqp://example.invalid';
69
+ publisher._setNackDelayForTests(5);
70
+ await Activity.deleteMany({ id_project: 'proj-audit-test' });
71
+ ch = fakeChannel();
72
+ await publisher.startAuditConsumer({ channelFactory: function () { return Promise.resolve(ch); } });
73
+ });
74
+
75
+ after(async function () {
76
+ await Activity.deleteMany({ id_project: 'proj-audit-test' });
77
+ if (savedUrl === undefined) delete process.env.EXECUTIONS_AMQP_URL; else process.env.EXECUTIONS_AMQP_URL = savedUrl;
78
+ if (savedHistory === undefined) delete process.env.ACTIVITY_HISTORY_ENABLED; else process.env.ACTIVITY_HISTORY_ENABLED = savedHistory;
79
+ });
80
+
81
+ it('asserts the durable queue, binds audit.# and sets prefetch 20', function () {
82
+ expect(ch.asserted).to.deep.equal([{ q: 'server.executions.audit', o: { durable: true } }]);
83
+ expect(ch.bound).to.deep.equal([{ q: 'server.executions.audit', ex: 'tiledesk.executions', key: 'audit.#' }]);
84
+ expect(ch.prefetched).to.equal(20);
85
+ });
86
+
87
+ it('audit.recorded becomes one Activity with the mapped fields', async function () {
88
+ const body = auditBody();
89
+ const m = msg(body);
90
+ await deliver(ch, m);
91
+ expect(ch.acked).to.deep.equal([m]);
92
+ const list = await Activity.find({ 'actionObj.audit_id': body.audit_id }).lean();
93
+ expect(list).to.have.length(1);
94
+ const a = list[0];
95
+ expect(a.verb).to.equal('EXECUTION_STOP_HARD');
96
+ expect(a.id_project).to.equal('proj-audit-test');
97
+ expect(a.actor).to.deep.include({ type: 'user', id: 'u1', name: 'Mario Rossi' });
98
+ expect(a.target.type).to.equal('execution');
99
+ expect(a.target.id).to.equal('abcdef123456');
100
+ expect(a.target.object).to.deep.equal({
101
+ agent_id: 'agent-1', agent_name: 'Support Bot', request_id: 'req-9',
102
+ status_after: 'stopped', trigger_type: 'chat'
103
+ });
104
+ expect(a.related).to.deep.include({ role: 'agent', type: 'faq_kb', id: 'agent-1', name: 'Support Bot' });
105
+ expect(a.actionObj).to.deep.equal({ mode: 'hard', reason: 'too slow', result: 'accepted', audit_id: body.audit_id });
106
+ expect(new Date(a.createdAt).toISOString()).to.equal('2026-11-10T10:00:00.000Z');
107
+ });
108
+
109
+ it('maps each action to its verb', async function () {
110
+ const cases = { stop_soft: 'EXECUTION_STOP_SOFT', stop_hard: 'EXECUTION_STOP_HARD', destroy: 'EXECUTION_DESTROY',
111
+ resume: 'EXECUTION_RESUME', start_new: 'EXECUTION_START_NEW' };
112
+ for (const action of Object.keys(cases)) {
113
+ const body = auditBody({ action: action, reason: undefined, details: { result: 'accepted' } });
114
+ await deliver(ch, msg(body));
115
+ const a = await Activity.findOne({ 'actionObj.audit_id': body.audit_id }).lean();
116
+ expect(a.verb).to.equal(cases[action]);
117
+ expect(a.actionObj).to.deep.equal({ result: 'accepted', audit_id: body.audit_id });
118
+ }
119
+ });
120
+
121
+ it('a "requested" resume/start_new entry is acked without an Activity; its outcome entry is saved (contract 6)', async function () {
122
+ const first = auditBody({ action: 'start_new', details: { result: 'requested', status_before: 'completed', status_after: 'completed' } });
123
+ const m = msg(first);
124
+ await deliver(ch, m);
125
+ expect(ch.acked).to.include(m);
126
+ expect(await Activity.countDocuments({ id_project: 'proj-audit-test' })).to.equal(0);
127
+ const second = msg(auditBody({ action: 'start_new', details: { result: 'rejected:not_startable:webhook_not_found', of_audit_id: first.audit_id } }));
128
+ await deliver(ch, second);
129
+ const saved = await Activity.find({ id_project: 'proj-audit-test' }).lean();
130
+ expect(saved).to.have.length(1);
131
+ expect(saved[0].verb).to.equal('EXECUTION_START_NEW');
132
+ expect(saved[0].actionObj.result).to.equal('rejected:not_startable:webhook_not_found');
133
+ });
134
+
135
+ it('a data_viewed entry is acked without an Activity', async function () {
136
+ const m = msg(auditBody({ action: 'data_viewed', details: { result: 'accepted', purpose: 'start_new_prefill' } }));
137
+ await deliver(ch, m);
138
+ expect(ch.acked).to.include(m);
139
+ expect(ch.nacked).to.have.length(0);
140
+ expect(await Activity.countDocuments({ id_project: 'proj-audit-test' })).to.equal(0);
141
+ });
142
+
143
+ it('data_access_requested is mirrored only when accepted, with scope and grant', async function () {
144
+ const ok = auditBody({ action: 'data_access_requested', reason: 'debug',
145
+ details: { result: 'accepted', scope: { type: 'step', step_seq: 2 }, grant_id: 'g1' } });
146
+ await deliver(ch, msg(ok));
147
+ const a = await Activity.findOne({ 'actionObj.audit_id': ok.audit_id }).lean();
148
+ expect(a.verb).to.equal('EXECUTION_DATA_ACCESS');
149
+ expect(a.target.id).to.equal('abcdef123456');
150
+ expect(a.actionObj).to.deep.equal({ reason: 'debug', result: 'accepted', audit_id: ok.audit_id,
151
+ scope: { type: 'step', step_seq: 2 }, grant_id: 'g1' });
152
+ for (const result of ['rejected:invalid_reason', 'rejected:not_found', 'requested']) {
153
+ const m = msg(auditBody({ action: 'data_access_requested', details: { result: result, scope: { type: 'execution' } } }));
154
+ await deliver(ch, m);
155
+ expect(ch.acked).to.include(m);
156
+ }
157
+ expect(await Activity.countDocuments({ id_project: 'proj-audit-test' })).to.equal(1);
158
+ });
159
+
160
+ it('data_access_denied becomes EXECUTION_DATA_ACCESS_DENIED with the role', async function () {
161
+ const body = auditBody({ action: 'data_access_denied', reason: undefined,
162
+ details: { result: 'rejected:forbidden', scope: { type: 'execution' }, role: 'agent' } });
163
+ await deliver(ch, msg(body));
164
+ const a = await Activity.findOne({ 'actionObj.audit_id': body.audit_id }).lean();
165
+ expect(a.verb).to.equal('EXECUTION_DATA_ACCESS_DENIED');
166
+ expect(a.actionObj).to.deep.equal({ result: 'rejected:forbidden', audit_id: body.audit_id,
167
+ scope: { type: 'execution' }, role: 'agent' });
168
+ });
169
+
170
+ it('retention_update has no execution and no agent: saved with a project target, idempotent on audit_id', async function () {
171
+ const retention = { before: { trace_days: 90, data_days: 30 }, after: { trace_days: 30, data_days: 7 } };
172
+ const body = auditBody({ action: 'retention_update', execution_id: undefined, agent_id: undefined, agent_name: undefined,
173
+ request_id: undefined, status_after: undefined, trigger_type: undefined, reason: undefined,
174
+ details: { result: 'accepted', retention: retention } });
175
+ const m = msg(body);
176
+ await deliver(ch, m);
177
+ await deliver(ch, msg(body));
178
+ expect(ch.acked).to.include(m);
179
+ const list = await Activity.find({ 'actionObj.audit_id': body.audit_id }).lean();
180
+ expect(list).to.have.length(1);
181
+ expect(list[0].verb).to.equal('EXECUTION_RETENTION_UPDATE');
182
+ expect(list[0].target.type).to.equal('project');
183
+ expect(list[0].target.id).to.equal('proj-audit-test');
184
+ expect(list[0].related).to.equal(undefined);
185
+ expect(list[0].actionObj).to.deep.equal({ result: 'accepted', audit_id: body.audit_id, retention: retention });
186
+ });
187
+
188
+ it('stop_notice_update is project-level too: saved with a project target and the setting', async function () {
189
+ const stopNotice = { before: { enabled: true, text: null }, after: { enabled: false, text: null } };
190
+ const body = auditBody({ action: 'stop_notice_update', execution_id: undefined, agent_id: undefined, agent_name: undefined,
191
+ request_id: undefined, status_after: undefined, trigger_type: undefined, reason: undefined,
192
+ details: { result: 'accepted', stop_notice: stopNotice } });
193
+ const m = msg(body);
194
+ await deliver(ch, m);
195
+ expect(ch.acked).to.include(m);
196
+ const list = await Activity.find({ 'actionObj.audit_id': body.audit_id }).lean();
197
+ expect(list).to.have.length(1);
198
+ expect(list[0].verb).to.equal('EXECUTION_STOP_NOTICE_UPDATE');
199
+ expect(list[0].target.type).to.equal('project');
200
+ expect(list[0].target.id).to.equal('proj-audit-test');
201
+ expect(list[0].actionObj).to.deep.equal({ result: 'accepted', audit_id: body.audit_id, stop_notice: stopNotice });
202
+ });
203
+
204
+ it('duplicate audit_id saves once', async function () {
205
+ const body = auditBody();
206
+ const m1 = msg(body), m2 = msg(body);
207
+ await deliver(ch, m1);
208
+ await deliver(ch, m2);
209
+ expect(ch.acked).to.deep.equal([m1, m2]);
210
+ expect(ch.nacked).to.have.length(0);
211
+ expect(await Activity.countDocuments({ 'actionObj.audit_id': body.audit_id })).to.equal(1);
212
+ });
213
+
214
+ it('ACTIVITY_HISTORY_ENABLED false -> acked, nothing saved', async function () {
215
+ process.env.ACTIVITY_HISTORY_ENABLED = 'false';
216
+ const body = auditBody();
217
+ const m = msg(body);
218
+ await deliver(ch, m);
219
+ expect(ch.acked).to.deep.equal([m]);
220
+ expect(await Activity.countDocuments({ 'actionObj.audit_id': body.audit_id })).to.equal(0);
221
+ });
222
+
223
+ it('invalid JSON is acked without saving', async function () {
224
+ const m = msg('not json {');
225
+ await deliver(ch, m);
226
+ expect(ch.acked).to.deep.equal([m]);
227
+ expect(ch.nacked).to.have.length(0);
228
+ });
229
+
230
+ it('a message missing id_project, execution_id or actor.user_id is acked and never saved', async function () {
231
+ const cases = [
232
+ auditBody({ id_project: undefined }),
233
+ auditBody({ execution_id: undefined }),
234
+ auditBody({ actor: { email: 'a@b.c', role: 'owner' } }),
235
+ auditBody({ actor: undefined })
236
+ ];
237
+ for (const body of cases) {
238
+ const m = msg(body);
239
+ await deliver(ch, m);
240
+ expect(ch.acked).to.include(m);
241
+ expect(await Activity.countDocuments({ 'actionObj.audit_id': body.audit_id })).to.equal(0);
242
+ }
243
+ await new Promise(function (r) { setTimeout(r, 30); });
244
+ expect(ch.nacked).to.have.length(0);
245
+ });
246
+
247
+ it('ValidationError, CastError and StrictModeError are acked (never redelivered)', async function () {
248
+ const orig = Activity.prototype.save;
249
+ try {
250
+ for (const name of ['ValidationError', 'CastError', 'StrictModeError']) {
251
+ const m = msg(auditBody());
252
+ Activity.prototype.save = function () { const e = new Error('bad doc'); e.name = name; return Promise.reject(e); };
253
+ await deliver(ch, m);
254
+ expect(ch.acked).to.include(m);
255
+ }
256
+ } finally {
257
+ Activity.prototype.save = orig;
258
+ }
259
+ await new Promise(function (r) { setTimeout(r, 30); });
260
+ expect(ch.nacked).to.have.length(0);
261
+ });
262
+
263
+ it('a real validation failure of the Activity document is acked', async function () {
264
+ const m = msg(auditBody({ at: undefined }));
265
+ const orig = Activity.prototype.save;
266
+ const mongooseLib = require('mongoose');
267
+ Activity.prototype.save = function () { return Promise.reject(new mongooseLib.Error.ValidationError()); };
268
+ try {
269
+ await deliver(ch, m);
270
+ } finally {
271
+ Activity.prototype.save = orig;
272
+ }
273
+ expect(ch.acked).to.deep.equal([m]);
274
+ });
275
+
276
+ it('an unknown (not recoverable) error is acked and logged, not requeued', async function () {
277
+ const m = msg(auditBody());
278
+ const orig = Activity.prototype.save;
279
+ Activity.prototype.save = function () { return Promise.reject(new Error('boom')); };
280
+ try {
281
+ await deliver(ch, m);
282
+ } finally {
283
+ Activity.prototype.save = orig;
284
+ }
285
+ await new Promise(function (r) { setTimeout(r, 30); });
286
+ expect(ch.acked).to.deep.equal([m]);
287
+ expect(ch.nacked).to.have.length(0);
288
+ });
289
+
290
+ // the shapes this server's mongoose 5.13 / mongodb 3.7 driver really produces
291
+ async function deliverWithSaveError(makeErr) {
292
+ const m = msg(auditBody());
293
+ const orig = Activity.prototype.save;
294
+ Activity.prototype.save = function () { return Promise.reject(makeErr()); };
295
+ try {
296
+ await deliver(ch, m);
297
+ } finally {
298
+ Activity.prototype.save = orig;
299
+ }
300
+ await new Promise(function (r) { setTimeout(r, 30); });
301
+ return m;
302
+ }
303
+
304
+ it('a MongoError with a not-primary code (failover) is requeued', async function () {
305
+ const { MongoError } = require('mongodb');
306
+ const m = await deliverWithSaveError(function () { const e = new MongoError('not master'); e.code = 10107; return e; });
307
+ expect(ch.acked).to.have.length(0);
308
+ expect(ch.nacked).to.deep.equal([{ m: m, requeue: true }]);
309
+ });
310
+
311
+ it('a mongoose buffering timeout (save during an outage) is requeued', async function () {
312
+ const mongooseLib = require('mongoose');
313
+ const m = await deliverWithSaveError(function () {
314
+ return new mongooseLib.Error('Operation `activities.insertOne()` buffering timed out after 10000ms');
315
+ });
316
+ expect(ch.acked).to.have.length(0);
317
+ expect(ch.nacked).to.deep.equal([{ m: m, requeue: true }]);
318
+ });
319
+
320
+ it('driver timeout and server selection errors are requeued', async function () {
321
+ const { MongoTimeoutError, MongoServerSelectionError } = require('mongodb');
322
+ const m1 = await deliverWithSaveError(function () { return new MongoTimeoutError('Server selection timed out after 30000 ms'); });
323
+ const m2 = await deliverWithSaveError(function () { return new MongoServerSelectionError('connection refused'); });
324
+ expect(ch.acked).to.have.length(0);
325
+ expect(ch.nacked).to.deep.equal([{ m: m1, requeue: true }, { m: m2, requeue: true }]);
326
+ });
327
+
328
+ it('a MongoError duplicate key is acked, and a ValidationError is still acked', async function () {
329
+ const { MongoError } = require('mongodb');
330
+ const mongooseLib = require('mongoose');
331
+ const m1 = await deliverWithSaveError(function () { const e = new MongoError('E11000 duplicate key'); e.code = 11000; return e; });
332
+ const m2 = await deliverWithSaveError(function () { return new mongooseLib.Error.ValidationError(); });
333
+ expect(ch.acked).to.deep.equal([m1, m2]);
334
+ expect(ch.nacked).to.have.length(0);
335
+ });
336
+
337
+ it('recoverable errors (connection, timeout) are nacked with requeue after a delay', async function () {
338
+ const m = msg(auditBody());
339
+ const orig = Activity.prototype.save;
340
+ Activity.prototype.save = function () { const e = new Error('connection reset'); e.name = 'MongoNetworkError'; return Promise.reject(e); };
341
+ try {
342
+ await deliver(ch, m);
343
+ } finally {
344
+ Activity.prototype.save = orig;
345
+ }
346
+ expect(ch.acked).to.have.length(0);
347
+ expect(ch.nacked).to.have.length(0);
348
+ await new Promise(function (r) { setTimeout(r, 30); });
349
+ expect(ch.nacked).to.deep.equal([{ m: m, requeue: true }]);
350
+ });
351
+
352
+ it('listen({ audit: false }) publishes only: no audit consumer (the jobs worker)', function () {
353
+ const saved = process.env.EXECUTIONS_AMQP_URL;
354
+ process.env.EXECUTIONS_AMQP_URL = 'amqp://unused.invalid';
355
+ const requestEvent = require('../../../event/requestEvent');
356
+ const names = ['request.close', 'request.participants.update', 'request.participants.leave'];
357
+ const before = names.map(function (n) { return requestEvent.listeners(n).slice(); });
358
+ let called = false;
359
+ publisher._setAuditChannelFactoryForTests(function () { called = true; return Promise.resolve(fakeChannel()); });
360
+ try {
361
+ publisher.listen({ audit: false });
362
+ expect(called).to.equal(false);
363
+ expect(names.map(function (n) { return requestEvent.listenerCount(n); })).to.deep.equal(before.map(function (l) { return l.length + 1; }));
364
+ } finally {
365
+ // the listeners this test added go: the next file checks that none are left without EXECUTIONS_AMQP_URL
366
+ names.forEach(function (n, i) {
367
+ requestEvent.listeners(n).forEach(function (l) { if (before[i].indexOf(l) === -1) requestEvent.removeListener(n, l); });
368
+ });
369
+ publisher._setAuditChannelFactoryForTests(null);
370
+ if (saved === undefined) delete process.env.EXECUTIONS_AMQP_URL;
371
+ else process.env.EXECUTIONS_AMQP_URL = saved;
372
+ }
373
+ });
374
+
375
+ it('consumer not started without EXECUTIONS_AMQP_URL', function () {
376
+ delete process.env.EXECUTIONS_AMQP_URL;
377
+ let called = false;
378
+ publisher.listen();
379
+ publisher._setAuditChannelFactoryForTests(function () { called = true; return Promise.resolve(fakeChannel()); });
380
+ publisher.listen();
381
+ expect(called).to.equal(false);
382
+ publisher._setAuditChannelFactoryForTests(null);
383
+ });
384
+ });
@@ -0,0 +1,204 @@
1
+ // During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+
4
+ const { expect } = require('chai');
5
+
6
+ const requestEvent = require('../../../event/requestEvent');
7
+ const publisher = require('../index');
8
+
9
+ const savedUrl = process.env.EXECUTIONS_AMQP_URL;
10
+
11
+ const published = [];
12
+ const transport = {
13
+ publish: function (routingKey, buffer) {
14
+ published.push({ routingKey: routingKey, body: JSON.parse(buffer.toString()) });
15
+ }
16
+ };
17
+
18
+ function request(extra) {
19
+ return Object.assign({
20
+ request_id: 'req-1',
21
+ id_project: 'proj-1',
22
+ participants: ['user-1', 'bot_b1'],
23
+ attributes: { execution_id: 'exec-1' }
24
+ }, extra || {});
25
+ }
26
+
27
+ describe('executions-publisher', function () {
28
+ before(function () {
29
+ publisher._setTransportForTests(transport);
30
+ });
31
+
32
+ beforeEach(function () {
33
+ published.length = 0;
34
+ });
35
+
36
+ after(function () {
37
+ if (savedUrl === undefined) delete process.env.EXECUTIONS_AMQP_URL;
38
+ else process.env.EXECUTIONS_AMQP_URL = savedUrl;
39
+ });
40
+
41
+ it('no listeners without EXECUTIONS_AMQP_URL', function () {
42
+ delete process.env.EXECUTIONS_AMQP_URL;
43
+ const names = ['request.close', 'request.participants.update', 'request.participants.leave'];
44
+ const before = names.map((n) => requestEvent.listenerCount(n));
45
+ publisher.listen();
46
+ expect(names.map((n) => requestEvent.listenerCount(n))).to.deep.equal(before);
47
+ requestEvent.emit('request.close', request());
48
+ expect(published).to.have.lengthOf(0);
49
+ });
50
+
51
+ describe('with EXECUTIONS_AMQP_URL set', function () {
52
+ before(function () {
53
+ process.env.EXECUTIONS_AMQP_URL = 'amqp://unused.invalid';
54
+ // keep the audit consumer off the real (shared) AMQP connection: these tests own it
55
+ publisher._setAuditChannelFactoryForTests(function () {
56
+ return Promise.resolve({
57
+ on: function () {}, assertQueue: function () { return Promise.resolve(); },
58
+ bindQueue: function () { return Promise.resolve(); }, prefetch: function () { return Promise.resolve(); },
59
+ consume: function () { return Promise.resolve(); }
60
+ });
61
+ });
62
+ publisher.listen();
63
+ });
64
+
65
+ after(function () {
66
+ publisher._setAuditChannelFactoryForTests(null);
67
+ });
68
+
69
+ it('request.close publishes conversation.closed', function () {
70
+ requestEvent.emit('request.close', request({ closed_by: 'user-9' }));
71
+ expect(published).to.have.lengthOf(1);
72
+ const p = published[0];
73
+ expect(p.routingKey).to.equal('exec.proj-1.conversation.closed');
74
+ expect(p.body.event_version).to.equal(1);
75
+ expect(p.body.type).to.equal('conversation.closed');
76
+ expect(p.body.execution_id).to.equal('exec-1');
77
+ expect(p.body.id_project).to.equal('proj-1');
78
+ expect(p.body.request_id).to.equal('req-1');
79
+ expect(new Date(p.body.at).toISOString()).to.equal(p.body.at);
80
+ expect(p.body.data).to.deep.equal({
81
+ request_id: 'req-1', execution_id: 'exec-1', bot_id: 'b1', closed_by: 'user-9'
82
+ });
83
+ });
84
+
85
+ it('closed without execution_id attribute publishes execution_id null', function () {
86
+ requestEvent.emit('request.close', request({ attributes: {} }));
87
+ expect(published).to.have.lengthOf(1);
88
+ expect(published[0].body.execution_id).to.equal(null);
89
+ expect(published[0].body.data.execution_id).to.equal(null);
90
+ });
91
+
92
+ it('closed with execution_id but no bot participant publishes with bot_id null', function () {
93
+ requestEvent.emit('request.close', request({ participants: ['user-1'] }));
94
+ expect(published).to.have.lengthOf(1);
95
+ expect(published[0].body.data.bot_id).to.equal(null);
96
+ });
97
+
98
+ it('a request without bot participants publishes nothing', function () {
99
+ requestEvent.emit('request.close', request({ participants: ['user-1'], attributes: {} }));
100
+ expect(published).to.have.lengthOf(0);
101
+ });
102
+
103
+ it('participants.update with removed bot and added bot publishes bot_replaced', function () {
104
+ requestEvent.emit('request.participants.update', {
105
+ beforeRequest: request(),
106
+ removedParticipants: ['bot_b1'],
107
+ addedParticipants: ['bot_b2'],
108
+ request: request({ participants: ['user-1', 'bot_b2'] })
109
+ });
110
+ expect(published).to.have.lengthOf(1);
111
+ expect(published[0].routingKey).to.equal('exec.proj-1.conversation.bot_replaced');
112
+ expect(published[0].body.data).to.deep.equal({
113
+ request_id: 'req-1', execution_id: 'exec-1', bot_id: 'b1', to_bot_id: 'b2'
114
+ });
115
+ });
116
+
117
+ it('participants.update with removed bot and no added bot publishes bot_left', function () {
118
+ requestEvent.emit('request.participants.update', {
119
+ removedParticipants: ['bot_b1'],
120
+ addedParticipants: ['agent-1'],
121
+ request: request({ participants: ['user-1', 'agent-1'] })
122
+ });
123
+ expect(published).to.have.lengthOf(1);
124
+ expect(published[0].routingKey).to.equal('exec.proj-1.conversation.bot_left');
125
+ expect(published[0].body.data.bot_id).to.equal('b1');
126
+ expect(published[0].body.data).to.not.have.property('to_bot_id');
127
+ });
128
+
129
+ it('participants.update with a subagent reason publishes nothing', function () {
130
+ ['subagent_call', 'subagent_return'].forEach(function (reason) {
131
+ requestEvent.emit('request.participants.update', {
132
+ removedParticipants: ['bot_b1'],
133
+ addedParticipants: ['bot_b2'],
134
+ request: request(),
135
+ reason: reason
136
+ });
137
+ });
138
+ expect(published).to.have.lengthOf(0);
139
+ });
140
+
141
+ it('participants.update without a removed bot publishes nothing', function () {
142
+ requestEvent.emit('request.participants.update', {
143
+ removedParticipants: ['agent-1'],
144
+ addedParticipants: ['bot_b2'],
145
+ request: request()
146
+ });
147
+ expect(published).to.have.lengthOf(0);
148
+ });
149
+
150
+ it('participants.leave of a bot publishes bot_left', function () {
151
+ requestEvent.emit('request.participants.leave', { member: 'bot_b1', request: request() });
152
+ expect(published).to.have.lengthOf(1);
153
+ expect(published[0].routingKey).to.equal('exec.proj-1.conversation.bot_left');
154
+ expect(published[0].body.data.bot_id).to.equal('b1');
155
+ });
156
+
157
+ it('participants.leave of a human publishes nothing', function () {
158
+ requestEvent.emit('request.participants.leave', { member: 'agent-1', request: request() });
159
+ expect(published).to.have.lengthOf(0);
160
+ });
161
+
162
+ it('closed without closed_by publishes closed_by null, never undefined (V1)', function () {
163
+ requestEvent.emit('request.close', request());
164
+ expect(published).to.have.lengthOf(1);
165
+ expect(published[0].body.data).to.have.property('closed_by', null);
166
+ requestEvent.emit('request.close', request({ closed_by: null }));
167
+ expect(published[1].body.data).to.have.property('closed_by', null);
168
+ });
169
+
170
+ it('a throwing transport never reaches the emitter', function () {
171
+ publisher._setTransportForTests({ publish: function () { throw new Error('boom'); } });
172
+ try {
173
+ expect(function () { requestEvent.emit('request.close', request()); }).to.not.throw();
174
+ } finally {
175
+ publisher._setTransportForTests(transport);
176
+ }
177
+ });
178
+ });
179
+
180
+ describe('amqp transport (V2)', function () {
181
+ const amqplib = require('amqplib');
182
+ const origConnect = amqplib.connect;
183
+ let connectArgs;
184
+ afterEach(function () {
185
+ amqplib.connect = origConnect;
186
+ publisher._setConnectTimeoutForTests(null);
187
+ });
188
+
189
+ it('a connect that never answers fails after the connect timeout, and the next publish reconnects', async function () {
190
+ let attempts = 0;
191
+ amqplib.connect = function () { attempts++; connectArgs = Array.from(arguments); return new Promise(function () {}); };
192
+ publisher._setConnectTimeoutForTests(50);
193
+ const t0 = Date.now();
194
+ let err = null;
195
+ try { await publisher._amqpTransport.publish('exec.p.conversation.closed', Buffer.from('{}')); } catch (e) { err = e; }
196
+ expect(err).to.be.an('error');
197
+ expect(err.message).to.match(/connect timeout/);
198
+ expect(Date.now() - t0).to.be.below(2000);
199
+ expect(connectArgs[1]).to.deep.include({ timeout: 50 });
200
+ try { await publisher._amqpTransport.publish('exec.p.conversation.closed', Buffer.from('{}')); } catch (e) { /* times out again */ }
201
+ expect(attempts).to.equal(2);
202
+ });
203
+ });
204
+ });
@@ -636,6 +636,18 @@ class PubModulesManager {
636
636
  }
637
637
  }
638
638
 
639
+ try {
640
+ this.executionsPublisher = require('./executions-publisher');
641
+ this.executionsPublisher.listen();
642
+ winston.info("PubModulesManager executionsPublisher initialized.");
643
+ } catch(err) {
644
+ if (err.code == 'MODULE_NOT_FOUND') {
645
+ winston.info("PubModulesManager init executionsPublisher module not found");
646
+ } else {
647
+ winston.info("PubModulesManager error initializing executionsPublisher module", err);
648
+ }
649
+ }
650
+
639
651
  try {
640
652
  this.docsparse = require('./docsparse');
641
653
  winston.debug("this.docsparse: " + this.docsparse);
@@ -4,6 +4,7 @@ const { Namespace, AnsweredQuestion } = require('../models/kb_setting');
4
4
  const winston = require('../config/winston');
5
5
  var fastCsv = require('fast-csv');
6
6
  const kbQuestionService = require('../services/kbQuestionService');
7
+ const numericInput = require('../utils/numericInput');
7
8
 
8
9
  // Add a new unanswerd question
9
10
  router.post('/', async (req, res) => {
@@ -51,10 +52,13 @@ router.get('/:namespace', async (req, res) => {
51
52
  })
52
53
  }
53
54
 
54
- const page = parseInt(req.query.page) || 0;
55
- const limit = parseInt(req.query.limit) || 20;
55
+ const paging = numericInput.takePagination(res, req.query, { defaultLimit: 20, maxLimit: 100, overMax: 'reject' });
56
+ if (!paging) return;
57
+ const page = paging.page;
58
+ const limit = paging.limit;
56
59
  const sortField = req.query.sortField || 'createdAt';
57
- const direction = parseInt(req.query.direction) || -1;
60
+ const direction = numericInput.takeSortDirection(res, req.query.direction);
61
+ if (direction === null) return;
58
62
 
59
63
  const filter = { id_project, namespace };
60
64
 
@@ -11,6 +11,7 @@ var MessageConstants = require("../models/messageConstants");
11
11
  var UIDGenerator = require("../utils/UIDGenerator");
12
12
  var LeadConstants = require("../models/leadConstants");
13
13
  var Segment2MongoConverter = require("../utils/segment2mongoConverter");
14
+ var numericInput = require('../utils/numericInput');
14
15
 
15
16
  var JobManager = require("jobs-worker-queued");
16
17
 
@@ -28,7 +29,8 @@ var jobManager = new JobManager(JOB_RABBITURI,
28
29
  // this endpoint supports support-group- or groups. this create a conversation for the sender (agent console)
29
30
  router.post('/', function (req, res) {
30
31
 
31
- let messageStatus = req.body.status || MessageConstants.CHAT_MESSAGE_STATUS.SENDING;
32
+ let messageStatus = numericInput.takeMessageStatus(res, req.body.status);
33
+ if (messageStatus === null) return;
32
34
 
33
35
  winston.debug(req.body);
34
36
  winston.debug("req.user", req.user);
@@ -68,7 +70,8 @@ Specifica nel campo text il messaggio.
68
70
 
69
71
  router.post('/directDEPRECATED?', async function (req, res) {
70
72
 
71
- let messageStatus = req.body.status || MessageConstants.CHAT_MESSAGE_STATUS.SENDING;
73
+ let messageStatus = numericInput.takeMessageStatus(res, req.body.status);
74
+ if (messageStatus === null) return;
72
75
 
73
76
  winston.debug(req.body);
74
77
  winston.debug("req.user", req.user);
@@ -292,7 +295,8 @@ router.post('/direct', async function (req, res) {
292
295
  var segment_id = req.body.segment_id;
293
296
  winston.info("segment_id"+ segment_id);
294
297
 
295
- let messageStatus = req.body.status || MessageConstants.CHAT_MESSAGE_STATUS.SENDING;
298
+ let messageStatus = numericInput.takeMessageStatus(res, req.body.status);
299
+ if (messageStatus === null) return;
296
300
  // winston.info("messageStatus"+ messageStatus);
297
301
 
298
302