domma-cms 1.80.0 → 1.81.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 (39) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/admin/css/site-settings.css +1 -1
  3. package/admin/js/lib/site-settings-arrange.js +3 -3
  4. package/admin/js/templates/docs/usage-site-settings.html +29 -3
  5. package/admin/js/templates/settings.html +94 -4
  6. package/admin/js/views/settings.js +3 -3
  7. package/docs/DommaFeatures.md +51 -2
  8. package/docs/plans/2026-11-19-brand-kit-design.md +1 -1
  9. package/docs/plugin-development.md +6 -0
  10. package/package.json +1 -1
  11. package/plugins/_lib/telegram/bot.js +120 -0
  12. package/plugins/free-tier.lock.json +26 -1
  13. package/plugins/telegram/CHANGELOG.md +5 -0
  14. package/plugins/telegram/CLAUDE.md +77 -0
  15. package/plugins/telegram/admin/css/index.css +68 -0
  16. package/plugins/telegram/admin/lib/arrange.js +103 -0
  17. package/plugins/telegram/admin/lib/kit.js +153 -0
  18. package/plugins/telegram/admin/templates/telegram.html +1 -0
  19. package/plugins/telegram/admin/views/chats.js +223 -0
  20. package/plugins/telegram/admin/views/connection.js +90 -0
  21. package/plugins/telegram/admin/views/telegram.js +89 -0
  22. package/plugins/telegram/admin/views/test.js +84 -0
  23. package/plugins/telegram/config.js +21 -0
  24. package/plugins/telegram/docs/guide.md +87 -0
  25. package/plugins/telegram/lib/messages.js +176 -0
  26. package/plugins/telegram/lib/queue.js +72 -0
  27. package/plugins/telegram/plugin.js +490 -0
  28. package/plugins/telegram/plugin.json +71 -0
  29. package/plugins/telegram/tests/api.test.js +381 -0
  30. package/plugins/telegram/tests/arrange.test.js +41 -0
  31. package/plugins/telegram/tests/messages.test.js +110 -0
  32. package/plugins/telegram/tests/queue.test.js +47 -0
  33. package/server/routes/api/brand-kit.js +55 -0
  34. package/server/routes/api/settings.js +17 -1
  35. package/server/server.js +2 -0
  36. package/server/services/brandKit.js +268 -0
  37. package/server/services/emailBrand.js +31 -13
  38. package/server/services/notify.js +20 -2
  39. package/server/services/plugins.js +3 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Telegram - what is sent, and to which chat. PURE: no I/O, so every rule here is tested
