domma-cms 1.58.0 → 1.60.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.
@@ -11,6 +11,8 @@
11
11
  * That asymmetry is preserved rather than tidied - changing who can see a group
12
12
  * is a behaviour change, and this was a relocation. A test pins it so the next
13
13
  * reader finds it stated rather than inferred.
14
+ * The one exception is a `contacts-restricted` person (RESTRICTED below), who
15
+ * sees and uses only the groups they created.
14
16
  *
15
17
  * Because a group is shared, renaming or deleting one rewrites every user's
16
18
  * contacts. So only the group's creator (`meta.createdBy`, recorded on new
@@ -33,7 +35,7 @@ import {registerToolTrash, trashToolEntry} from '../../services/tool-trash.js';
33
35
  import {authenticate as defaultAuthenticate, requirePermission as defaultRequirePermission} from '../../middleware/auth.js';
34
36
  import {createEntry, deleteEntry, getEntry, listEntries, updateEntry} from '../../services/collections.js';
35
37
  import {hooks} from '../../services/hooks.js';
36
- import {getPermissionsFor} from '../../services/roles.js';
38
+ import {getPermissionsFor, getPermissionsForRole, getRoleLevel} from '../../services/roles.js';
37
39
  import {getEffectiveRoles} from '../../services/userRoles.js';
38
40
  import {ago, clip, plural} from '../../services/sidebarBadges.js';
39
41
 
@@ -59,6 +61,44 @@ function defaultHoldsManageGroups(request) {
59
61
  return getEffectiveRoles(request.user).some(r => allowed.includes(r));
60
62
  }
61
63
 
64
+ /**
65
+ * `contacts-restricted`: Contacts for a person's own address book and nothing
66
+ * more - for outside accounts such as a Job Board candidate or hiring company.
67
+ * Groups are shared on the site, so a restricted person sees, uses and counts
68
+ * only the groups they created themselves, and can put a contact only in one
69
+ * of those. Someone else's group is "not found" to them. Contacts Pro reads
70
+ * the same permission for its own surfaces (people list, sharing, fields).
71
+ */
72
+ export const RESTRICTED = 'contacts-restricted';
73
+
74
+ /**
75
+ * The rule, pure (the lookups are passed in) - the same as Docs' docs-restricted:
76
+ * restricted when a role held carries the mark and no role held opens Contacts
77
+ * without it. A level-0 role is never restricted.
78
+ *
79
+ * @param {string[]} roles - every role the person holds
80
+ * @param {{isRoot: Function, marked: Function, givesContacts: Function}} look
81
+ * @returns {boolean}
82
+ */
83
+ export function contactsRestricted(roles, {isRoot, marked, givesContacts}) {
84
+ const list = (Array.isArray(roles) ? roles : []).filter(r => typeof r === 'string' && r);
85
+ if (!list.length || list.some(isRoot)) return false;
86
+ if (!list.some(marked)) return false;
87
+ return !list.some(r => givesContacts(r) && !marked(r));
88
+ }
89
+
90
+ /** Is the caller restricted? A lookup that throws restricts (fail closed). */
91
+ function defaultIsRestricted(request) {
92
+ if (!request.user) return false;
93
+ try {
94
+ return contactsRestricted(getEffectiveRoles(request.user), {
95
+ isRoot: (r) => getRoleLevel(r) === 0,
96
+ marked: (r) => getPermissionsForRole(r).some(p => p === RESTRICTED || String(p).startsWith(`${RESTRICTED}.`)),
97
+ givesContacts: (r) => getPermissionsFor('contacts', 'read').includes(r)
98
+ });
99
+ } catch { return true; }
100
+ }
101
+
62
102
  const CONTACTS_SLUG = 'contacts-contacts';
63
103
  const GROUPS_SLUG = 'contacts-groups';
64
104
 
