@tiledesk/tiledesk-server 3.3.4 → 3.5.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/app.js +7 -0
  3. package/docs/activities-client.md +27 -0
  4. package/docs/mcp-oauth2-it.md +279 -0
  5. package/docs/mcp-oauth2.md +279 -0
  6. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server-it.md +155 -0
  7. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server.md +155 -0
  8. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot-it.md +63 -0
  9. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot.md +63 -0
  10. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design-it.md +207 -0
  11. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md +207 -0
  12. package/jobs.js +15 -0
  13. package/models/mcpOAuthConnection.js +131 -0
  14. package/package.json +2 -2
  15. package/pubmodules/activities/activityMessageUtil.js +137 -0
  16. package/pubmodules/activities/models/activity.js +2 -0
  17. package/pubmodules/activities/routes/activity.js +30 -1
  18. package/pubmodules/activities/test/execution-filter.test.js +133 -0
  19. package/pubmodules/activities/test/execution-messages.test.js +158 -0
  20. package/pubmodules/executions-publisher/index.js +457 -0
  21. package/pubmodules/executions-publisher/test/audit-consumer.test.js +384 -0
  22. package/pubmodules/executions-publisher/test/executions-publisher.test.js +204 -0
  23. package/pubmodules/pubModulesManager.js +12 -0
  24. package/routes/executions-refire.js +148 -0
  25. package/routes/mcp.js +11 -8
  26. package/routes/mcpOAuth.js +133 -0
  27. package/routes/mcpOAuthCallback.js +75 -0
  28. package/routes/request.js +5 -0
  29. package/routes/webhook.js +120 -54
  30. package/services/mcpOAuthDiscovery.js +248 -0
  31. package/services/mcpOAuthGoogleScopes.js +55 -0
  32. package/services/mcpOAuthService.js +732 -0
  33. package/services/mcpService.js +111 -15
  34. package/services/requestService.js +4 -2
  35. package/services/webhookService.js +4 -2
  36. package/test/executions-refire.test.js +362 -0
  37. package/test/mcpOAuthDiscovery.test.js +331 -0
  38. package/test/mcpOAuthGoogleScopes.test.js +25 -0
  39. package/test/mcpOAuthRoute.test.js +455 -0
  40. package/test/mcpOAuthService.test.js +693 -0
  41. package/test/mcpOAuthUtils.test.js +348 -0
  42. package/test/mcpServiceOAuth.test.js +267 -0
  43. package/test/requestRoute.js +57 -0
  44. package/test/webhookConversationRoute.js +51 -0
  45. package/utils/logRedactor.js +4 -2
  46. package/utils/mcpOAuthCrypto.js +69 -0
  47. package/utils/mcpOAuthPkce.js +20 -0
  48. package/utils/outboundUrlGuard.js +131 -0