3
+ * (tests/messages.test.js).
4
+ *
5
+ * A linked chat (a person or a group, linked with "/link <code>") has its own routing:
6
+ *
7
+ * alerts {on, severities, sources} notifications the site raises (notification:raised)
8
+ * forms {on, all, slugs, detail} form submissions (form:submitted)
9
+ *
10
+ * What leaves the site is decided here and nowhere else:
11
+ * - an alert: its title, body, severity, the Tool that raised it and a link to the admin. A personal
12
+ * notification (one meant for named people, such as a to-do reminder) is never sent, and a chat gets only
13
+ * the alerts the person who set up its routing (its owner) may see in the bell.
14
+ * - a form submission: the form's title and a link to its submissions; with detail 'fields' (the
15
+ * default) also each field's label and value - never a password, file, image or hidden field. Only
16
+ * forms the chat's owner may read the submissions of.
17
+ *
18
+ * Messages are built from whole lines under Telegram's length limit, cut before escaping (bot.js escFit /
19
+ * fitLines): a cut through the HTML would make Telegram refuse the whole message.
20
+ *
21
+ * @module telegram/lib/messages
22
+ */
23
+ import {clip, esc, escFit, fitLines} from '../../_lib/telegram/bot.js';
24
+
25
+ export const SEVERITIES = ['info', 'success', 'warning', 'critical'];
26
+ export const DEFAULT_SEVERITIES = ['warning', 'critical'];
27
+ export const DETAILS = ['fields', 'title'];
28
+ export const DEFAULT_DETAIL = 'fields';
29
+
30
+ /** Never sent, whatever a chat's routing says: secrets, files, and what the visitor did not type. */
31
+ export const NEVER_SENT = new Set(['password', 'file', 'image', 'hidden', 'spacer', 'page-break', 'html', 'section', 'heading']);
32
+
33
+ const MAX_FIELDS = 40;
34
+ const MAX_VALUE = 600;
35
+ const MAX_SOURCES = 200;
36
+ const MAX_FORMS = 200;
37
+
38
+ const MARK = {info: 'ℹ️', success: '✅', warning: '⚠️', critical: '🚨'};
39
+
40
+ /** A new chat's routing: warning and critical alerts from everything, no forms yet. */
41
+ export function defaultRouting() {
42
+ return {
43
+ alerts: {on: true, severities: [...DEFAULT_SEVERITIES], sources: []},
44
+ forms: {on: false, all: false, slugs: [], detail: DEFAULT_DETAIL}
45
+ };
46
+ }
47
+
48
+ const strings = (list, max, test = () => true) => [...new Set((Array.isArray(list) ? list : [])
49
+ .map(s => String(s ?? '').trim()).filter(s => s && s.length <= 200 && test(s)))].slice(0, max);
50
+
51
+ /**
52
+ * A chat's routing as stored: whitelisted, defaulted, bounded. `patch` may hold any part; what it
53
+ * leaves out keeps `current`.
54
+ */
55
+ export function cleanRouting(patch = {}, current = defaultRouting()) {
56
+ const cur = {...defaultRouting(), ...current};
57
+ const a = {...cur.alerts, ...(patch.alerts && typeof patch.alerts === 'object' ? patch.alerts : {})};
58
+ const f = {...cur.forms, ...(patch.forms && typeof patch.forms === 'object' ? patch.forms : {})};
59
+ return {
60
+ alerts: {
61
+ on: a.on !== false,
62
+ severities: strings(a.severities, SEVERITIES.length, s => SEVERITIES.includes(s)),
63
+ sources: strings(a.sources, MAX_SOURCES, s => /^[a-z0-9_.-]+(:[a-z0-9_.:-]+)?$/i.test(s))
64
+ },
65
+ forms: {
66
+ on: f.on === true,
67
+ all: f.all === true,
68
+ slugs: strings(f.slugs, MAX_FORMS, s => /^[a-z0-9][a-z0-9_-]*$/i.test(s)),
69
+ detail: DETAILS.includes(f.detail) ? f.detail : DEFAULT_DETAIL
70
+ }
71
+ };
72
+ }
73
+
74
+ /** A chat's name as typed in the admin: one line, 80 characters. */
75
+ export const cleanName = (s, fallback = 'Chat') => (String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 80) || fallback);
76
+
77
+ /**
78
+ * Does a source id match a chat's chosen sources? Empty = every source. A chosen owner ('invoice')
79
+ * takes every source of that Tool ('invoice:overdue').
80
+ */
81
+ export function sourceMatches(chosen, source) {
82
+ if (!chosen?.length) return true;
83
+ const s = String(source || '');
84
+ return chosen.some(c => c === s || (!c.includes(':') && s.split(':')[0] === c));
85
+ }
86
+
87
+ /** A notification meant for named people (a to-do, a personal reminder) - never to a chat. */
88
+ export const isPersonal = (data) => Array.isArray(data?.audience?.userIds);
89
+
90
+ /**
91
+ * The chats an alert goes to. `mayHear(chat, data)` - may this chat's owner see this notification in the bell?
92
+ * (The plugin checks the owner's roles against the notification's audience.) Without it, nothing is sent.
93
+ */
94
+ export function chatsForAlert(chats, entry, {mayHear = () => false} = {}) {
95
+ const d = entry?.data;
96
+ if (!d?.title || isPersonal(d)) return [];
97
+ return (chats || []).filter(c => !c.paused && c.alerts?.on
98
+ && (c.alerts.severities || []).includes(d.severity) && sourceMatches(c.alerts.sources, d.source) && mayHear(c, d));
99
+ }
100
+
101
+ /** The chats a form submission goes to. `mayRead(chat)` - may this chat's owner read this form's submissions? */
102
+ export function chatsForForm(chats, slug, {mayRead = () => false} = {}) {
103
+ if (!slug) return [];
104
+ return (chats || []).filter(c => !c.paused && c.forms?.on && (c.forms.all || (c.forms.slugs || []).includes(slug)) && mayRead(c));
105
+ }
106
+
107
+ /** An admin link for a message: an admin route under the site's address, or a web address as it is. */
108
+ export function adminLink(link, base) {
109
+ const l = String(link || '').trim();
110
+ if (l.length > 500 || String(base || '').length > 200) return '';
111
+ if (/^https?:\/\/\S+$/i.test(l)) return l;
112
+ if (/^#\/\S*$/.test(l) && base) return `${base}/admin/${l}`;
113
+ return '';
114
+ }
115
+
116
+ /** One alert, as Telegram HTML, under Telegram's limit. */
117
+ export function alertText(entry, {base = '', site = ''} = {}) {
118
+ const d = entry?.data || {};
119
+ const link = adminLink(d.link, base);
120
+ const from = [d.sourceLabel || '', site].filter(Boolean).map(s => escFit(s, 120)).join(' · ');
121
+ return fitLines([
122
+ `${MARK[d.severity] || MARK.info} <b>${escFit(d.title, 400)}</b>`,
123
+ ...(d.body ? [escFit(d.body, 2500)] : []),
124
+ ...(from ? [`<i>${from}</i>`] : [])
125
+ ], {keep: link ? [`<a href="${esc(link)}">Open in the admin</a>`] : []});
126
+ }
127
+
128
+ /** A field's value as one line of text, or '' when there is nothing to show (or nothing that may be shown). */
129
+ export function fieldValue(v) {
130
+ if (v === null || v === undefined || v === '') return '';
131
+ if (typeof v === 'boolean') return v ? 'Yes' : 'No';
132
+ if (typeof v === 'number') return Number.isFinite(v) ? String(v) : '';
133
+ if (Array.isArray(v)) return v.map(fieldValue).filter(Boolean).join(', ');
134
+ // An object is a file ({url, name, …}) or something else no person typed - never sent.
135
+ if (typeof v === 'object') return '';
136
+ return String(v).trim();
137
+ }
138
+
139
+ /**
140
+ * The fields a submission may show, in the form's order: [{label, value}]. Only fields the form
141
+ * defines (a stray key in the posted data is not shown), never one of NEVER_SENT.
142
+ */
143
+ export function shownFields(form, data) {
144
+ const out = [];
145
+ for (const f of Array.isArray(form?.fields) ? form.fields : []) {
146
+ if (!f || typeof f.name !== 'string' || NEVER_SENT.has(String(f.type || '').toLowerCase())) continue;
147
+ if (/pass(word)?|secret|token/i.test(f.name)) continue;
148
+ const value = fieldValue(data?.[f.name]);
149
+ if (!value) continue;
150
+ out.push({label: clip(String(f.label || f.name), 120), value: clip(value, MAX_VALUE)});
151
+ if (out.length >= MAX_FIELDS) break;
152
+ }
153
+ return out;
154
+ }
155
+
156
+ /**
157
+ * One form submission, as Telegram HTML. `detail` 'title' sends the form's title and the link only. A long
158
+ * submission keeps its first answers whole and says the rest are in the admin.
159
+ */
160
+ export function formText(sub, form, {base = '', site = '', detail = DEFAULT_DETAIL} = {}) {
161
+ const title = sub?.formTitle || form?.title || sub?.slug || 'a form';
162
+ const link = base && sub?.slug ? `${base}/admin/#/forms/${encodeURIComponent(sub.slug)}/submissions` : '';
163
+ const fields = detail === 'title' ? [] : shownFields(form, sub?.data);
164
+ return fitLines([
165
+ `📝 <b>New ${escFit(title, 200)} entry</b>${sub?.ended ? ' <i>(ended early by one of its rules)</i>' : ''}`,
166
+ ...(site ? [`<i>${escFit(site, 120)}</i>`] : []),
167
+ ...(fields.length ? ['', ...fields.map(f => `<b>${esc(f.label)}:</b> ${esc(f.value)}`)] : [])
168
+ ], {keep: link ? ['', `<a href="${esc(link)}">Open the submissions</a>`] : [], more: '<i>… more answers in the admin</i>'});
169
+ }
170
+
171
+ /** A chat for the admin: never its Telegram id's history, just what the screens show. */
172
+ export function chatForAdmin(c) {
173
+ const r = cleanRouting(c);
174
+ return {id: c.id, name: c.name, type: c.type || 'private', linkedAt: c.linkedAt || null, paused: Boolean(c.paused),
175
+ lastError: c.lastError || '', lastSentAt: c.lastSentAt || null, ownerName: c.ownerName || '', ...r};
176
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Telegram - one queue per chat, so a burst (a form flood, a run of alerts) reaches Telegram at about one
3
+ * message a second per chat, as Telegram asks, instead of being refused. In memory: a restart drops what
4
+ * is waiting, which is the right side to fail on for alerts that are also in the admin's bell.
5
+ *
6
+ * A send never throws at the caller: each queued message resolves to Telegram's answer, or
7
+ * {ok: false, description} when the queue is full or the chat could not be reached. A 429 is waited out
8
+ * once (Telegram says how long, `parameters.retry_after`).
9
+ *
10
+ * @module telegram/lib/queue
11
+ */
12
+
13
+ /**
14
+ * @param {object} o
15
+ * @param {(chatId: string, text: string, extra: object, ctx: any) => Promise<object>} o.send - `ctx` is what push was given (the bot token it was queued under)
16
+ * @param {number} [o.gapMs=1000] - the least time between two messages to one chat
17
+ * @param {number} [o.max=50] - messages waiting per chat before new ones are refused
18
+ * @param {(ms: number) => Promise<void>} [o.sleep]
19
+ * @param {() => number} [o.now]
20
+ * @param {(chatId: string, result: object) => void} [o.onResult] - every answer, for the chat's last error
21
+ */
22
+ export function createQueue({send, gapMs = 1000, max = 50, sleep = (ms) => new Promise(r => setTimeout(r, ms).unref?.()), now = () => Date.now(), onResult = () => {}}) {
23
+ const lanes = new Map(); // chatId -> {chain, waiting, last}
24
+
25
+ const lane = (chatId) => {
26
+ let l = lanes.get(chatId);
27
+ if (!l) {
28
+ // Customer chats (Telegram Pro) each make a lane: forget idle ones past their gap, so the map stays small.
29
+ if (lanes.size >= 500) for (const [k, v] of lanes) if (!v.waiting && now() - v.last > gapMs) lanes.delete(k);
30
+ l = {chain: Promise.resolve(), waiting: 0, last: -Infinity};
31
+ lanes.set(chatId, l);
32
+ }
33
+ return l;
34
+ };
35
+
36
+ async function deliver(l, chatId, text, extra, ctx) {
37
+ const wait = l.last + gapMs - now();
38
+ if (wait > 0) await sleep(wait);
39
+ let r;
40
+ try { r = await send(chatId, text, extra, ctx); } catch (err) { r = {ok: false, description: err?.message || String(err)}; }
41
+ if (!r?.ok && r?.error_code === 429) {
42
+ const after = Math.min(Number(r.parameters?.retry_after) || 1, 60);
43
+ await sleep(after * 1000);
44
+ try { r = await send(chatId, text, extra, ctx); } catch (err) { r = {ok: false, description: err?.message || String(err)}; }
45
+ }
46
+ l.last = now();
47
+ r = r || {ok: false, description: 'No answer.'};
48
+ try { onResult(chatId, r); } catch { /* a report, not part of the send */ }
49
+ return r;
50
+ }
51
+
52
+ return {
53
+ /** Queue one message for a chat. Resolves to Telegram's answer; never rejects. */
54
+ push(chatId, text, extra = {}, ctx = undefined) {
55
+ const id = String(chatId);
56
+ const l = lane(id);
57
+ if (l.waiting >= max) return Promise.resolve({ok: false, description: 'Too many messages waiting for this chat - this one was dropped.'});
58
+ l.waiting++;
59
+ // A lane is kept once made (one per linked chat - a handful): its `last` spaces the next burst too.
60
+ const p = l.chain.then(() => deliver(l, id, text, extra, ctx)).finally(() => { l.waiting--; });
61
+ l.chain = p.catch(() => {});
62
+ return p;
63
+ },
64
+ /** How many are waiting, for one chat or all. */
65
+ waiting(chatId) {
66
+ if (chatId !== undefined) return lanes.get(String(chatId))?.waiting || 0;
67
+ let n = 0;
68
+ for (const l of lanes.values()) n += l.waiting;
69
+ return n;
70
+ }
71
+ };
72
+ }