@tiledesk/tiledesk-server 3.3.5 → 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 +17 -0
  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 +1 -1
  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.5",
4
+ "version": "3.5.0",
5
5
  "scripts": {
6
6
  "start": "node ./bin/www",
7
7
  "quota-restore": "node ./bin/quota-restore",
@@ -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
+ });
@@ -0,0 +1,158 @@
1
+ process.env.NODE_ENV = 'test';
2
+
3
+ const { expect } = require('chai');
4
+ const util = require('../activityMessageUtil');
5
+
6
+ function act(verb, reason) {
7
+ return {
8
+ verb: verb,
9
+ actor: { type: 'user', id: 'u1', name: 'Mario' },
10
+ target: { type: 'execution', id: 'abcdef123456', object: { agent_name: 'Support Bot' } },
11
+ actionObj: reason ? { reason: reason } : {}
12
+ };
13
+ }
14
+
15
+ describe('execution activity messages', function () {
16
+ it('sentences en/it for each verb', function () {
17
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_STOP_SOFT')))
18
+ .to.equal('Mario paused execution 123456 of Support Bot after the current action');
19
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_STOP_HARD')))
20
+ .to.equal('Mario paused execution 123456 of Support Bot now');
21
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_DESTROY')))
22
+ .to.equal('Mario destroyed execution 123456 of Support Bot');
23
+ expect(util.buildExecutionMessage(act('EXECUTION_STOP_SOFT'), 'it'))
24
+ .to.equal('Mario ha messo in pausa l\'esecuzione 123456 di Support Bot dopo l\'azione corrente');
25
+ expect(util.buildExecutionMessage(act('EXECUTION_STOP_HARD'), 'it'))
26
+ .to.equal('Mario ha messo in pausa l\'esecuzione 123456 di Support Bot subito');
27
+ expect(util.buildExecutionMessage(act('EXECUTION_DESTROY'), 'it'))
28
+ .to.equal('Mario ha eliminato l\'esecuzione 123456 di Support Bot');
29
+ expect(util.buildExecutionMessage(act('EXECUTION_DESTROY'), 'en'))
30
+ .to.equal('Mario destroyed execution 123456 of Support Bot');
31
+ });
32
+
33
+ it('the short id is the random tail of a uuid v7 (last 6 hex chars without dashes), not its timestamp prefix', function () {
34
+ const a = act('EXECUTION_DESTROY');
35
+ a.target.id = '01a1c193-4e44-73c1-91d5-373a5c5d8888';
36
+ expect(util.buildDefaultActivityMessage(a)).to.equal('Mario destroyed execution 5d8888 of Support Bot');
37
+ });
38
+
39
+ it('appends the reason when present', function () {
40
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_DESTROY', 'cleanup')))
41
+ .to.equal('Mario destroyed execution 123456 of Support Bot · "cleanup"');
42
+ expect(util.buildExecutionMessage(act('EXECUTION_STOP_SOFT', 'x'), 'it'))
43
+ .to.equal('Mario ha messo in pausa l\'esecuzione 123456 di Support Bot dopo l\'azione corrente · "x"');
44
+ });
45
+
46
+ it('a rejected control reads as an attempt, with the reason it was refused (en/it)', function () {
47
+ const rej = (verb, result, reason) => Object.assign(act(verb, reason), { actionObj: Object.assign({ result: result }, reason ? { reason: reason } : {}) });
48
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_STOP_HARD', 'rejected:stopped')))
49
+ .to.equal('Mario tried to pause execution 123456 of Support Bot now (rejected: paused)');
50
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_STOP_SOFT', 'rejected:completed')))
51
+ .to.equal('Mario tried to pause execution 123456 of Support Bot after the current action (rejected: completed)');
52
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_DESTROY', 'rejected:destroyed', 'again')))
53
+ .to.equal('Mario tried to destroy execution 123456 of Support Bot (rejected: destroyed) · "again"');
54
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_DESTROY', 'rejected')))
55
+ .to.equal('Mario tried to destroy execution 123456 of Support Bot (rejected)');
56
+ expect(util.buildExecutionMessage(rej('EXECUTION_STOP_HARD', 'rejected:stopped'), 'it'))
57
+ .to.equal('Mario ha provato a mettere in pausa l\'esecuzione 123456 di Support Bot subito (rifiutato: paused)');
58
+ expect(util.buildExecutionMessage(rej('EXECUTION_STOP_SOFT', 'rejected:completed'), 'it'))
59
+ .to.equal('Mario ha provato a mettere in pausa l\'esecuzione 123456 di Support Bot dopo l\'azione corrente (rifiutato: completed)');
60
+ expect(util.buildExecutionMessage(rej('EXECUTION_DESTROY', 'rejected:destroyed'), 'it'))
61
+ .to.equal('Mario ha provato a eliminare l\'esecuzione 123456 di Support Bot (rifiutato: destroyed)');
62
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_DESTROY', 'rejected:stopping')))
63
+ .to.equal('Mario tried to destroy execution 123456 of Support Bot (rejected: pausing)');
64
+ // accepted (or no result, as older rows): the plain sentence
65
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_STOP_HARD', 'accepted')))
66
+ .to.equal('Mario paused execution 123456 of Support Bot now');
67
+ });
68
+
69
+ it('audit resume/start_new map to the new verbs and sentences en/it', function () {
70
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_RESUME')))
71
+ .to.equal('Mario resumed execution 123456 of Support Bot');
72
+ expect(util.buildDefaultActivityMessage(act('EXECUTION_START_NEW')))
73
+ .to.equal('Mario started a new run of execution 123456 of Support Bot');
74
+ expect(util.buildExecutionMessage(act('EXECUTION_RESUME'), 'it'))
75
+ .to.equal('Mario ha ripreso l\'esecuzione 123456 di Support Bot');
76
+ expect(util.buildExecutionMessage(act('EXECUTION_START_NEW'), 'it'))
77
+ .to.equal('Mario ha avviato una nuova esecuzione da 123456 di Support Bot');
78
+ expect(util.buildExecutionMessage(act('EXECUTION_START_NEW', 'retry'), 'en'))
79
+ .to.equal('Mario started a new run of execution 123456 of Support Bot · "retry"');
80
+
81
+ const rej = (verb, result) => Object.assign(act(verb), { actionObj: { result: result } });
82
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_RESUME', 'rejected:not_resumable')))
83
+ .to.equal('Mario tried to resume execution 123456 of Support Bot (rejected: not_resumable)');
84
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_START_NEW', 'rejected:already_started')))
85
+ .to.equal('Mario tried to start a new run of execution 123456 of Support Bot (rejected: already_started)');
86
+ expect(util.buildExecutionMessage(rej('EXECUTION_RESUME', 'rejected:not_resumable'), 'it'))
87
+ .to.equal('Mario ha provato a riprendere l\'esecuzione 123456 di Support Bot (rifiutato: not_resumable)');
88
+ expect(util.buildExecutionMessage(rej('EXECUTION_START_NEW', 'rejected:already_started'), 'it'))
89
+ .to.equal('Mario ha provato ad avviare una nuova esecuzione da 123456 di Support Bot (rifiutato: already_started)');
90
+
91
+ // an unconfirmed refire may have started the run: it reads as started, flagged
92
+ expect(util.buildDefaultActivityMessage(rej('EXECUTION_START_NEW', 'rejected:refire_unconfirmed')))
93
+ .to.equal('Mario started a new run of execution 123456 of Support Bot (unconfirmed)');
94
+ expect(util.buildExecutionMessage(rej('EXECUTION_START_NEW', 'rejected:refire_unconfirmed'), 'it'))
95
+ .to.equal('Mario ha avviato una nuova esecuzione da 123456 di Support Bot (non confermata)');
96
+ // other verbs keep the tried phrasing
97
+ expect(util.buildExecutionMessage(rej('EXECUTION_RESUME', 'rejected:refire_unconfirmed'), 'en'))
98
+ .to.equal('Mario tried to resume execution 123456 of Support Bot (rejected: refire_unconfirmed)');
99
+ });
100
+
101
+ describe('data access and retention', function () {
102
+ const da = (verb, actionObj) => Object.assign(act(verb), { actionObj: actionObj });
103
+ const ret = (before, after) => ({
104
+ verb: 'EXECUTION_RETENTION_UPDATE',
105
+ actor: { type: 'user', id: 'u1', name: 'Mario' },
106
+ target: { type: 'project', id: 'p1', object: {} },
107
+ actionObj: { result: 'accepted', retention: { before: before, after: after } }
108
+ });
109
+
110
+ it('EXECUTION_DATA_ACCESS: reason + one block or whole execution (en/it)', function () {
111
+ const step = da('EXECUTION_DATA_ACCESS', { result: 'accepted', reason: 'debug', scope: { type: 'step', step_seq: 3 } });
112
+ const whole = da('EXECUTION_DATA_ACCESS', { result: 'accepted', reason: 'debug', scope: { type: 'execution' } });
113
+ expect(util.buildDefaultActivityMessage(step))
114
+ .to.equal('Mario viewed the data of execution 123456 of Support Bot · "debug" · 1 block');
115
+ expect(util.buildDefaultActivityMessage(whole))
116
+ .to.equal('Mario viewed the data of execution 123456 of Support Bot · "debug" · whole execution');
117
+ expect(util.buildExecutionMessage(step, 'it'))
118
+ .to.equal('Mario ha visualizzato i dati dell\'esecuzione 123456 di Support Bot · "debug" · 1 blocco');
119
+ expect(util.buildExecutionMessage(whole, 'it'))
120
+ .to.equal('Mario ha visualizzato i dati dell\'esecuzione 123456 di Support Bot · "debug" · intera esecuzione');
121
+ });
122
+
123
+ it('EXECUTION_DATA_ACCESS_DENIED carries the role (en/it)', function () {
124
+ const a = da('EXECUTION_DATA_ACCESS_DENIED', { result: 'rejected:forbidden', role: 'agent' });
125
+ expect(util.buildDefaultActivityMessage(a))
126
+ .to.equal('Mario was denied access to the data of execution 123456 of Support Bot (role agent)');
127
+ expect(util.buildExecutionMessage(a, 'it'))
128
+ .to.equal('Mario non ha ottenuto l\'accesso ai dati dell\'esecuzione 123456 di Support Bot (ruolo agent)');
129
+ });
130
+
131
+ it('EXECUTION_STOP_NOTICE_UPDATE states the setting after the change (en/it)', function () {
132
+ const sn = (after) => ({ verb: 'EXECUTION_STOP_NOTICE_UPDATE', actor: { type: 'user', id: 'u1', name: 'Mario' },
133
+ target: { type: 'project', id: 'p1', object: {} }, actionObj: { result: 'accepted', stop_notice: { before: { enabled: true, text: null }, after } } });
134
+ expect(util.buildDefaultActivityMessage(sn({ enabled: false, text: null })))
135
+ .to.equal('Mario changed the executions pause notice: off');
136
+ expect(util.buildDefaultActivityMessage(sn({ enabled: true, text: 'Back soon' })))
137
+ .to.equal('Mario changed the executions pause notice: on, custom text');
138
+ expect(util.buildExecutionMessage(sn({ enabled: true, text: null }), 'it'))
139
+ .to.equal("Mario ha modificato l'avviso di esecuzione in pausa: attivo, testo predefinito");
140
+ expect(util.buildDefaultActivityMessage(Object.assign(sn({}), { actionObj: {} })))
141
+ .to.equal('Mario changed the executions pause notice');
142
+ });
143
+
144
+ it('EXECUTION_RETENTION_UPDATE shows only the changed parts (en/it)', function () {
145
+ const both = ret({ trace_days: 90, data_days: 30 }, { trace_days: 30, data_days: 7 });
146
+ expect(util.buildDefaultActivityMessage(both))
147
+ .to.equal('Mario changed executions retention: trace 90 → 30 days, data 30 → 7 days');
148
+ expect(util.buildExecutionMessage(both, 'it'))
149
+ .to.equal('Mario ha modificato la conservazione delle esecuzioni: tracce 90 → 30 giorni, dati 30 → 7 giorni');
150
+ const onlyTrace = ret({ trace_days: 90, data_days: 30 }, { trace_days: 60, data_days: 30 });
151
+ expect(util.buildDefaultActivityMessage(onlyTrace))
152
+ .to.equal('Mario changed executions retention: trace 90 → 60 days');
153
+ const onlyData = ret({ trace_days: 90, data_days: 30 }, { trace_days: 90, data_days: 0 });
154
+ expect(util.buildExecutionMessage(onlyData, 'it'))
155
+ .to.equal('Mario ha modificato la conservazione delle esecuzioni: dati 30 → 0 giorni');
156
+ });
157
+ });
158
+ });