@@ -0,0 +1,131 @@
1
+ const mongoose = require('mongoose');
2
+ const Schema = mongoose.Schema;
3
+ const winston = require('../config/winston');
4
+
5
+ const McpOAuthConnectionSchema = new Schema({
6
+ id_project: {
7
+ type: String,
8
+ required: true,
9
+ index: true
10
+ },
11
+ mode: {
12
+ type: String,
13
+ enum: ['mcp', 'google', 'manual'],
14
+ required: true
15
+ },
16
+ server_url: {
17
+ type: String,
18
+ required: true
19
+ },
20
+ name: {
21
+ type: String
22
+ },
23
+ status: {
24
+ type: String,
25
+ enum: ['pending', 'active', 'needs_reauth', 'revoked'],
26
+ default: 'pending'
27
+ },
28
+ client_id: {
29
+ type: String
30
+ },
31
+ client_secret_enc: {
32
+ type: String
33
+ },
34
+ client_registered_at: {
35
+ type: Date
36
+ },
37
+ resource: {
38
+ type: String
39
+ },
40
+ issuer: {
41
+ type: String
42
+ },
43
+ authorization_endpoint: {
44
+ type: String
45
+ },
46
+ token_endpoint: {
47
+ type: String
48
+ },
49
+ revocation_endpoint: {
50
+ type: String
51
+ },
52
+ registration_endpoint: {
53
+ type: String
54
+ },
55
+ token_endpoint_auth_method: {
56
+ type: String,
57
+ enum: ['client_secret_basic', 'client_secret_post', 'none']
58
+ },
59
+ scopes: {
60
+ type: [String],
61
+ default: []
62
+ },
63
+ access_token_enc: {
64
+ type: String
65
+ },
66
+ refresh_token_enc: {
67
+ type: String
68
+ },
69
+ token_type: {
70
+ type: String
71
+ },
72
+ expires_at: {
73
+ type: Date
74
+ },
75
+ granted_scopes: {
76
+ type: [String],
77
+ default: []
78
+ },
79
+ last_refresh_at: {
80
+ type: Date
81
+ },
82
+ last_error: {
83
+ code: String,
84
+ message: String,
85
+ at: Date
86
+ },
87
+ created_by: {
88
+ type: String
89
+ }
90
+ }, {
91
+ timestamps: true
92
+ });
93
+
94
+ McpOAuthConnectionSchema.index({ id_project: 1, server_url: 1 }, { unique: true });
95
+ // refreshDue: active connections expiring within the window
96
+ McpOAuthConnectionSchema.index({ status: 1, expires_at: 1 });
97
+
98
+ const PUBLIC_FIELDS = [
99
+ '_id', 'mode', 'server_url', 'name', 'status', 'scopes', 'granted_scopes', 'expires_at',
100
+ 'last_refresh_at', 'last_error', 'issuer', 'createdAt', 'updatedAt'
101
+ ];
102
+
103
+ /** The connection as returned by the API: no client credentials, no tokens. */
104
+ McpOAuthConnectionSchema.statics.toPublic = function (connection) {
105
+ if (!connection) {
106
+ return connection;
107
+ }
108
+ const source = connection.toObject ? connection.toObject() : connection;
109
+ const result = {};
110
+ for (const field of PUBLIC_FIELDS) {
111
+ if (source[field] !== undefined) {
112
+ result[field] = source[field];
113
+ }
114
+ }
115
+ return result;
116
+ };
117
+
118
+ const McpOAuthConnection = mongoose.model('mcp_oauth_connection', McpOAuthConnectionSchema);
119
+
120
+ // Created explicitly because MONGOOSE_AUTOINDEX can be off: without it a project could
121
+ // end up with two connections for the same MCP server.
122
+ McpOAuthConnection.collection
123
+ .createIndex({ id_project: 1, server_url: 1 }, { unique: true })
124
+ .then(function () {
125
+ winston.verbose('McpOAuthConnection unique index ensured');
126
+ })
127
+ .catch(function (err) {
128
+ winston.error('McpOAuthConnection unique index not created: ', err);
129
+ });
130
+
131
+ module.exports = McpOAuthConnection;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-server",
3
3
  "description": "The Tiledesk server module",
