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.
- package/CHANGELOG.md +13 -0
- package/admin/css/site-settings.css +1 -1
- package/admin/js/lib/site-settings-arrange.js +3 -3
- package/admin/js/templates/docs/usage-site-settings.html +29 -3
- package/admin/js/templates/settings.html +94 -4
- package/admin/js/views/settings.js +3 -3
- package/docs/DommaFeatures.md +51 -2
- package/docs/plans/2026-11-19-brand-kit-design.md +1 -1
- package/docs/plugin-development.md +6 -0
- package/package.json +1 -1
- package/plugins/_lib/telegram/bot.js +120 -0
- package/plugins/free-tier.lock.json +26 -1
- package/plugins/telegram/CHANGELOG.md +5 -0
- package/plugins/telegram/CLAUDE.md +77 -0
- package/plugins/telegram/admin/css/index.css +68 -0
- package/plugins/telegram/admin/lib/arrange.js +103 -0
- package/plugins/telegram/admin/lib/kit.js +153 -0
- package/plugins/telegram/admin/templates/telegram.html +1 -0
- package/plugins/telegram/admin/views/chats.js +223 -0
- package/plugins/telegram/admin/views/connection.js +90 -0
- package/plugins/telegram/admin/views/telegram.js +89 -0
- package/plugins/telegram/admin/views/test.js +84 -0
- package/plugins/telegram/config.js +21 -0
- package/plugins/telegram/docs/guide.md +87 -0
- package/plugins/telegram/lib/messages.js +176 -0
- package/plugins/telegram/lib/queue.js +72 -0
- package/plugins/telegram/plugin.js +490 -0
- package/plugins/telegram/plugin.json +71 -0
- package/plugins/telegram/tests/api.test.js +381 -0
- package/plugins/telegram/tests/arrange.test.js +41 -0
- package/plugins/telegram/tests/messages.test.js +110 -0
- package/plugins/telegram/tests/queue.test.js +47 -0
- package/server/routes/api/brand-kit.js +55 -0
- package/server/routes/api/settings.js +17 -1
- package/server/server.js +2 -0
- package/server/services/brandKit.js +268 -0
- package/server/services/emailBrand.js +31 -13
- package/server/services/notify.js +20 -2
- package/server/services/plugins.js +3 -0
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram (free) - the site's own Telegram bot sends the team its alerts and form submissions.
|
|
3
|
+
*
|
|
4
|
+
* Connect a bot made with @BotFather (its token stays on this server, never sent back to a browser), link any
|
|
5
|
+
* number of chats - a person or a group - with a one-time "/link <code>", and give each chat its routing:
|
|
6
|
+
* which notifications (severities, Tools) and which forms it gets. Listens to the core's
|
|
7
|
+
* `notification:raised` (CMS 1.72+) and `form:submitted` events; every message goes through a per-chat queue
|
|
8
|
+
* (about one a second) and a failure never reaches the notification or the form.
|
|
9
|
+
*
|
|
10
|
+
* Telegram Pro (paid) adds two-way customer chat through the registry
|
|
11
|
+
* `globalThis[Symbol.for('domma.telegram')]`: every message this Tool does not answer itself is offered to the
|
|
12
|
+
* handlers registered there (`register(name, {onMessage})`).
|
|
13
|
+
*
|
|
14
|
+
* API (/api/plugins/telegram; permission `telegram`: read / manage):
|
|
15
|
+
* GET /status · GET /count
|
|
16
|
+
* POST /connect · DELETE /connection · POST /link-code · PUT|DELETE /chats/:id · POST /test
|
|
17
|
+
* Telegram (no sign-in; the webhook secret header):
|
|
18
|
+
* POST /webhook
|
|
19
|
+
*
|
|
20
|
+
* @module telegram/plugin
|
|
21
|
+
*/
|
|
22
|
+
import {randomBytes, randomUUID} from 'crypto';
|
|
23
|
+
import {getPluginStates, savePluginState} from '../../server/services/plugins.js';
|
|
24
|
+
import {getConfig} from '../../server/config.js';
|
|
25
|
+
import {getForm as coreGetForm, listForms as coreListForms} from '../../server/services/forms.js';
|
|
26
|
+
import {inAudience, listNotificationSources} from '../../server/services/notify.js';
|
|
27
|
+
import {getUserById} from '../../server/services/users.js';
|
|
28
|
+
import {getPermissionsFor} from '../../server/services/roles.js';
|
|
29
|
+
import {getEffectiveRoles} from '../../server/services/userRoles.js';
|
|
30
|
+
import {canSeeArtefact} from '../../server/services/projects.js';
|
|
31
|
+
import {call, chatName, esc, parseCommand, randomCode, sameSecret, sendMessage, tokenShape} from '../_lib/telegram/bot.js';
|
|
32
|
+
import {createQueue} from './lib/queue.js';
|
|
33
|
+
import {alertText, chatForAdmin, chatsForAlert, chatsForForm, cleanName, cleanRouting, defaultRouting, formText, SEVERITIES} from './lib/messages.js';
|
|
34
|
+
import defaults from './config.js';
|
|
35
|
+
|
|
36
|
+
export const NAME = 'telegram';
|
|
37
|
+
export const KEY = Symbol.for('domma.telegram');
|
|
38
|
+
const WEBHOOK_PATH = '/api/plugins/telegram/webhook';
|
|
39
|
+
const LINK_CODE_FOR = 15 * 60_000;
|
|
40
|
+
const LINK_CODE_TRIES = 5; // wrong codes from one chat before it is ignored
|
|
41
|
+
const LINK_CODE_TRIES_ALL = 50; // wrong codes from everyone before the code is burnt
|
|
42
|
+
const SEEN_UPDATES = 500;
|
|
43
|
+
const MAX_CHATS = 25;
|
|
44
|
+
const INFO_FOR = 5 * 60_000;
|
|
45
|
+
|
|
46
|
+
// The core's event bus has no "off": listen once per process, and send through whichever instance is live.
|
|
47
|
+
let live = null;
|
|
48
|
+
let listening = false;
|
|
49
|
+
|
|
50
|
+
/** The registry Telegram Pro (and any later Tool) joins. Made once; its services follow the live instance. */
|
|
51
|
+
function registry() {
|
|
52
|
+
if (!globalThis[KEY]) {
|
|
53
|
+
const handlers = new Map();
|
|
54
|
+
globalThis[KEY] = {
|
|
55
|
+
version: 1,
|
|
56
|
+
handlers,
|
|
57
|
+
services: {},
|
|
58
|
+
register(name, handler) { if (name && typeof handler?.onMessage === 'function') handlers.set(String(name), handler); },
|
|
59
|
+
unregister(name) { handlers.delete(String(name)); }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return globalThis[KEY];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export default async function telegram(fastify, options) {
|
|
66
|
+
const {authenticate, requirePermission} = options.auth;
|
|
67
|
+
const hooks = options.hooks || {};
|
|
68
|
+
const log = fastify.log;
|
|
69
|
+
const can = (action) => ({preHandler: [authenticate, requirePermission(NAME, action)]});
|
|
70
|
+
const allowedTo = async (request, action) => {
|
|
71
|
+
let denied = false;
|
|
72
|
+
await requirePermission(NAME, action)(request, {code: () => ({send: () => { denied = true; }})});
|
|
73
|
+
return !denied;
|
|
74
|
+
};
|
|
75
|
+
const fail = (reply, status, error) => reply.code(status).send({error});
|
|
76
|
+
const getForm = options.getForm || coreGetForm;
|
|
77
|
+
const listForms = options.listForms || coreListForms;
|
|
78
|
+
const listSources = options.listSources || listNotificationSources;
|
|
79
|
+
const getUser = options.getUser || getUserById;
|
|
80
|
+
/** May this user read form submissions (the core's Forms permission) - and this form's, by its project? */
|
|
81
|
+
const canReadForms = options.canReadForms || ((user) => getEffectiveRoles(user || {}).some(r => getPermissionsFor('collections', 'read').includes(r)));
|
|
82
|
+
const canSeeForm = options.canSeeForm || ((user, f) => canSeeArtefact(user, f));
|
|
83
|
+
|
|
84
|
+
// ---- Settings: written only by this Tool's routes --------------------------------------------
|
|
85
|
+
|
|
86
|
+
const stored = () => getPluginStates()[NAME]?.settings || {};
|
|
87
|
+
const st = () => ({...defaults, ...stored(), chats: Array.isArray(stored().chats) ? stored().chats : []});
|
|
88
|
+
const save = (patch) => { savePluginState(NAME, {settings: {...stored(), ...patch}}); return st(); };
|
|
89
|
+
const ready = () => Boolean(st().botToken && st().secret);
|
|
90
|
+
const siteName = () => { try { return String(getConfig('site')?.title || ''); } catch { return ''; } };
|
|
91
|
+
const saveChat = (id, patch) => save({chats: st().chats.map(c => (c.id === id ? {...c, ...patch} : c))});
|
|
92
|
+
|
|
93
|
+
// ---- Owners: a chat gets only what the person who set it up may see ---------------------------------
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A chat's owner is whoever made its link code, then whoever last changed its routing. An alert goes to a
|
|
97
|
+
* chat only if its owner may see that notification in the bell (its audience); a form only if its owner may
|
|
98
|
+
* read that form's submissions. Read fresh (60 s), so a demoted or deleted owner stops the chat getting more.
|
|
99
|
+
*/
|
|
100
|
+
const owners = new Map(); // user id -> {at, user}
|
|
101
|
+
async function ownerOf(chat) {
|
|
102
|
+
if (!chat?.ownerId) return null;
|
|
103
|
+
const hit = owners.get(chat.ownerId);
|
|
104
|
+
if (hit && Date.now() - hit.at < 60_000) return hit.user;
|
|
105
|
+
let user = null;
|
|
106
|
+
try { user = await getUser(chat.ownerId); } catch { /* gone */ }
|
|
107
|
+
const usable = user && user.isActive !== false ? user : null;
|
|
108
|
+
owners.set(chat.ownerId, {at: Date.now(), user: usable});
|
|
109
|
+
return usable;
|
|
110
|
+
}
|
|
111
|
+
async function ownersOf(chats) {
|
|
112
|
+
const m = new Map();
|
|
113
|
+
for (const c of chats) m.set(c.id, await ownerOf(c));
|
|
114
|
+
return m;
|
|
115
|
+
}
|
|
116
|
+
/** The owner fields for a signed-in user, or null for one who cannot own a chat (the Manager's staff session has no user record). */
|
|
117
|
+
const ownerFields = (user) => {
|
|
118
|
+
const id = String(user?.id || user?.sub || '');
|
|
119
|
+
if (!id || user?.dcmStaff) return null;
|
|
120
|
+
return {ownerId: id, ownerName: String(user?.name || user?.email || '').slice(0, 80)};
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
// ---- Sending ----------------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
const lastSaved = new Map(); // chat id -> when lastSentAt was last written (a flood writes it once a minute)
|
|
126
|
+
const queue = createQueue({
|
|
127
|
+
gapMs: options.queueGapMs ?? 1000,
|
|
128
|
+
sleep: options.sleep,
|
|
129
|
+
send: (chatId, text, extra, token) => sendMessage(token, chatId, text, extra),
|
|
130
|
+
onResult(chatId, r) {
|
|
131
|
+
const c = st().chats.find(x => x.chatId === chatId);
|
|
132
|
+
if (!c) return;
|
|
133
|
+
const error = r.ok ? '' : String(r.description || 'Not sent.').slice(0, 300);
|
|
134
|
+
const at = Date.now();
|
|
135
|
+
if (error !== (c.lastError || '') || at - (lastSaved.get(c.id) || 0) > 60_000) {
|
|
136
|
+
lastSaved.set(c.id, at);
|
|
137
|
+
saveChat(c.id, {lastError: error, ...(r.ok ? {lastSentAt: new Date(at).toISOString()} : {})});
|
|
138
|
+
}
|
|
139
|
+
if (!r.ok) log.warn(`[telegram] Not sent to "${c.name}": ${error}`);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
// Queued under the token of the moment: a message queued before the bot was changed is not sent by the new one.
|
|
143
|
+
const send = (chatId, text, extra) => (ready() ? queue.push(String(chatId), text, extra, st().botToken) : Promise.resolve({ok: false, description: 'Telegram is not connected.'}));
|
|
144
|
+
|
|
145
|
+
async function alert(entry) {
|
|
146
|
+
if (!ready()) return;
|
|
147
|
+
const s = st();
|
|
148
|
+
const who = await ownersOf(s.chats);
|
|
149
|
+
const to = chatsForAlert(s.chats, entry, {mayHear: (c, d) => Boolean(who.get(c.id)) && inAudience(d.audience, who.get(c.id))});
|
|
150
|
+
if (!to.length) return;
|
|
151
|
+
const text = alertText(entry, {base: s.base, site: siteName()});
|
|
152
|
+
await Promise.all(to.map(c => send(c.chatId, text)));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function form(sub) {
|
|
156
|
+
if (!ready() || !sub?.slug) return;
|
|
157
|
+
const s = st();
|
|
158
|
+
let def = null;
|
|
159
|
+
try { def = await getForm(sub.slug); } catch { /* deleted since: title and link only */ }
|
|
160
|
+
const who = await ownersOf(s.chats);
|
|
161
|
+
const to = chatsForForm(s.chats, sub.slug, {mayRead: (c) => {
|
|
162
|
+
const u = who.get(c.id);
|
|
163
|
+
return Boolean(u) && canReadForms(u) && (!def || canSeeForm(u, def));
|
|
164
|
+
}});
|
|
165
|
+
if (!to.length) return;
|
|
166
|
+
await Promise.all(to.map(c => send(c.chatId, formText(sub, def, {base: s.base, site: siteName(), detail: def ? c.forms.detail : 'title'}))));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
live = {alert, form};
|
|
170
|
+
fastify.addHook('onClose', async () => { if (live?.alert === alert) live = null; });
|
|
171
|
+
if (!listening && typeof hooks.on === 'function') {
|
|
172
|
+
listening = true;
|
|
173
|
+
hooks.on('notification:raised', (entry) => live?.alert(entry).catch(err => log.warn?.(`[telegram] alert: ${err.message}`)));
|
|
174
|
+
hooks.on('form:submitted', (sub) => live?.form(sub).catch(err => log.warn?.(`[telegram] form: ${err.message}`)));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
hooks.registerNotificationSource?.({id: 'test', label: 'Telegram test alerts', severity: 'warning',
|
|
179
|
+
description: 'Raised by Telegram > Test > "Raise a test notification", to try the whole path from the bell to the chat.'});
|
|
180
|
+
} catch { /* an older CMS */ }
|
|
181
|
+
|
|
182
|
+
// ---- The registry (Telegram Pro) -----------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
const reg = registry();
|
|
185
|
+
reg.services = {
|
|
186
|
+
ready: () => ready(),
|
|
187
|
+
botName: () => st().botName || '',
|
|
188
|
+
base: () => st().base || '',
|
|
189
|
+
siteName,
|
|
190
|
+
/** Linked chats: {id, chatId, name, type}. */
|
|
191
|
+
chats: () => st().chats.map(c => ({id: c.id, chatId: c.chatId, name: c.name, type: c.type})),
|
|
192
|
+
/** Queue one message (Telegram HTML; escape with `esc`). Resolves to Telegram's answer, never rejects. */
|
|
193
|
+
send: (chatId, text, extra) => send(chatId, text, extra),
|
|
194
|
+
esc
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
// ---- Admin ---------------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
let info = {at: 0, token: '', value: null};
|
|
200
|
+
async function webhookInfo({fresh = false} = {}) {
|
|
201
|
+
const s = st();
|
|
202
|
+
if (!s.botToken) return null;
|
|
203
|
+
if (!fresh && info.token === s.botToken && Date.now() - info.at < INFO_FOR) return info.value;
|
|
204
|
+
const r = await call(s.botToken, 'getWebhookInfo');
|
|
205
|
+
const want = s.base ? `${s.base}${WEBHOOK_PATH}` : '';
|
|
206
|
+
const value = r.ok
|
|
207
|
+
? {ours: Boolean(want) && r.result?.url === want, url: r.result?.url || '', pending: r.result?.pending_update_count || 0,
|
|
208
|
+
lastError: r.result?.last_error_message || '', lastErrorAt: r.result?.last_error_date ? new Date(r.result.last_error_date * 1000).toISOString() : null}
|
|
209
|
+
: {error: r.description || 'Telegram did not answer.'};
|
|
210
|
+
info = {at: Date.now(), token: s.botToken, value};
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const liveCode = (s) => (s.linkSecret && Date.parse(s.linkSecretUntil) > Date.now() ? s.linkSecret : '');
|
|
215
|
+
|
|
216
|
+
async function status(request, {fresh = true} = {}) {
|
|
217
|
+
const s = st();
|
|
218
|
+
const manage = await allowedTo(request, 'manage');
|
|
219
|
+
let forms = [];
|
|
220
|
+
// Only forms this person may read the submissions of: they are the ones a chat they set up can get.
|
|
221
|
+
try {
|
|
222
|
+
forms = canReadForms(request.user)
|
|
223
|
+
? (await listForms()).filter(f => canSeeForm(request.user, f)).map(f => ({slug: f.slug, title: String(f.title || f.slug)})).sort((a, b) => a.title.localeCompare(b.title))
|
|
224
|
+
: [];
|
|
225
|
+
} catch { /* none */ }
|
|
226
|
+
let sources = [];
|
|
227
|
+
try { sources = listSources().map(x => ({id: x.id, label: x.label, ownerLabel: x.ownerLabel, owner: x.owner})); } catch { /* an older CMS */ }
|
|
228
|
+
const code = manage ? liveCode(s) : '';
|
|
229
|
+
return {
|
|
230
|
+
connected: ready(), botName: s.botName || '', base: s.base || '',
|
|
231
|
+
webhook: ready() ? await webhookInfo({fresh}) : null,
|
|
232
|
+
chats: s.chats.map(chatForAdmin),
|
|
233
|
+
linkCode: code, linkCodeUntil: code ? s.linkSecretUntil : null,
|
|
234
|
+
can: {manage}, forms, sources, severities: SEVERITIES, defaults: defaultRouting(),
|
|
235
|
+
waiting: queue.waiting(), pro: reg.handlers.size > 0, site: siteName()
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
fastify.get('/status', can('read'), async (request) => status(request));
|
|
240
|
+
|
|
241
|
+
/** The badge: linked chats as a calm total; red only when Telegram reports it cannot reach the site. */
|
|
242
|
+
fastify.get('/count', can('read'), async () => {
|
|
243
|
+
const s = st();
|
|
244
|
+
if (!ready()) return {count: 0, label: 'Not connected', tone: 'info', inventory: true};
|
|
245
|
+
const w = await webhookInfo();
|
|
246
|
+
const recent = w?.lastErrorAt && Date.now() - Date.parse(w.lastErrorAt) < 3600_000;
|
|
247
|
+
const broken = w && (w.error || !w.ours || recent);
|
|
248
|
+
const n = s.chats.length;
|
|
249
|
+
const sent = s.chats.filter(c => c.lastError);
|
|
250
|
+
if (broken || sent.length) {
|
|
251
|
+
const why = w?.error ? `Telegram: ${w.error}` : !w?.ours ? 'The bot\'s webhook points somewhere else - connect it again.'
|
|
252
|
+
: recent ? `Telegram cannot reach this site: ${w.lastError}` : `${sent.length} chat${sent.length === 1 ? '' : 's'} could not be sent to`;
|
|
253
|
+
return {count: 1, label: why, tone: 'danger',
|
|
254
|
+
details: {title: 'Telegram', rows: [{label: 'Linked chats', value: String(n)}], items: [{text: why}, ...sent.slice(0, 4).map(c => ({text: `${c.name}: ${c.lastError}`}))]}};
|
|
255
|
+
}
|
|
256
|
+
return {count: n, label: `${n} linked chat${n === 1 ? '' : 's'} on @${s.botName}`, tone: 'info', inventory: true};
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
/** Connect a bot: check the token, refuse a bot already used elsewhere, point its webhook here (https only). */
|
|
260
|
+
fastify.post('/connect', can('manage'), async (request, reply) => {
|
|
261
|
+
const token = String(request.body?.token || '').trim();
|
|
262
|
+
const base = String(request.body?.base || '').trim().replace(/\/+$/, '');
|
|
263
|
+
if (!tokenShape(token)) return fail(reply, 400, 'That does not look like a bot token - it is the long line @BotFather gave you, like 123456789:AAE….');
|
|
264
|
+
if (!/^https:\/\/[^/\s?#]+$/i.test(base)) return fail(reply, 400, 'Telegram can only reach a site on https.');
|
|
265
|
+
const me = await call(token, 'getMe');
|
|
266
|
+
if (!me.ok) return fail(reply, 400, `Telegram did not accept that token: ${me.description || 'unknown error'}.`);
|
|
267
|
+
const url = `${base}${WEBHOOK_PATH}`;
|
|
268
|
+
const hook = await call(token, 'getWebhookInfo');
|
|
269
|
+
if (!hook.ok) return fail(reply, 502, `Telegram did not answer: ${hook.description || 'unknown error'}.`);
|
|
270
|
+
const now = hook.result?.url || '';
|
|
271
|
+
if (now && now !== url) {
|
|
272
|
+
let where = 'another address';
|
|
273
|
+
try {
|
|
274
|
+
const u = new URL(now);
|
|
275
|
+
const takeaway = u.pathname.startsWith('/api/plugins/takeaway/');
|
|
276
|
+
where = takeaway ? `Takeaway on ${u.host}` : u.host;
|
|
277
|
+
} catch { /* not a URL */ }
|
|
278
|
+
return fail(reply, 409, `This bot is already used by ${where}. Make a second bot with @BotFather for this Tool - one bot can only send its messages to one place.`);
|
|
279
|
+
}
|
|
280
|
+
const secret = randomBytes(24).toString('hex');
|
|
281
|
+
const set = await call(token, 'setWebhook', {url, secret_token: secret, allowed_updates: ['message'], drop_pending_updates: true});
|
|
282
|
+
if (!set.ok) return fail(reply, 502, `Telegram would not set the webhook: ${set.description || 'unknown error'}.`);
|
|
283
|
+
const before = st();
|
|
284
|
+
const same = before.botToken === token;
|
|
285
|
+
seen.clear(); // update ids are per bot
|
|
286
|
+
// The bot this replaces stops sending here.
|
|
287
|
+
if (before.botToken && !same) await call(before.botToken, 'deleteWebhook', {drop_pending_updates: true});
|
|
288
|
+
save({botToken: token, botName: String(me.result?.username || ''), secret, base, linkSecret: '', linkSecretUntil: '', ...(same ? {} : {chats: []})});
|
|
289
|
+
info = {at: 0, token: '', value: null};
|
|
290
|
+
return status(request);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
fastify.delete('/connection', can('manage'), async (request) => {
|
|
294
|
+
const s = st();
|
|
295
|
+
if (s.botToken) await call(s.botToken, 'deleteWebhook', {drop_pending_updates: true});
|
|
296
|
+
save({botToken: '', botName: '', secret: '', linkSecret: '', linkSecretUntil: '', chats: []});
|
|
297
|
+
info = {at: 0, token: '', value: null};
|
|
298
|
+
return status(request);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* A one-time code for "/link <code>": 16 random characters, 15 minutes, one chat, burnt after a few wrong
|
|
303
|
+
* guesses - whoever links a chat receives what is routed to it.
|
|
304
|
+
*/
|
|
305
|
+
const linkTries = new Map(); // chat id -> wrong codes
|
|
306
|
+
let linkTriesAll = 0;
|
|
307
|
+
fastify.post('/link-code', can('manage'), async (request, reply) => {
|
|
308
|
+
if (!ready()) return fail(reply, 409, 'Connect a bot first.');
|
|
309
|
+
if (st().chats.length >= MAX_CHATS) return fail(reply, 409, `${MAX_CHATS} chats are linked - unlink one first.`);
|
|
310
|
+
linkTries.clear();
|
|
311
|
+
linkTriesAll = 0;
|
|
312
|
+
// Who made the code becomes the new chat's owner - kept with the code, so a restart in between keeps it.
|
|
313
|
+
const by = ownerFields(request.user) || {ownerId: '', ownerName: ''};
|
|
314
|
+
save({linkSecret: randomCode(16), linkSecretUntil: new Date(Date.now() + LINK_CODE_FOR).toISOString(), linkOwnerId: by.ownerId, linkOwnerName: by.ownerName});
|
|
315
|
+
return status(request, {fresh: false});
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
fastify.put('/chats/:id', can('manage'), async (request, reply) => {
|
|
319
|
+
const c = st().chats.find(x => x.id === request.params.id);
|
|
320
|
+
if (!c) return fail(reply, 404, 'That chat is not linked any more.');
|
|
321
|
+
const b = request.body || {};
|
|
322
|
+
const patch = {...cleanRouting(b, c)};
|
|
323
|
+
// Forms chosen here must be ones this person may read. Only the forms sent are checked: a save that
|
|
324
|
+
// changes only the alerts leaves the forms someone else chose as they were.
|
|
325
|
+
if (b.forms !== undefined && patch.forms.on) {
|
|
326
|
+
if (!canReadForms(request.user)) return fail(reply, 403, 'Sending form submissions needs permission to read them.');
|
|
327
|
+
if (!patch.forms.all) {
|
|
328
|
+
let all = [];
|
|
329
|
+
try { all = await listForms(); } catch { /* none */ }
|
|
330
|
+
const readable = new Set(all.filter(f => canSeeForm(request.user, f)).map(f => f.slug));
|
|
331
|
+
patch.forms.slugs = patch.forms.slugs.filter(s => readable.has(s));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
// Whoever changes a chat's routing becomes its owner: it then gets only what they may see.
|
|
335
|
+
if (b.alerts !== undefined || b.forms !== undefined) {
|
|
336
|
+
const by = ownerFields(request.user);
|
|
337
|
+
if (by) { Object.assign(patch, by); owners.delete(by.ownerId); }
|
|
338
|
+
}
|
|
339
|
+
if (b.name !== undefined) patch.name = cleanName(b.name, c.name);
|
|
340
|
+
if (b.paused !== undefined) patch.paused = Boolean(b.paused);
|
|
341
|
+
saveChat(c.id, patch);
|
|
342
|
+
return status(request, {fresh: false});
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
fastify.delete('/chats/:id', can('manage'), async (request, reply) => {
|
|
346
|
+
const c = st().chats.find(x => x.id === request.params.id);
|
|
347
|
+
if (!c) return fail(reply, 404, 'That chat is not linked any more.');
|
|
348
|
+
save({chats: st().chats.filter(x => x.id !== c.id)});
|
|
349
|
+
send(c.chatId, `This chat is no longer linked to ${esc(siteName() || 'the site')}. Nothing more will arrive here.`);
|
|
350
|
+
return status(request, {fresh: false});
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
/** Try a chat: a hello, a sample alert, a sample form entry, or a real notification through the bell. */
|
|
354
|
+
fastify.post('/test', can('manage'), async (request, reply) => {
|
|
355
|
+
if (!ready()) return fail(reply, 409, 'Connect a bot first.');
|
|
356
|
+
const kind = String(request.body?.kind || 'hello');
|
|
357
|
+
if (kind === 'notification') {
|
|
358
|
+
if (typeof hooks.notify !== 'function') return fail(reply, 501, 'This CMS cannot raise notifications for Tools.');
|
|
359
|
+
const severity = SEVERITIES.includes(request.body?.severity) ? request.body.severity : 'warning';
|
|
360
|
+
await hooks.notify({source: 'test', title: 'A test notification from Telegram', severity,
|
|
361
|
+
body: 'Raised from Telegram > Test. Every chat whose routing takes this severity should get it.', link: '#/plugins/telegram/test'});
|
|
362
|
+
return {sent: true, note: 'Raised. Chats whose routing takes it get it within a few seconds.'};
|
|
363
|
+
}
|
|
364
|
+
const c = st().chats.find(x => x.id === request.body?.chat);
|
|
365
|
+
if (!c) return fail(reply, 404, 'Choose a linked chat.');
|
|
366
|
+
const s = st();
|
|
367
|
+
let text;
|
|
368
|
+
if (kind === 'alert') {
|
|
369
|
+
text = alertText({data: {title: 'A sample alert', body: 'This is how a notification arrives here.', severity: 'warning', sourceLabel: 'Telegram', link: '#/plugins/telegram'}}, {base: s.base, site: siteName()});
|
|
370
|
+
} else if (kind === 'form') {
|
|
371
|
+
const slug = String(request.body?.form || '');
|
|
372
|
+
let def = null;
|
|
373
|
+
try { def = slug ? await getForm(slug) : null; } catch { /* gone */ }
|
|
374
|
+
if (!def) return fail(reply, 404, 'Choose a form.');
|
|
375
|
+
const sample = Object.fromEntries((def.fields || []).filter(f => f?.name).map(f => [f.name, `(${f.label || f.name})`]));
|
|
376
|
+
text = formText({slug, formTitle: def.title, data: sample}, def, {base: s.base, site: siteName(), detail: c.forms?.detail});
|
|
377
|
+
} else {
|
|
378
|
+
text = `👋 A test from ${esc(siteName() || 'your site')} - this chat is linked as <b>${esc(c.name)}</b>.`;
|
|
379
|
+
}
|
|
380
|
+
const r = await send(c.chatId, text);
|
|
381
|
+
if (!r.ok) return fail(reply, 502, `Not sent: ${r.description || 'unknown error'}`);
|
|
382
|
+
return {sent: true};
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// ---- Telegram's updates ----------------------------------------------------------------------
|
|
386
|
+
|
|
387
|
+
const say = (chatId, text) => send(chatId, text);
|
|
388
|
+
|
|
389
|
+
async function link(msg, arg) {
|
|
390
|
+
const chat = msg.chat;
|
|
391
|
+
const s = st();
|
|
392
|
+
const code = liveCode(s);
|
|
393
|
+
const from = String(chat.id);
|
|
394
|
+
const tries = linkTries.get(from) || 0;
|
|
395
|
+
if (!code || tries >= LINK_CODE_TRIES || !sameSecret(arg, code)) {
|
|
396
|
+
// A chat gets a few typos, then is ignored until a new code is made; a guessing run from many chats
|
|
397
|
+
// burns the code. (16 random characters cannot be guessed; this only stops the noise.)
|
|
398
|
+
if (code && tries < LINK_CODE_TRIES) {
|
|
399
|
+
linkTries.set(from, tries + 1);
|
|
400
|
+
if (++linkTriesAll >= LINK_CODE_TRIES_ALL) save({linkSecret: '', linkSecretUntil: ''});
|
|
401
|
+
}
|
|
402
|
+
await say(chat.id, 'That code is not right or has run out - make a new one in Telegram › Chats.');
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
linkTries.clear();
|
|
406
|
+
linkTriesAll = 0;
|
|
407
|
+
const chatId = String(chat.id);
|
|
408
|
+
const had = s.chats.find(c => c.chatId === chatId);
|
|
409
|
+
if (had) {
|
|
410
|
+
save({linkSecret: '', linkSecretUntil: '', chats: s.chats.map(c => (c.chatId === chatId ? {...c, type: chat.type || c.type} : c))});
|
|
411
|
+
await say(chat.id, `This chat was already linked as <b>${esc(had.name)}</b>.`);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (s.chats.length >= MAX_CHATS) { await say(chat.id, 'Too many chats are linked already - unlink one in the admin first.'); return; }
|
|
415
|
+
const added = {id: randomUUID(), chatId, name: chatName(chat), type: chat.type || 'private', linkedAt: new Date().toISOString(), paused: false, lastError: '',
|
|
416
|
+
ownerId: s.linkOwnerId || '', ownerName: s.linkOwnerName || '', ...defaultRouting()};
|
|
417
|
+
save({linkSecret: '', linkSecretUntil: '', linkOwnerId: '', linkOwnerName: '', chats: [...s.chats, added]});
|
|
418
|
+
await say(chat.id, `✅ Linked as <b>${esc(added.name)}</b>. Warning and critical alerts from ${esc(siteName() || 'the site')} will arrive here; change what this chat gets in the admin, under Telegram › Chats.`);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Checked by the secret Telegram echoes in its header; answered 200 at once (Telegram retries anything else,
|
|
423
|
+
* and a failure here must not make it retry an update forever) and handled after, one at a time per chat,
|
|
424
|
+
* so a customer's messages stay in order and a busy chat never holds up another. Telegram resends an update it thinks was lost: its update_id is
|
|
425
|
+
* remembered, so a repeat does nothing. Understands /link <code>, /unlink and, without Telegram Pro, /start
|
|
426
|
+
* and /help; anything else is offered to Telegram Pro.
|
|
427
|
+
*/
|
|
428
|
+
const seen = new Set();
|
|
429
|
+
// One chain per chat: a chat whose messages wait (a busy staff chat) never holds up another's.
|
|
430
|
+
const lanes = new Map(); // chat id -> {chain, waiting}
|
|
431
|
+
const MAX_WAITING = 100;
|
|
432
|
+
fastify.post('/webhook', {config: {rateLimit: {max: 3000, timeWindow: '1 minute'}}}, async (request, reply) => {
|
|
433
|
+
const s = st();
|
|
434
|
+
if (!ready() || !sameSecret(request.headers['x-telegram-bot-api-secret-token'], s.secret)) return reply.code(401).send({ok: false});
|
|
435
|
+
const update = request.body || {};
|
|
436
|
+
const uid = Number(update.update_id);
|
|
437
|
+
if (Number.isFinite(uid)) {
|
|
438
|
+
if (seen.has(uid)) return {ok: true};
|
|
439
|
+
seen.add(uid);
|
|
440
|
+
if (seen.size > SEEN_UPDATES) seen.delete(seen.values().next().value);
|
|
441
|
+
}
|
|
442
|
+
const key = String(update.message?.chat?.id ?? '');
|
|
443
|
+
if (!key) return {ok: true};
|
|
444
|
+
let lane = lanes.get(key);
|
|
445
|
+
if (!lane) { lane = {chain: Promise.resolve(), waiting: 0}; lanes.set(key, lane); }
|
|
446
|
+
if (lane.waiting >= MAX_WAITING) { log.warn(`[telegram] ${MAX_WAITING} updates waiting for one chat - one dropped.`); return {ok: true}; }
|
|
447
|
+
lane.waiting++;
|
|
448
|
+
const done = lane.chain.then(() => handle(update.message)).finally(() => {
|
|
449
|
+
lane.waiting--;
|
|
450
|
+
if (!lane.waiting && lanes.get(key) === lane) lanes.delete(key);
|
|
451
|
+
});
|
|
452
|
+
lane.chain = done.catch(() => {});
|
|
453
|
+
if (options.awaitUpdates) await done; // tests only
|
|
454
|
+
return {ok: true};
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
async function handle(msg) {
|
|
458
|
+
const s = st();
|
|
459
|
+
const chat = msg?.chat;
|
|
460
|
+
if (!chat?.id || !ready()) return;
|
|
461
|
+
try {
|
|
462
|
+
// A group that became a supergroup has a new id: follow it.
|
|
463
|
+
if (msg.migrate_to_chat_id) {
|
|
464
|
+
const from = String(chat.id);
|
|
465
|
+
if (s.chats.some(c => c.chatId === from)) save({chats: s.chats.map(c => (c.chatId === from ? {...c, chatId: String(msg.migrate_to_chat_id), type: 'supergroup'} : c))});
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const cmd = parseCommand(msg.text);
|
|
469
|
+
const linked = st().chats.find(c => c.chatId === String(chat.id)) || null;
|
|
470
|
+
if (cmd?.command === 'link') { await link(msg, cmd.arg); return; }
|
|
471
|
+
if (cmd?.command === 'unlink' && linked) {
|
|
472
|
+
save({chats: st().chats.filter(c => c.id !== linked.id)});
|
|
473
|
+
await say(chat.id, 'Unlinked. Nothing more will arrive here.');
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
for (const [name, h] of reg.handlers) {
|
|
477
|
+
try {
|
|
478
|
+
if (await h.onMessage(msg, {command: cmd, linked: linked ? {id: linked.id, name: linked.name, type: linked.type} : null, botName: s.botName})) return;
|
|
479
|
+
} catch (err) { log.warn(`[telegram] ${name} could not take an update: ${err.message}`); }
|
|
480
|
+
}
|
|
481
|
+
if (cmd?.command === 'start' && chat.type === 'private') {
|
|
482
|
+
await say(chat.id, `Hello! This is the bot of ${esc(siteName() || 'a website')}. It sends the team's alerts; it does not read messages.`);
|
|
483
|
+
} else if (cmd?.command === 'help') {
|
|
484
|
+
await say(chat.id, 'Commands: /link <code> links this chat (the code is in the admin, Telegram › Chats); /unlink stops what arrives here.');
|
|
485
|
+
}
|
|
486
|
+
} catch (err) {
|
|
487
|
+
log.warn(`[telegram] update: ${err.message}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "telegram",
|
|
3
|
+
"displayName": "Telegram",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"tier": "free",
|
|
6
|
+
"description": "Your own Telegram bot sends the team the site's alerts and form submissions - to a person or a group, each chat with its own choice of what it gets.",
|
|
7
|
+
"author": "Domma CMS",
|
|
8
|
+
"date": "2026-11-16",
|
|
9
|
+
"icon": "send",
|
|
10
|
+
"permissions": [
|
|
11
|
+
{
|
|
12
|
+
"key": "telegram",
|
|
13
|
+
"label": "Telegram",
|
|
14
|
+
"group": "Plugins",
|
|
15
|
+
"icon": "send",
|
|
16
|
+
"description": "See the Telegram connection and linked chats (read); connect the bot, link chats and choose what each gets (manage).",
|
|
17
|
+
"actions": [
|
|
18
|
+
{
|
|
19
|
+
"key": "read",
|
|
20
|
+
"label": "Read",
|
|
21
|
+
"description": "See the bot and the linked chats"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"key": "manage",
|
|
25
|
+
"label": "Manage",
|
|
26
|
+
"description": "Connect the bot, link and unlink chats, choose what each chat gets"
|
|
27
|
+
}
|
|
28
|
+
],
|
|
29
|
+
"grant": [
|
|
30
|
+
"admin"
|
|
31
|
+
]
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
"admin": {
|
|
35
|
+
"css": [
|
|
36
|
+
"admin/css/index.css"
|
|
37
|
+
],
|
|
38
|
+
"sidebar": [
|
|
39
|
+
{
|
|
40
|
+
"id": "telegram",
|
|
41
|
+
"text": "Telegram",
|
|
42
|
+
"icon": "send",
|
|
43
|
+
"url": "#/plugins/telegram",
|
|
44
|
+
"section": "#/plugins/telegram",
|
|
45
|
+
"permission": "telegram",
|
|
46
|
+
"countUrl": "/api/plugins/telegram/count"
|
|
47
|
+
}
|
|
48
|
+
],
|
|
49
|
+
"routes": [
|
|
50
|
+
{
|
|
51
|
+
"path": "/plugins/telegram",
|
|
52
|
+
"view": "plugin-telegram",
|
|
53
|
+
"title": "Telegram - Domma CMS"
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"path": "/plugins/telegram/:tab",
|
|
57
|
+
"view": "plugin-telegram",
|
|
58
|
+
"title": "Telegram - Domma CMS"
|
|
59
|
+
}
|
|
60
|
+
],
|
|
61
|
+
"views": {
|
|
62
|
+
"plugin-telegram": {
|
|
63
|
+
"entry": "telegram/admin/views/telegram.js",
|
|
64
|
+
"exportName": "telegramView"
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"docs": {
|
|
69
|
+
"permission": "telegram"
|
|
70
|
+
}
|
|
71
|
+
}
|