@@ -114,6 +154,7 @@ export async function contactsRoutes(fastify, opts = {}) {
114
154
  const authenticate = opts.authenticate || defaultAuthenticate;
115
155
  const requirePermission = opts.requirePermission || defaultRequirePermission;
116
156
  const holdsManageGroups = opts.holdsManageGroups || defaultHoldsManageGroups;
157
+ const isRestricted = opts.isRestricted || defaultIsRestricted;
117
158
 
118
159
  registerToolTrash(fastify, {slug: CONTACTS_SLUG, resource: 'contacts', itemPath: '/contacts', authenticate, requirePermission, project: toContact, onPurge: entry => hooks.emit('contact:deleted', {id: entry.id, userId: entry.data.userId})});
119
160
 
@@ -133,6 +174,21 @@ export async function contactsRoutes(fastify, opts = {}) {
133
174
  return entries.map(e => ({id: e.id, name: toGroupName(e), createdBy: e.meta?.createdBy ?? null}));
134
175
  }
135
176
 
177
+ /** The groups this caller sees: every group, or a restricted person's own. */
178
+ async function visibleGroups(request) {
179
+ const groups = await loadGroups();
180
+ if (!isRestricted(request)) return groups;
181
+ const uid = userId(request);
182
+ return groups.filter(g => uid && g.createdBy === uid);
183
+ }
184
+
185
+ /** A contact's `groups` as this caller may set them: a restricted person's own groups only. */
186
+ async function allowedGroups(request, contact) {
187
+ if (!Array.isArray(contact.groups) || !contact.groups.length || !isRestricted(request)) return contact;
188
+ const mine = new Set((await visibleGroups(request)).map(g => g.name));
189
+ return {...contact, groups: contact.groups.filter(g => mine.has(g))};
190
+ }
191
+
136
192
  /**
137
193
  * May this caller rename or delete this group? Its creator may; so may
138
194
  * anyone holding contacts.manageGroups. A group from before creators were
@@ -141,7 +197,7 @@ export async function contactsRoutes(fastify, opts = {}) {
141
197
  function canManageGroup(request, group) {
142
198
  const uid = userId(request);
143
199
  if (uid && group.createdBy && group.createdBy === uid) return true;
144
- return holdsManageGroups(request) === true;
200
+ return !isRestricted(request) && holdsManageGroups(request) === true;
145
201
  }
146
202
 
147
203
  const NOT_YOURS = 'Only the person who created this group, or someone allowed to manage every group, can rename or delete it.';
@@ -152,7 +208,7 @@ export async function contactsRoutes(fastify, opts = {}) {
152
208
 
153
209
  /** GET /api/contacts/count - the sidebar badge (contactsBadge). */
154
210
  fastify.get('/count', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request) => {
155
- const [contacts, groups] = await Promise.all([loadContacts(userId(request)), loadGroups()]);
211
+ const [contacts, groups] = await Promise.all([loadContacts(userId(request)), visibleGroups(request)]);
156
212
  return contactsBadge(contacts, groups.length);
157
213
  });
158
214
 
@@ -191,7 +247,7 @@ export async function contactsRoutes(fastify, opts = {}) {
191
247
  return reply.code(400).send({ error: 'name is required' });
192
248
  }
193
249
 
194
- const entry = await createEntry(CONTACTS_SLUG, buildContact(body, uid),
250
+ const entry = await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(body, uid)),
195
251
  {createdBy: uid, source: 'admin'});
196
252
 
197
253
  return reply.code(201).send(toContact(entry));