4
- "version": "3.3.4",
4
+ "version": "3.5.0",
5
5
  "scripts": {
6
6
  "start": "node ./bin/www",
7
7
  "quota-restore": "node ./bin/quota-restore",
@@ -51,7 +51,7 @@
51
51
  "@tiledesk/tiledesk-rasa-connector": "^1.0.10",
52
52
  "@tiledesk/tiledesk-sms-connector": "^0.1.13",
53
53
  "@tiledesk/tiledesk-telegram-connector": "^0.1.14",
54
- "@tiledesk/tiledesk-tybot-connector": "^3.0.8",
54
+ "@tiledesk/tiledesk-tybot-connector": "^3.0.9",
55
55
  "@tiledesk/tiledesk-voice-twilio-connector": "^0.3.2",
56
56
  "@tiledesk/tiledesk-vxml-connector": "^0.2.7",
57
57
  "@tiledesk/tiledesk-whatsapp-connector": "1.0.33",
@@ -189,6 +189,131 @@ function kbContentLabel(activity) {
189
189
  return 'content';
190
190
  }
191
191
 
192
+ const EXECUTION_VERBS = {
193
+ // "stop" is shown as "pause" (feedback 2026-11-13): the verbs keep their names, the sentences say pause.
194
+ // enMode/itMode follow "<id> of <agent>": the soft pause waits for the current action, the hard one does not.
195
+ EXECUTION_STOP_SOFT: { en: 'paused execution', it: "ha messo in pausa l'esecuzione",
196
+ enTried: 'tried to pause execution', itTried: "ha provato a mettere in pausa l'esecuzione",
197
+ enMode: 'after the current action', itMode: "dopo l'azione corrente" },
198
+ EXECUTION_STOP_HARD: { en: 'paused execution', it: "ha messo in pausa l'esecuzione",
199
+ enTried: 'tried to pause execution', itTried: "ha provato a mettere in pausa l'esecuzione",
200
+ enMode: 'now', itMode: 'subito' },
201
+ EXECUTION_DESTROY: { en: 'destroyed execution', it: "ha eliminato l'esecuzione",
202
+ enTried: 'tried to destroy execution', itTried: "ha provato a eliminare l'esecuzione" },
203
+ EXECUTION_RESUME: { en: 'resumed execution', it: "ha ripreso l'esecuzione",
204
+ enTried: 'tried to resume execution', itTried: "ha provato a riprendere l'esecuzione" },
205
+ EXECUTION_START_NEW: { en: 'started a new run of execution', it: 'ha avviato una nuova esecuzione da',
206
+ enTried: 'tried to start a new run of execution', itTried: 'ha provato ad avviare una nuova esecuzione da' },
207
+ EXECUTION_DATA_ACCESS: { en: 'viewed the data of execution', it: "ha visualizzato i dati dell'esecuzione" },
208
+ EXECUTION_DATA_ACCESS_DENIED: { en: 'was denied access to the data of execution', it: "non ha ottenuto l'accesso ai dati dell'esecuzione" },
209
+ EXECUTION_RETENTION_UPDATE: { en: 'changed executions retention', it: 'ha modificato la conservazione delle esecuzioni' },
210
+ EXECUTION_STOP_NOTICE_UPDATE: { en: 'changed the executions pause notice', it: "ha modificato l'avviso di esecuzione in pausa" }
211
+ };
212
+
213
+ // "on, custom text" / "off" / "on, default text": the setting after the change (en / it)
214
+ function stopNoticeState(activity, it) {
215
+ const s = activity.actionObj && activity.actionObj.stop_notice;
216
+ const after = s && (s.after || s);
217
+ if (!after || typeof after.enabled !== 'boolean') return '';
218
+ if (!after.enabled) return it ? 'disattivato' : 'off';
219
+ const custom = typeof after.text === 'string' && after.text.trim() !== '';
220
+ return it ? (custom ? 'attivo, testo personalizzato' : 'attivo, testo predefinito') : (custom ? 'on, custom text' : 'on, default text');
221
+ }
222
+
223
+ // "trace 90 → 30 days, data 30 → 7 days": only the parts that changed (en); "tracce ... giorni, dati ... giorni" (it)
224
+ function retentionChanges(activity, it) {
225
+ const r = (activity.actionObj && activity.actionObj.retention) || {};
226
+ const before = r.before || {};
227
+ const after = r.after || {};
228
+ const parts = [];
229
+ [['trace_days', 'trace', 'tracce'], ['data_days', 'data', 'dati']].forEach(function (k) {
230
+ if (before[k[0]] !== after[k[0]]) {
231
+ parts.push((it ? k[2] : k[1]) + ' ' + before[k[0]] + ' → ' + after[k[0]] + (it ? ' giorni' : ' days'));
232
+ }
233
+ });
234
+ return parts.join(', ');
235
+ }
236
+
237
+ // actionObj.result is 'accepted' or 'rejected:<status>' (a 409 is audited too); no result (older rows) = accepted
238
+ function executionRejection(activity) {
239
+ const result = activity && activity.actionObj && activity.actionObj.result;
240
+ if (typeof result !== 'string' || !/^rejected(:|$)/.test(result)) {
241
+ return null;
242
+ }
243
+ return { reason: result.indexOf(':') >= 0 ? result.substring(result.indexOf(':') + 1) : '' };
244
+ }
245
+
246
+ // The status in "(rejected: <status>)" as the dashboard names it: stopped/stopping read paused/pausing.
247
+ const SHOWN_STATUS = { stopped: 'paused', stopping: 'pausing' };
248
+ function shownStatus(status) {
249
+ return Object.prototype.hasOwnProperty.call(SHOWN_STATUS, status) ? SHOWN_STATUS[status] : status;
250
+ }
251
+
252
+ function isExecutionVerb(verb) {
253
+ return Object.prototype.hasOwnProperty.call(EXECUTION_VERBS, verb);
254
+ }
255
+
256
+ // "<actor> paused execution <short id> of <agent> after the current action" (en) /
257
+ // "<actor> ha messo in pausa l'esecuzione <id> di <agent> dopo l'azione corrente" (it); a rejected control:
258
+ // "<actor> tried to pause execution <id> of <agent> now (rejected: <status>)" /
259
+ // "<actor> ha provato a mettere in pausa l'esecuzione <id> di <agent> subito (rifiutato: <status>)". The dashboard renders the same en sentence.
260
+ function buildExecutionMessage(activity, lang) {
261
+ if (!activity || !isExecutionVerb(activity.verb)) {
262
+ return null;
263
+ }
264
+ const it = lang === 'it';
265
+ const phrases = EXECUTION_VERBS[activity.verb];
266
+ if (activity.verb === 'EXECUTION_STOP_NOTICE_UPDATE') {
267
+ const state = stopNoticeState(activity, it);
268
+ return actorLabel(activity) + ' ' + (it ? phrases.it : phrases.en) + (state ? ': ' + state : '');
269
+ }
270
+ if (activity.verb === 'EXECUTION_RETENTION_UPDATE') {
271
+ const changes = retentionChanges(activity, it);
272
+ return actorLabel(activity) + ' ' + (it ? phrases.it : phrases.en) + (changes ? ': ' + changes : '');
273
+ }
274
+ // a denied data access is itself the rejection: its sentence has no "tried"/"(rejected: ...)" form
275
+ let rejected = activity.verb === 'EXECUTION_DATA_ACCESS_DENIED' ? null : executionRejection(activity);
276
+ // a start new whose refire got no answer: the run may have started, so it reads as started, flagged unconfirmed
277
+ const unconfirmed = !!rejected && activity.verb === 'EXECUTION_START_NEW' && rejected.reason === 'refire_unconfirmed';
278
+ if (unconfirmed) {
279
+ rejected = null;
280
+ }
281
+ const object = (activity.target && activity.target.object) || {};
282
+ const executionId = String((activity.target && activity.target.id) || '');
283
+ // the random tail of a uuid v7 (its head is the timestamp, shared by runs started close together); the same
284
+ // short id the executions destroy confirmation and the dashboard use
285
+ const shortId = executionId.replace(/-/g, '').slice(-6);
286
+ const agent = object.agent_name || (activity.related && activity.related.name) || object.agent_id || 'agent';
287
+ const phrase = rejected ? (it ? phrases.itTried : phrases.enTried) : (it ? phrases.it : phrases.en);
288
+ let message = actorLabel(activity) + ' ' + phrase + ' ' + shortId +
289
+ (it ? ' di ' : ' of ') + agent;
290
+ const mode = it ? phrases.itMode : phrases.enMode;
291
+ if (mode) {
292
+ message += ' ' + mode;
293
+ }
294
+ if (unconfirmed) {
295
+ message += it ? ' (non confermata)' : ' (unconfirmed)';
296
+ }
297
+ if (rejected) {
298
+ message += ' (' + (it ? 'rifiutato' : 'rejected') + (rejected.reason ? ': ' + shownStatus(rejected.reason) : '') + ')';
299
+ }
300
+ const reason = activity.actionObj && activity.actionObj.reason;
301
+ if (reason && activity.verb !== 'EXECUTION_DATA_ACCESS_DENIED') {
302
+ message += ' · "' + reason + '"';
303
+ }
304
+ if (activity.verb === 'EXECUTION_DATA_ACCESS') {
305
+ const scope = (activity.actionObj && activity.actionObj.scope) || {};
306
+ message += ' · ' + (scope.type === 'step' ? (it ? '1 blocco' : '1 block') : (it ? 'intera esecuzione' : 'whole execution'));
307
+ }
308
+ if (activity.verb === 'EXECUTION_DATA_ACCESS_DENIED') {
309
+ const role = activity.actionObj && activity.actionObj.role;
310
+ if (role) {
311
+ message += ' (' + (it ? 'ruolo ' : 'role ') + role + ')';
312
+ }
313
+ }
314
+ return message;
315
+ }
316
+
192
317
  function buildDefaultActivityMessage(activity) {
193
318
  if (!activity || !activity.verb) {
194
319
  return null;
@@ -310,6 +435,17 @@ function buildDefaultActivityMessage(activity) {
310
435
  return actor + ' deleted content ' + kbContentLabel(activity) +
311
436
  ' from namespace ' + namespaceLabel(activity);
312
437
 
438
+ case 'EXECUTION_STOP_SOFT':
439
+ case 'EXECUTION_STOP_HARD':
440
+ case 'EXECUTION_DESTROY':
441
+ case 'EXECUTION_RESUME':
442
+ case 'EXECUTION_START_NEW':
443
+ case 'EXECUTION_DATA_ACCESS':
444
+ case 'EXECUTION_DATA_ACCESS_DENIED':
445
+ case 'EXECUTION_RETENTION_UPDATE':
446
+ case 'EXECUTION_STOP_NOTICE_UPDATE':
447
+ return buildExecutionMessage(activity, 'en');
448
+
313
449
  default:
314
450
  return null;
315
451
  }
@@ -332,5 +468,6 @@ module.exports = {
332
468
  kbContentLabel,
333
469
  resolveParticipantLabel,
334
470
  buildDefaultActivityMessage,
471
+ buildExecutionMessage,
335
472
  enrichActivityWithMessage
336
473
  };
@@ -228,6 +228,8 @@ ActivitySchema.index({ id_project: 1, createdAt: -1 });
228
228
  ActivitySchema.index({ id_project: 1, 'actor.id': 1, createdAt: -1 });
229
229
  ActivitySchema.index({ id_project: 1, 'target.object.id_user._id': 1, createdAt: -1 });
230
230
  ActivitySchema.index({ id_project: 1, involvedUserIds: 1, createdAt: -1 });
231
+ // Idempotency of the execution audit mirror (executions-publisher audit consumer).
232
+ ActivitySchema.index({ 'actionObj.audit_id': 1 }, { unique: true, sparse: true });
231
233
  ActivitySchema.index({ createdAt: 1 }, { expireAfterSeconds: expireAfterSeconds });
232
234
 
233
235
 
@@ -50,6 +50,22 @@ function resolveActivityQueryLimit(query) {
50
50
  };
51
51
  }
52
52
 
53
+ const EXECUTION_AUDIT_PERMISSION = 'executions_audit_read';
54
+
55
+ // EXECUTION_* rows are visible to the project owner and to custom roles that carry
56
+ // the executions_audit_read permission (hasRole sets req.projectuser, with
57
+ // _doc.rolePermissions for custom roles).
58
+ function canReadExecutionAudit(projectuser) {
59
+ if (!projectuser) return false;
60
+ if (projectuser.role === 'owner') return true;
61
+ const perms = projectuser._doc && projectuser._doc.rolePermissions;
62
+ return Array.isArray(perms) && perms.includes(EXECUTION_AUDIT_PERMISSION);
63
+ }
64
+
65
+ function hideExecutionVerbs(query) {
66
+ query.verb = Object.assign({}, query.verb, { $not: /^EXECUTION_/ });
67
+ }
68
+
53
69
  router.get('/', async (req, res) => {
54
70
 
55
71
  let id_project = req.projectid;
@@ -101,6 +117,10 @@ router.get('/', async (req, res) => {
101
117
  };
102
118
  }
103
119
 
120
+ if (!canReadExecutionAudit(req.projectuser)) {
121
+ hideExecutionVerbs(query);
122
+ }
123
+
104
124
  let direction = parseInt(req.query.direction) || -1;
105
125
  let sortField = req.query.sort || "createdAt";
106
126
 
@@ -215,12 +235,16 @@ router.get('/csv', function (req, res) {
215
235
  let verbs = req.query.activities.split(",")
216
236
 
217
237
  winston.debug('verbs: ', verbs);
218
- query.verb = verbs;
238
+ query.verb = { $in: verbs };
219
239
 
220
240
  // to test
221
241
  // query.verb = ['PROJECT_USER_DELETE','PROJECT_USER_INVITE']
222
242
  }
223
243
 
244
+ if (!canReadExecutionAudit(req.projectuser)) {
245
+ hideExecutionVerbs(query);
246
+ }
247
+
224
248
  if (req.query.lang) {
225
249
  winston.debug('req.query.lang:', req.query.lang);
226
250
  var lang = req.query.lang;
@@ -579,6 +603,10 @@ router.get('/csv', function (req, res) {
579
603
  message = buildMsg_REQUEST_CREATE(lang, activity)
580
604
  }
581
605
 
606
+ if (activityMessageUtil.buildExecutionMessage(activity, lang)) {
607
+ message = activityMessageUtil.buildExecutionMessage(activity, lang);
608
+ }
609
+
582
610
  if (!message) {
583
611
  message = activityMessageUtil.buildDefaultActivityMessage(activity) || '';
584
612
  }
@@ -678,3 +706,4 @@ router.get('/csv', function (req, res) {
678
706
 
679
707
 
680
708
  module.exports = router;
709
+ module.exports.canReadExecutionAudit = canReadExecutionAudit;
@@ -0,0 +1,133 @@
1
+ process.env.NODE_ENV = 'test';
2
+
3
+ // Mounts the activities router with a stubbed req.projectuser (what hasRole sets in production),
4
+ // so the tests do not need the full app/auth harness. Mongo: a dedicated test database.
5
+ const { expect } = require('chai');
6
+ const express = require('express');
7
+ const http = require('http');
8
+ const mongoose = require('mongoose');
9
+
10
+ const Activity = require('../models/activity');
11
+ const router = require('../routes/activity');
12
+ const { canReadExecutionAudit } = router;
13
+
14
+ const MONGO = process.env.ACTIVITIES_TEST_MONGO || 'mongodb://127.0.0.1:27017/tiledesk-activities-filter-test';
15
+ const PROJECT = new mongoose.Types.ObjectId().toString();
16
+
17
+ function pu(role, rolePermissions) {
18
+ const doc = { role: role };
19
+ if (rolePermissions) doc.rolePermissions = rolePermissions;
20
+ return { role: role, _doc: doc };
21
+ }
22
+
23
+ function get(projectuser, path) {
24
+ const app = express();
25
+ app.use((req, res, next) => { req.projectid = PROJECT; req.projectuser = projectuser; next(); });
26
+ app.use('/', router);
27
+ return new Promise((resolve, reject) => {
28
+ const srv = app.listen(0, () => {
29
+ http.get({ port: srv.address().port, path: path }, (res) => {
30
+ let body = '';
31
+ res.on('data', (c) => body += c);
32
+ res.on('end', () => { srv.close(); resolve({ status: res.statusCode, body: body }); });
33
+ }).on('error', (e) => { srv.close(); reject(e); });
34
+ });
35
+ });
36
+ }
37
+
38
+ describe('activities: EXECUTION_* rows are owner-only', function () {
39
+ this.timeout(20000);
40
+
41
+ before(async function () {
42
+ // run together with other suites: reuse their connection (rows are scoped by PROJECT)
43
+ if (mongoose.connection.readyState === 0) await mongoose.connect(MONGO);
44
+ await Activity.deleteMany({ id_project: PROJECT });
45
+ const mk = (verb) => ({ id_project: PROJECT, verb: verb, actor: { type: 'user', id: 'u1', name: 'Mario' },
46
+ target: { type: 'execution', id: 'abcdef123456', object: { agent_name: 'Bot' } }, actionObj: {} });
47
+ await Activity.create([mk('EXECUTION_DESTROY'), mk('EXECUTION_STOP_SOFT'), mk('REQUEST_CLOSE')]);
48
+ });
49
+
50
+ after(async function () {
51
+ await Activity.deleteMany({ id_project: PROJECT });
52
+ await mongoose.disconnect();
53
+ });
54
+
55
+ const verbsOf = (r) => JSON.parse(r.body).activities.map((a) => a.verb).sort();
56
+
57
+ it('canReadExecutionAudit', function () {
58
+ expect(canReadExecutionAudit(pu('owner'))).to.equal(true);
59
+ expect(canReadExecutionAudit(pu('admin'))).to.equal(false);
60
+ expect(canReadExecutionAudit(pu('custom', ['executions_audit_read']))).to.equal(true);
61
+ expect(canReadExecutionAudit(pu('custom', ['other']))).to.equal(false);
62
+ expect(canReadExecutionAudit(undefined)).to.equal(false);
63
+ });
64
+
65
+ it('owner sees EXECUTION_ rows', async function () {
66
+ const r = await get(pu('owner'), '/');
67
+ expect(r.status).to.equal(200);
68
+ expect(verbsOf(r)).to.deep.equal(['EXECUTION_DESTROY', 'EXECUTION_STOP_SOFT', 'REQUEST_CLOSE']);
69
+ });
70
+
71
+ it('data access and retention rows (retention has a project target) are owner-only too', async function () {
72
+ const base = { id_project: PROJECT, actor: { type: 'user', id: 'u1', name: 'Mario' }, actionObj: {} };
73
+ const rows = await Activity.create([
74
+ Object.assign({ verb: 'EXECUTION_DATA_ACCESS', target: { type: 'execution', id: 'abcdef123456', object: {} } }, base),
75
+ Object.assign({ verb: 'EXECUTION_DATA_ACCESS_DENIED', target: { type: 'execution', id: 'abcdef123456', object: {} } }, base),
76
+ Object.assign({ verb: 'EXECUTION_RETENTION_UPDATE', target: { type: 'project', id: PROJECT, object: {} } }, base)
77
+ ]);
78
+ try {
79
+ const owner = verbsOf(await get(pu('owner'), '/'));
80
+ expect(owner).to.include.members(['EXECUTION_DATA_ACCESS', 'EXECUTION_DATA_ACCESS_DENIED', 'EXECUTION_RETENTION_UPDATE']);
81
+ expect(verbsOf(await get(pu('admin'), '/'))).to.deep.equal(['REQUEST_CLOSE']);
82
+ } finally {
83
+ await Activity.deleteMany({ _id: { $in: rows.map((r) => r._id) } });
84
+ }
85
+ });
86
+
87
+ it('admin does not (list)', async function () {
88
+ const r = await get(pu('admin'), '/');
89
+ expect(verbsOf(r)).to.deep.equal(['REQUEST_CLOSE']);
90
+ expect(JSON.parse(r.body).count).to.equal(1);
91
+ });
92
+
93
+ it('csv for admin excludes EXECUTION_ verbs', async function () {
94
+ const r = await get(pu('admin'), '/csv');
95
+ expect(r.status).to.equal(200);
96
+ expect(r.body).to.not.contain('EXECUTION_');
97
+ expect(r.body).to.contain('REQUEST_CLOSE');
98
+ });
99
+
100
+ it('csv for owner includes EXECUTION_ verbs, also when filtered', async function () {
101
+ const r = await get(pu('owner'), '/csv?activities=EXECUTION_DESTROY,REQUEST_CLOSE');
102
+ expect(r.body).to.contain('EXECUTION_DESTROY');
103
+ expect(r.body).to.contain('REQUEST_CLOSE');
104
+ expect(r.body).to.not.contain('EXECUTION_STOP_SOFT');
105
+ });
106
+
107
+ it('csv for admin with a verb filter keeps non-execution verbs only', async function () {
108
+ const r = await get(pu('admin'), '/csv?activities=EXECUTION_DESTROY,REQUEST_CLOSE');
109
+ expect(r.body).to.not.contain('EXECUTION_');
110
+ expect(r.body).to.contain('REQUEST_CLOSE');
111
+ });
112
+
113
+ it('custom role with executions_audit_read sees them', async function () {
114
+ const r = await get(pu('auditor', ['executions_audit_read']), '/');
115
+ expect(verbsOf(r)).to.include('EXECUTION_DESTROY');
116
+ });
117
+
118
+ it('custom role without the permission does not', async function () {
119
+ const r = await get(pu('other', ['something']), '/');
120
+ expect(verbsOf(r)).to.deep.equal(['REQUEST_CLOSE']);
121
+ });
122
+
123
+ it('requested activities=EXECUTION_DESTROY for admin returns none', async function () {
124
+ const r = await get(pu('admin'), '/?activities=EXECUTION_DESTROY');
125
+ expect(JSON.parse(r.body).activities).to.have.length(0);
126
+ expect(JSON.parse(r.body).count).to.equal(0);
127
+ });
128
+
129
+ it('requested activities=EXECUTION_DESTROY for owner returns it', async function () {
130
+ const r = await get(pu('owner'), '/?activities=EXECUTION_DESTROY');
131
+ expect(verbsOf(r)).to.deep.equal(['EXECUTION_DESTROY']);
132
+ });
133
+ });