@@ -210,7 +266,7 @@ export async function contactsRoutes(fastify, opts = {}) {
210
266
  // Coerced exactly as create (buildContact) does: the editor sends
211
267
  // payment terms as the input's string and a PUT used to store "30"
212
268
  // where a POST stores 30 - and a bare `favourite: "false"` was truthy.
213
- const shaped = buildContact({...entry.data, ...updates}, entry.data.userId ?? null);
269
+ const shaped = await allowedGroups(request, buildContact({...entry.data, ...updates}, entry.data.userId ?? null));
214
270
  const merged = {...entry.data};
215
271
  for (const key of TEXT_FIELDS) {
216
272
  if (key in updates) merged[key] = shaped[key];
@@ -280,7 +336,7 @@ export async function contactsRoutes(fastify, opts = {}) {
280
336
 
281
337
  /** GET /api/contacts/groups */
282
338
  fastify.get('/groups', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
283
- const groups = await loadGroups();
339
+ const groups = await visibleGroups(request);
284
340
  return reply.send(groups.map(g => g.name));
285
341
  });
286
342
 
@@ -291,8 +347,8 @@ export async function contactsRoutes(fastify, opts = {}) {
291
347
  */
292
348
  fastify.get('/groups/access', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
293
349
  const uid = userId(request);
294
- const manageAll = holdsManageGroups(request) === true;
295
- const groups = await loadGroups();
350
+ const manageAll = !isRestricted(request) && holdsManageGroups(request) === true;
351
+ const groups = await visibleGroups(request);
296
352
  return reply.send({
297
353
  manageAll,
298
354
  groups: groups.map(g => {
@@ -331,7 +387,7 @@ export async function contactsRoutes(fastify, opts = {}) {
331
387
  }
332
388
 
333
389
  const groups = await loadGroups();
334
- const grpEntry = groups.find(g => g.name === oldName);
390
+ const grpEntry = (await visibleGroups(request)).find(g => g.name === oldName);
335
391
  if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
336
392
  if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
337
393
 
@@ -362,8 +418,7 @@ export async function contactsRoutes(fastify, opts = {}) {
362
418
  fastify.delete('/groups/:name', {preHandler: [authenticate, requirePermission('contacts', 'delete')]}, async (request, reply) => {
363
419
  const name = decodeURIComponent(request.params.name);
364
420
 
365
- const groups = await loadGroups();
366
- const grpEntry = groups.find(g => g.name === name);
421
+ const grpEntry = (await visibleGroups(request)).find(g => g.name === name);
367
422
  if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
368
423
  if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
369
424
 
@@ -410,7 +465,7 @@ export async function contactsRoutes(fastify, opts = {}) {
410
465
  let imported = 0;
411
466
  for (const raw of incoming) {
412
467
  if (!raw || typeof raw.name !== 'string') continue;
413
- await createEntry(CONTACTS_SLUG, buildContact(raw, uid), {source: 'import'});
468
+ await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(raw, uid)), {source: 'import'});
414
469
  imported++;
415
470
  }
416
471
 
package/server/server.js CHANGED
@@ -778,6 +778,17 @@ try {
778
778
  (await import('./services/passwordReset.js')).registerPasswordChangeNotice({log: app.log});
779
779
 
780
780
  await registerPlugins(app);
781
+ // AI Assist (Pro) owns every chat: its screen takes the Chats entry's place, which keeps
782
+ // its spot in a saved menu. Plugins load once per process (a switch restarts it).
783
+ {
784
+ const {isAiAssist} = await import('./services/aiAssist.js');
785
+ if (isAiAssist()) {
786
+ const url = isToolEnabled('launchers') ? '#/ai-assist/chats' : '#/ai-assist/settings';
787
+ registerSidebarItem({item: {source: 'Built in', text: 'AI Assist', url, icon: 'sparkles', permission: isToolEnabled('launchers') ? 'chats' : 'settings',
788
+ ...(isToolEnabled('launchers') && {countUrl: '/api/chats/_count'})}});
789
+ hideSidebarUrl('#/launchers/chats', url);
790
+ }
791
+ }
781
792
  // After the plugins' onRequest hooks - see serve() in services/adminAssets.js.
782
793
  adminAssets.serve();
783
794
 
@@ -38,6 +38,18 @@ export function isAiAssist() {
38
38
  return owners.size > 0;
39
39
  }
40
40
 
41
+ /** The AI Assist screen (admin #/ai-assist): Chats, Knowledge and Settings when the Tool is on. */
42
+ export const AI_ASSIST_CHATS = '#/ai-assist/chats';
43
+ export const LAUNCHER_CHATS = '#/launchers/chats';
44
+
45
+ /**
46
+ * Where the staff answer chats: AI Assist owns every chat on a site that has it;
47
+ * a site without it keeps the plain Chats screen under Launchers.
48
+ */
49
+ export function chatsHome() {
50
+ return isAiAssist() ? AI_ASSIST_CHATS : LAUNCHER_CHATS;
51
+ }
52
+
41
53
  /** Tests only: forget every owner. */
42
54
  export function _resetAiAssistForTests() {
43
55
  owners.clear();
@@ -82,8 +82,19 @@ async function ask(payload, {env, fetchFn}) {
82
82
  * @param {{botName: string, aiContext?: string, aiRules?: string, useKnowledge?: boolean}} chat - the launcher's chat block
83
83
  * @returns {Promise<string>} the answer, or '' (no answer: carry on without)
84
84
  */
85
- export async function aiAnswer(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
86
- if (!aiAvailable(env)) return '';
85
+ export async function aiAnswer(id, question, chat, opts = {}) {
86
+ return (await aiReply(id, question, chat, opts)).text;
87
+ }
88
+
89
+ /**
90
+ * As aiAnswer, and whether the AI turned the question down (off-topic, or the rules forbid it): its polite
91
+ * reply, if any, is still the text. The site tells its admins (conversation.js).
92
+ *
93
+ * @returns {Promise<{text: string, declined: boolean}>}
94
+ */
95
+ export async function aiReply(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
96
+ const none = {text: '', declined: false};
97
+ if (!aiAvailable(env)) return none;
87
98
  try {
88
99
  const brief = assistantBrief(chat);
89
100
  const {byId} = chat.useKnowledge === false ? {byId: new Map()} : await knowledgeIndex();
@@ -98,13 +109,13 @@ export async function aiAnswer(id, question, chat, {env = process.env, fetchFn =
98
109
  question
99
110
  };
100
111
  const {status, body} = await ask(payload, {env, fetchFn});
101
- if (status === 200) return typeof body?.answer === 'string' ? body.answer.trim() : '';
112
+ if (status === 200) return {text: typeof body?.answer === 'string' ? body.answer.trim() : '', declined: body?.declined === true};
102
113
  restUntil = Date.now() + (BACKOFF_MS[status] || BACKOFF_MS.other);
103
114
  if (status !== 429) log.warn?.(`[chat] AI answers unavailable (${status}): ${String(body?.error || '').slice(0, 120)}`);
104
- return '';
115
+ return none;
105
116
  } catch (err) {
106
117
  restUntil = Date.now() + BACKOFF_MS.other;
107
118
  log.warn?.(`[chat] AI answer failed: ${err.message}`);
108
- return '';
119
+ return none;
109
120
  }
110
121
  }
@@ -22,14 +22,19 @@
22
22
  */
23
23
  import {match} from './matcher.js';
24
24
  import {notify, registerNotificationSource, resolveNotification} from '../notify.js';
25
+ import {chatsHome} from '../aiAssist.js';
25
26
  import {
26
27
  addMessage, cleanText, countHit, forgetSession, getSession, knowledgeIndex, listSessions, logUnanswered, messagesAfter,
27
28
  patchSession, removeSession, removeSessionsAndOrphans, renderAnswer, staffAvailable, withChat
28
29
  } from './store.js';
29
30
  import {readChatSettings, staffDisplayName} from './settings.js';
30
- import {aiAnswer} from './ai.js';
31
+ import {aiReply} from './ai.js';
31
32
 
32
33
  export const SOURCE = 'core:chat';
34
+ /** A visitor started a chat (their first message). */
35
+ export const STARTED_SOURCE = 'core:chat-started';
36
+ /** The AI turned a visitor's question down (off-topic, or the launcher's rules forbid it). */
37
+ export const DECLINED_SOURCE = 'core:chat-declined';
33
38
  const int = (v) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : 0);
34
39
  const ACTIVE = ['waiting', 'open', 'message'];
35
40
 
@@ -60,6 +65,16 @@ export function registerChatSource() {
60
65
  description: 'A visitor asked to talk to a person, or left a message for the team because nobody was available.',
61
66
  severity: 'info', audience: 'admins'
62
67
  });
68
+ registerNotificationSource({
69
+ id: STARTED_SOURCE, owner: 'core', label: 'Visitor chat started',
70
+ description: 'A visitor started a chat, whether the bot or a person answers it.',
71
+ severity: 'info', audience: 'admins'
72
+ });
73
+ registerNotificationSource({
74
+ id: DECLINED_SOURCE, owner: 'core', label: 'Chat question turned down',
75
+ description: 'The AI turned down a visitor\'s question in chat: off-topic, or something the launcher\'s rules forbid.',
76
+ severity: 'info', audience: 'admins'
77
+ });
63
78
  }
64
79
 
65
80
  const noticeKey = (id) => `chat:${id}`;
@@ -72,10 +87,38 @@ function raise(session, kind) {
72
87
  const notice = kind === 'message'
73
88
  ? {severity: 'info', title: `${who} left a message in chat`, body: `Nobody was available, so they left their details${d.visitorEmail ? ` (${d.visitorEmail})` : ''}.${about}${where}`}
74
89
  : {severity: 'warning', title: `${who} wants to talk to a person`, body: `They are waiting in chat now.${about}${where}`};
75
- return notify({...notice, source: SOURCE, dedupeKey: noticeKey(session.id), link: '#/launchers/chats'}).catch(() => null);
90
+ return notify({...notice, source: SOURCE, dedupeKey: noticeKey(session.id), link: chatsHome()}).catch(() => null);
76
91
  }
77
92
 
78
- const settle = (id) => resolveNotification(noticeKey(id), SOURCE).catch(() => 0);
93
+ /**
94
+ * Someone took the chat, or it ended: its "wants a person" and "started a chat"
95
+ * notices are settled, which also closes their pop-ups in every admin (chat-toast.js).
96
+ */
97
+ const settle = (id) => Promise.all([
98
+ resolveNotification(noticeKey(id), SOURCE).catch(() => 0),
99
+ resolveNotification(`chat-started:${id}`, STARTED_SOURCE).catch(() => 0)
100
+ ]);
101
+
102
+ /** What the admins are told about the chat: the visitor's words (as the Chats screen shows them) and the page. */
103
+ const quoted = (text) => `"${cleanText(text, 200).replace(/\n/g, ' ')}"`;
104
+
105
+ /** A visitor's first message: the chat has started. */
106
+ function raiseStarted(session, text, chat) {
107
+ const d = session.data;
108
+ const where = d.page ? `\nPage: ${d.page}` : '';
109
+ const who = chat.bot ? `${chat.botName || 'The bot'} is answering.` : 'It is waiting for a person.';
110
+ return notify({severity: 'info', title: `${d.visitorName || 'A visitor'} started a chat`, body: `${quoted(text)}\n\n${who}${where}`,
111
+ source: STARTED_SOURCE, dedupeKey: `chat-started:${session.id}`, link: chatsHome()}).catch(() => null);
112
+ }
113
+
114
+ /** The AI turned a question down. One notice per chat, said again in place for the next. */
115
+ function raiseDeclined(session, text, chat) {
116
+ const d = session.data;
117
+ const where = d.page ? `\nPage: ${d.page}` : '';
118
+ return notify({severity: 'info', title: `${chat.botName || 'The bot'} turned down a question in chat`,
119
+ body: `${d.visitorName || 'A visitor'} asked: ${quoted(text)}\n\nIt is off-topic or against the launcher's rules, so it was not answered.${where}`,
120
+ source: DECLINED_SOURCE, dedupeKey: `chat-declined:${session.id}`, link: chatsHome()}).catch(() => null);
121
+ }
79
122
 
80
123
  // ---------------------------------------------------------------------------
81
124
  // What visitors and staff see
@@ -168,7 +211,8 @@ async function aiTurn(id, text, chat, session) {
168
211
  if (!chat.ai) return null;
169
212
  const used = int(session?.data.aiCount);
170
213
  if (used >= int(chat.aiMaxPerChat ?? 20)) return null;
171
- const said = await aiAnswer(id, text, chat);
214
+ const {text: said, declined} = await aiReply(id, text, chat);
215
+ if (declined && session) raiseDeclined(session, text, chat);
172
216
  return said ? addMessage(id, {from: 'bot', text: said, ai: true}, {misses: 0, aiCount: used + 1}) : null;
173
217
  }
174
218
 
@@ -251,6 +295,8 @@ export function visitorSays(id, text, chat) {
251
295
  if (full(session)) return {error: SAY.full, code: 409};
252
296
  const staffSide = ACTIVE.includes(session.data.status);
253
297
  const wrote = await addMessage(id, {from: 'visitor', text: clean}, staffSide ? {unread: int(session.data.unread) + 1} : {});
298
+ // The first thing the visitor says starts the chat (the summary is set from it).
299
+ if (!session.data.summary && wrote?.session) raiseStarted(wrote.session, clean, chat);
254
300
  if (!staffSide) {
255
301
  if (chat.bot) await botReply(id, clean, chat, readChatSettings());
256
302
  else await handoverNow(id, chat);
@@ -99,7 +99,7 @@ const _registeredSidebarItems = [];
99
99
  */
100
100
  const TOOL_GROUPS = new Map(Object.entries({
101
101
  Productivity: ['#/notes', '#/todo', '#/calculator', '#/plugins/calendar', '#/plugins/waypoint-pro', '#/plugins/sheets'],
102
- Communication: ['#/contacts', '#/plugins/contacts-pro', '#/plugins/mail-reader', '#/plugins/email-pro', '#/plugins/messages'],
102
+ Communication: ['#/ai-assist/chats', '#/ai-assist/settings', '#/contacts', '#/plugins/contacts-pro', '#/plugins/mail-reader', '#/plugins/email-pro', '#/plugins/messages'],
103
103
  Marketing: ['#/analytics', '#/seo', '#/plugins/analytics-pro/dashboard', '#/plugins/social', '#/plugins/feedback', '#/plugins/surveys', '#/plugins/campaigns-pro', '#/plugins/ecards'],
104
104
  Publishing: ['#/plugins/blog', '#/plugins/blog-pro', '#/plugins/docs', '#/plugins/theme-roller', '#/plugins/wiki', '#/plugins/wiki-pro', '#/plugins/scraper', '#/plugins/scraper-pro'],
105
105
  Business: ['#/plugins/shopping-cart', '#/plugins/booking', '#/plugins/booking-pro', '#/plugins/invoice', '#/job-board', '#/plugins/garage', '#/plugins/takeaway', '#/plugins/support', '#/plugins/onboard-pro'],
@@ -216,6 +216,17 @@ export const REGISTRY = [
216
216
  {key: 'manageGroups', label: 'Manage groups', description: 'Rename or delete any group, not only the ones they created - groups are shared, so this changes everyone\'s contacts'}
217
217
  ]
218
218
  },
219
+ {
220
+ // routes/api/contacts.js RESTRICTED; Contacts Pro reads it too. For outside accounts (a Job Board's).
221
+ key: 'contacts-restricted',
222
+ label: 'Contacts: own address book only',
223
+ description: 'A role with this uses Contacts for its own address book and nothing more: only the groups it made, no list of people, no sharing, no shared fields. It changes nothing for a person who also holds a role that gives Contacts without it, and nothing for the top (level-0) role.',
224
+ icon: 'lock',
225
+ group: 'Tools',
226
+ actions: [
227
+ {key: 'on', label: 'Restricted', description: 'Own contacts and own groups only'}
228
+ ]
229
+ },
219
230
  {
220
231
  // Instant calls (services/instantCalls.js). Only in use while a Pro Tool with calls
221
232
  // (Booking Pro, Contacts Pro, Calendar) is running; admins are granted it then, once.