create-heresay 0.2.39 → 0.2.40
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/package.json +1 -1
- package/release/VERSION +1 -1
- package/release/functions/lib/core/handler.js +7 -1
- package/release/functions/lib/core/notifications.js +27 -5
- package/release/functions/lib/core/telegram.js +383 -0
- package/release/functions/lib/core/version.js +1 -1
- package/release/functions/lib/providers/firebase/api.js +2 -0
- package/release/functions/package.json +1 -1
- package/release/public/dashboard.js +57 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-heresay",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.40",
|
|
4
4
|
"description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/release/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.2.
|
|
1
|
+
0.2.40
|
|
@@ -6,6 +6,7 @@ import { mcp } from './chat.js';
|
|
|
6
6
|
import { withdraw } from './withdraw.js';
|
|
7
7
|
import { alsoReported, duplicatesOf, follow, merge, parseFixRef, stampFix, unmerge } from './duplicates.js';
|
|
8
8
|
import { notificationSettings, notify } from './notifications.js';
|
|
9
|
+
import { linkRoutes, telegramWebhook } from './telegram.js';
|
|
9
10
|
import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isFramework, isPlatform, isReportType, isSignIn, toReporterView, } from './types.js';
|
|
10
11
|
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
|
|
11
12
|
/**
|
|
@@ -192,6 +193,9 @@ async function route(req, deps) {
|
|
|
192
193
|
return withdrawMine(req, deps);
|
|
193
194
|
if (p[0] === 'reports' && req.method === 'OPTIONS')
|
|
194
195
|
return preflight(req);
|
|
196
|
+
// Telegram calls this itself, from its servers: no Origin, no sign-in (ADR 0016).
|
|
197
|
+
if (p[0] === 'telegram' && p[1] === 'webhook' && p.length === 3 && req.method === 'POST')
|
|
198
|
+
return telegramWebhook(p[2], req, deps, triage);
|
|
195
199
|
// Chat apps (ChatGPT and other MCP clients): OAuth with the member's own sign-in, then MCP.
|
|
196
200
|
if (p[0] === 'mcp' && p.length === 1)
|
|
197
201
|
return mcp(req, deps);
|
|
@@ -239,6 +243,8 @@ async function route(req, deps) {
|
|
|
239
243
|
return json(403, { error: 'Only an owner can manage notifications.' });
|
|
240
244
|
return notificationSettings(p, req, deps, parseBody(req.body));
|
|
241
245
|
}
|
|
246
|
+
if (p[0] === 'telegram' && p[1] === 'link-code' || p[0] === 'telegram' && p[1] === 'link')
|
|
247
|
+
return linkRoutes(p, member, req, deps);
|
|
242
248
|
if (p[0] === 'agent-tokens')
|
|
243
249
|
return tokens(p, member, req, deps, parseBody(req.body));
|
|
244
250
|
// The dashboard's "Allow this chat app?" page, and the chat apps a member has connected.
|
|
@@ -645,7 +651,7 @@ function transitionRes(t) {
|
|
|
645
651
|
// Two tabs triaging the same report: the second is told what the first did.
|
|
646
652
|
return json(409, { error: `this report is already ${t.status}`, status: t.status });
|
|
647
653
|
}
|
|
648
|
-
async function triage(project, report_id, action, uid, req, deps) {
|
|
654
|
+
export async function triage(project, report_id, action, uid, req, deps) {
|
|
649
655
|
const body = parseBody(req.body);
|
|
650
656
|
const at = new Date(deps.now()).toISOString();
|
|
651
657
|
let t;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BOT_LOGO_JPEG_BASE64 } from './bot-logo.js';
|
|
2
|
+
import { reportKeyboard, syncWebhook } from './telegram.js';
|
|
2
3
|
export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
|
|
3
4
|
export class TelegramLookupError extends Error {
|
|
4
5
|
}
|
|
@@ -17,6 +18,7 @@ export function notificationView(settings) {
|
|
|
17
18
|
cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
|
|
18
19
|
};
|
|
19
20
|
}
|
|
21
|
+
const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled;
|
|
20
22
|
class SettingsError extends Error {
|
|
21
23
|
}
|
|
22
24
|
const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
|
|
@@ -106,7 +108,8 @@ export async function notificationSettings(p, req, deps, body) {
|
|
|
106
108
|
}
|
|
107
109
|
if (p.length === 1 && req.method === 'PATCH') {
|
|
108
110
|
try {
|
|
109
|
-
const
|
|
111
|
+
const beforeTelegram = (await deps.store.getInstance())?.notifications?.telegram;
|
|
112
|
+
const before = beforeTelegram?.token ?? null;
|
|
110
113
|
const instance = await deps.store.updateInstance((cur) => ({
|
|
111
114
|
...cur, notifications: patchNotifications(cur.notifications ?? defaultNotifications(), body),
|
|
112
115
|
}));
|
|
@@ -121,7 +124,10 @@ export async function notificationSettings(p, req, deps, body) {
|
|
|
121
124
|
deps.log('api.telegram_photo', { ok: false });
|
|
122
125
|
} // never log the error: it may carry the token URL
|
|
123
126
|
}
|
|
124
|
-
|
|
127
|
+
// Buttons in Telegram need our webhook on the bot (or off it). Never fatal either.
|
|
128
|
+
if (telegramChanged(beforeTelegram, instance.notifications.telegram))
|
|
129
|
+
await syncWebhook(beforeTelegram, req, deps);
|
|
130
|
+
return json(200, { notifications: notificationView((await deps.store.getInstance()).notifications) });
|
|
125
131
|
}
|
|
126
132
|
catch (error) {
|
|
127
133
|
// Validation messages are ours; never expose backend exceptions or credentials.
|
|
@@ -143,6 +149,19 @@ export async function notificationSettings(p, req, deps, body) {
|
|
|
143
149
|
if (!await deps.store.hit(`notification-lookup:telegram:${start}`, 30, start + 60_000)) {
|
|
144
150
|
return json(429, { error: 'Wait a minute before looking again.' });
|
|
145
151
|
}
|
|
152
|
+
// Telegram refuses getUpdates once a webhook is set, and ours is. Say so instead of failing.
|
|
153
|
+
const saved = (await deps.store.getInstance()).notifications?.telegram;
|
|
154
|
+
if (saved?.token === token && saved.webhook_url && deps.telegramApi) {
|
|
155
|
+
const me = await deps.telegramApi(token, 'getMe', {});
|
|
156
|
+
const bot = me.result;
|
|
157
|
+
if (me.ok) {
|
|
158
|
+
return json(200, {
|
|
159
|
+
bot: { username: typeof bot?.username === 'string' ? bot.username : '', name: typeof bot?.first_name === 'string' ? bot.first_name.slice(0, 120) : '' },
|
|
160
|
+
chats: [], connected: true,
|
|
161
|
+
note: 'Telegram is connected; to pick a different chat, enter its chat ID.',
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
146
165
|
if (!deps.telegramLookup)
|
|
147
166
|
return json(503, { error: 'Telegram lookup is unavailable.' });
|
|
148
167
|
try {
|
|
@@ -195,6 +214,7 @@ export async function notificationSettings(p, req, deps, body) {
|
|
|
195
214
|
}
|
|
196
215
|
return json(404, { error: 'not found' });
|
|
197
216
|
}
|
|
217
|
+
const actionsReady = (tg) => !!(tg.webhook_secret && tg.webhook_url);
|
|
198
218
|
/** Metadata only: open reports and reporter details must never flow into an integration. */
|
|
199
219
|
export async function notify(event, project, reportId, deps) {
|
|
200
220
|
try {
|
|
@@ -212,7 +232,9 @@ export async function notify(event, project, reportId, deps) {
|
|
|
212
232
|
if (!settings[provider].enabled)
|
|
213
233
|
return;
|
|
214
234
|
try {
|
|
215
|
-
|
|
235
|
+
const markup = provider === 'telegram' && event === 'new_report' && actionsReady(settings.telegram)
|
|
236
|
+
? reportKeyboard(project.id, reportId) : null;
|
|
237
|
+
await deps.sendNotification(provider, settings[provider], text, markup ? { telegram_markup: markup } : undefined);
|
|
216
238
|
deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
|
|
217
239
|
}
|
|
218
240
|
catch {
|
|
@@ -228,13 +250,13 @@ export async function notify(event, project, reportId, deps) {
|
|
|
228
250
|
}
|
|
229
251
|
/** Shared HTTP transport; a backend adapter supplies this to the portable core. */
|
|
230
252
|
export function notificationSender(http = fetch) {
|
|
231
|
-
return async (provider, destination, text) => {
|
|
253
|
+
return async (provider, destination, text, extra) => {
|
|
232
254
|
let url, body;
|
|
233
255
|
if (!destination.token)
|
|
234
256
|
throw new Error('Notification token missing.');
|
|
235
257
|
if (provider === 'telegram' && 'chat_id' in destination) {
|
|
236
258
|
url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
|
|
237
|
-
body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true } };
|
|
259
|
+
body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
|
|
238
260
|
}
|
|
239
261
|
else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
|
|
240
262
|
const u = new URL(destination.endpoint);
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Acting on notifications from Telegram (ADR 0016). Telegram calls the webhook; a tap only counts
|
|
3
|
+
* if the Telegram user was linked, with a one-time code, to someone who is still on the team.
|
|
4
|
+
* Accept and decline go through the same `triage` the dashboard uses, so nothing is duplicated:
|
|
5
|
+
* a report still reaches an agent only through a person's accept, and declining still needs a reason.
|
|
6
|
+
* Everything here is plain text (no parse_mode): reporter text is untrusted.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
|
|
9
|
+
import { baseUrl } from './oauth.js';
|
|
10
|
+
import { LIMITS } from './types.js';
|
|
11
|
+
export function telegramApi(http = fetch) {
|
|
12
|
+
return async (token, method, body) => {
|
|
13
|
+
try {
|
|
14
|
+
const response = await http(`https://api.telegram.org/bot${token}/${method}`, {
|
|
15
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
|
|
16
|
+
signal: AbortSignal.timeout(5000), redirect: 'error',
|
|
17
|
+
});
|
|
18
|
+
const result = await response.json().catch(() => ({}));
|
|
19
|
+
return { ok: response.ok && result.ok === true, result: result.result };
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return { ok: false };
|
|
23
|
+
} // the error may carry the token URL
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const LINK_TTL_MS = 10 * 60_000;
|
|
27
|
+
const DECLINE_TTL_MS = 10 * 60_000;
|
|
28
|
+
const TEXT_MAX = 4096;
|
|
29
|
+
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O, 1/I
|
|
30
|
+
const sha = (s) => createHash('sha256').update(s).digest('hex');
|
|
31
|
+
const json = (status, body) => ({ status, body, headers: { 'cache-control': 'no-store' } });
|
|
32
|
+
// ---- the keyboard on a "new report" notification -------------------------------------------
|
|
33
|
+
/** a = accept, d = decline, t = full text; then the project and report ids. Null if it would pass 64 bytes. */
|
|
34
|
+
export function reportKeyboard(project_id, report_id) {
|
|
35
|
+
const data = (a) => `${a}|${project_id}|${report_id}`;
|
|
36
|
+
if (Buffer.byteLength(data('a')) > 64)
|
|
37
|
+
return null;
|
|
38
|
+
return { inline_keyboard: [[
|
|
39
|
+
{ text: 'Accept', callback_data: data('a') },
|
|
40
|
+
{ text: 'Decline', callback_data: data('d') },
|
|
41
|
+
{ text: 'Show full text', callback_data: data('t') },
|
|
42
|
+
]] };
|
|
43
|
+
}
|
|
44
|
+
// ---- keeping Telegram's webhook in step with the saved bot ----------------------------------
|
|
45
|
+
/** The secret in the webhook URL. A second value, derived from it, goes in Telegram's header. */
|
|
46
|
+
export const headerSecret = (secret) => createHash('sha256').update('heresay-telegram-header:' + secret).digest('base64url');
|
|
47
|
+
export const actionsConnected = (tg) => !!(tg?.enabled && tg.token && tg.webhook_secret && tg.webhook_url);
|
|
48
|
+
/**
|
|
49
|
+
* After notification settings are saved: point the bot's webhook at us, or take it away. Skipped
|
|
50
|
+
* silently when the public address isn't https (the emulator). Never fails the save and never logs
|
|
51
|
+
* the token or the secret.
|
|
52
|
+
*/
|
|
53
|
+
export async function syncWebhook(before, req, deps) {
|
|
54
|
+
try {
|
|
55
|
+
const api = deps.telegramApi;
|
|
56
|
+
const tg = (await deps.store.getInstance())?.notifications?.telegram;
|
|
57
|
+
if (!api || !tg)
|
|
58
|
+
return;
|
|
59
|
+
const old = before?.token ?? null;
|
|
60
|
+
const want = tg.enabled && !!tg.token;
|
|
61
|
+
const setUrl = (url) => deps.store.updateInstance((cur) => {
|
|
62
|
+
const n = structuredClone(cur.notifications);
|
|
63
|
+
n.telegram.webhook_url = url;
|
|
64
|
+
return { ...cur, notifications: n };
|
|
65
|
+
});
|
|
66
|
+
if (old && (!want || old !== tg.token)) {
|
|
67
|
+
const r = await api(old, 'deleteWebhook', {});
|
|
68
|
+
deps.log('api.telegram_webhook', { action: 'delete', ok: r.ok });
|
|
69
|
+
}
|
|
70
|
+
if (!want) {
|
|
71
|
+
if (tg.webhook_url)
|
|
72
|
+
await setUrl(null);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const base = baseUrl(req, deps);
|
|
76
|
+
if (!base.startsWith('https://'))
|
|
77
|
+
return;
|
|
78
|
+
let secret = tg.webhook_secret;
|
|
79
|
+
if (!secret) {
|
|
80
|
+
secret = randomBytes(24).toString('base64url');
|
|
81
|
+
const fresh = secret;
|
|
82
|
+
const inst = await deps.store.updateInstance((cur) => {
|
|
83
|
+
const n = structuredClone(cur.notifications);
|
|
84
|
+
n.telegram.webhook_secret = n.telegram.webhook_secret ?? fresh; // once per instance
|
|
85
|
+
return { ...cur, notifications: n };
|
|
86
|
+
});
|
|
87
|
+
secret = inst.notifications.telegram.webhook_secret;
|
|
88
|
+
}
|
|
89
|
+
const url = `${base}/v1/telegram/webhook/${secret}`;
|
|
90
|
+
if (tg.webhook_url === url && old === tg.token)
|
|
91
|
+
return;
|
|
92
|
+
const r = await api(tg.token, 'setWebhook', {
|
|
93
|
+
url, secret_token: headerSecret(secret), allowed_updates: ['message', 'callback_query'],
|
|
94
|
+
});
|
|
95
|
+
deps.log('api.telegram_webhook', { action: 'set', ok: r.ok });
|
|
96
|
+
if (r.ok)
|
|
97
|
+
await setUrl(url);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
deps.log('api.telegram_webhook', { action: 'sync', ok: false });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// ---- linking: dashboard side ----------------------------------------------------------------
|
|
104
|
+
const normEmail = (e) => e.trim().toLowerCase();
|
|
105
|
+
const normCode = (c) => c.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
|
106
|
+
const codeId = (c) => sha('heresay-telegram-link:' + normCode(c));
|
|
107
|
+
async function minute(deps, bucket, limit) {
|
|
108
|
+
const start = Math.floor(deps.now() / 60_000) * 60_000;
|
|
109
|
+
return deps.store.hit(`${bucket}:${start}`, limit, start + 60_000);
|
|
110
|
+
}
|
|
111
|
+
/** Member-level (any signed-in member): link status, a one-time code, and unlink. */
|
|
112
|
+
export async function linkRoutes(p, me, req, deps) {
|
|
113
|
+
const tg = (await deps.store.getInstance())?.notifications?.telegram;
|
|
114
|
+
const mine = (l) => Object.values(l ?? {}).some((e) => normEmail(e) === normEmail(me.email));
|
|
115
|
+
if (p[1] === 'link' && p.length === 2 && req.method === 'GET') {
|
|
116
|
+
return json(200, { connected: actionsConnected(tg), linked: mine(tg?.links) });
|
|
117
|
+
}
|
|
118
|
+
if (p[1] === 'link-code' && p.length === 2 && req.method === 'POST') {
|
|
119
|
+
if (!actionsConnected(tg)) {
|
|
120
|
+
return json(409, { error: 'Telegram isn’t connected for actions yet. An owner connects a bot under Notifications, on this Heresay’s public https address.' });
|
|
121
|
+
}
|
|
122
|
+
const start = Math.floor(deps.now() / 600_000) * 600_000;
|
|
123
|
+
if (!await deps.store.hit(`tg-link-code:${normEmail(me.email)}:${start}`, 5, start + 600_000)) {
|
|
124
|
+
return json(429, { error: 'Wait a few minutes before making another code.' });
|
|
125
|
+
}
|
|
126
|
+
for (const old of await deps.store.listAuth('link')) {
|
|
127
|
+
if (old.data.email === normEmail(me.email))
|
|
128
|
+
await deps.store.deleteAuth('link', old.id);
|
|
129
|
+
}
|
|
130
|
+
let code = '';
|
|
131
|
+
for (let i = 0; i < 8; i++)
|
|
132
|
+
code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
|
|
133
|
+
const expires = new Date(deps.now() + LINK_TTL_MS).toISOString();
|
|
134
|
+
await deps.store.putAuth({ kind: 'link', id: codeId(code), data: { email: normEmail(me.email) }, expires_at: expires });
|
|
135
|
+
let bot_username = null;
|
|
136
|
+
const bot = await deps.telegramApi?.(tg.token, 'getMe', {});
|
|
137
|
+
const name = bot?.result?.username;
|
|
138
|
+
if (bot?.ok && typeof name === 'string')
|
|
139
|
+
bot_username = name;
|
|
140
|
+
return json(200, { code, expires_at: expires, bot_username });
|
|
141
|
+
}
|
|
142
|
+
if (p[1] === 'link' && p.length === 2 && req.method === 'DELETE') {
|
|
143
|
+
await deps.store.updateInstance((cur) => {
|
|
144
|
+
const n = cur.notifications;
|
|
145
|
+
if (!n?.telegram.links)
|
|
146
|
+
return cur;
|
|
147
|
+
const next = structuredClone(n);
|
|
148
|
+
for (const [id, e] of Object.entries(next.telegram.links))
|
|
149
|
+
if (normEmail(e) === normEmail(me.email))
|
|
150
|
+
delete next.telegram.links[id];
|
|
151
|
+
return { ...cur, notifications: next };
|
|
152
|
+
});
|
|
153
|
+
for (const old of await deps.store.listAuth('link')) {
|
|
154
|
+
if (old.data.email === normEmail(me.email))
|
|
155
|
+
await deps.store.deleteAuth('link', old.id);
|
|
156
|
+
}
|
|
157
|
+
return json(200, { ok: true });
|
|
158
|
+
}
|
|
159
|
+
return json(404, { error: 'not found' });
|
|
160
|
+
}
|
|
161
|
+
const same = (a, b) => {
|
|
162
|
+
const x = createHash('sha256').update(a).digest(), y = createHash('sha256').update(b).digest();
|
|
163
|
+
return timingSafeEqual(x, y);
|
|
164
|
+
};
|
|
165
|
+
const label = (s) => ({ accepted: 'accepted', declined: 'declined', fixed: 'fixed', withdrawn: 'withdrawn', open: 'open' }[s] ?? s);
|
|
166
|
+
/** Telegram counts UTF-16 units; never leave half a character at the cut. */
|
|
167
|
+
export function capText(s, max = TEXT_MAX) {
|
|
168
|
+
if (s.length <= max)
|
|
169
|
+
return s;
|
|
170
|
+
let cut = s.slice(0, max - 1);
|
|
171
|
+
if (/[\ud800-\udbff]$/.test(cut))
|
|
172
|
+
cut = cut.slice(0, -1);
|
|
173
|
+
return cut + '…';
|
|
174
|
+
}
|
|
175
|
+
export async function telegramWebhook(secret, req, deps, triage) {
|
|
176
|
+
const notFound = () => ({ status: 404, body: null });
|
|
177
|
+
// Before anything else, so a flood of guesses is cheap. Telegram's own servers are few; generous.
|
|
178
|
+
if (!await minute(deps, `tg-hook-ip:${sha(req.ip)}`, 1200))
|
|
179
|
+
return { status: 429, body: null };
|
|
180
|
+
const instance = await deps.store.getInstance();
|
|
181
|
+
const tg = instance?.notifications?.telegram;
|
|
182
|
+
if (!tg?.enabled || !tg.token || !tg.webhook_secret)
|
|
183
|
+
return notFound();
|
|
184
|
+
// Both, always evaluated, in constant time.
|
|
185
|
+
const pathOk = same(secret, tg.webhook_secret);
|
|
186
|
+
const headerOk = same(req.headers['x-telegram-bot-api-secret-token'] ?? '', headerSecret(tg.webhook_secret));
|
|
187
|
+
if (!(pathOk && headerOk))
|
|
188
|
+
return notFound();
|
|
189
|
+
try {
|
|
190
|
+
const body = req.body instanceof Uint8Array ? JSON.parse(Buffer.from(req.body).toString('utf8')) : req.body;
|
|
191
|
+
if (body && typeof body === 'object')
|
|
192
|
+
await handleUpdate(body, instance.members, tg, deps, triage);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
deps.log('api.telegram_update', { ok: false }); // never the error: it may carry the token URL
|
|
196
|
+
}
|
|
197
|
+
return { status: 200, body: { ok: true } }; // Telegram retries anything else
|
|
198
|
+
}
|
|
199
|
+
const isConfiguredChat = (chat, tg) => String(chat.id) === tg.chat_id || (!!chat.username && tg.chat_id.toLowerCase() === '@' + chat.username.toLowerCase());
|
|
200
|
+
async function handleUpdate(u, members, tg, deps, triage) {
|
|
201
|
+
const token = tg.token;
|
|
202
|
+
const api = deps.telegramApi;
|
|
203
|
+
if (!api)
|
|
204
|
+
return;
|
|
205
|
+
const msg = u.callback_query?.message ?? u.message;
|
|
206
|
+
const from = u.callback_query?.from ?? u.message?.from;
|
|
207
|
+
if (!msg?.chat || !from || from.is_bot)
|
|
208
|
+
return;
|
|
209
|
+
if (!await minute(deps, `tg-hook-chat:${msg.chat.id}`, 60))
|
|
210
|
+
return;
|
|
211
|
+
const say = (text, extra = {}) => api(token, 'sendMessage', { chat_id: msg.chat.id, text: capText(text), link_preview_options: { is_disabled: true }, ...extra });
|
|
212
|
+
// A person tapping a button.
|
|
213
|
+
if (u.callback_query) {
|
|
214
|
+
const cb = u.callback_query;
|
|
215
|
+
if (!cb.message || !isConfiguredChat(cb.message.chat, tg))
|
|
216
|
+
return; // somewhere we never posted
|
|
217
|
+
const answer = (text, alert = false) => api(token, 'answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text: text.slice(0, 200), show_alert: alert } : {}) });
|
|
218
|
+
const m = /^([adt])\|([\w-]{1,40})\|([\w-]{1,40})$/.exec(cb.data ?? '');
|
|
219
|
+
if (!m) {
|
|
220
|
+
await answer();
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const email = actor(members, tg, from.id);
|
|
224
|
+
if (!email) {
|
|
225
|
+
await answer('Link your Telegram first: Heresay dashboard > Notifications', true);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const project = await deps.store.getProject(m[2]);
|
|
229
|
+
const report = project ? await deps.store.getReport(project.id, m[3]) : null;
|
|
230
|
+
if (!project || !report) {
|
|
231
|
+
await answer('That report no longer exists.', true);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
// A decided report: say so, tidy the message, change nothing.
|
|
235
|
+
async function alreadyOrFail(res, pr, id, ans, message) {
|
|
236
|
+
const status = res.body?.status;
|
|
237
|
+
if (res.status === 409 && status) {
|
|
238
|
+
const r = await deps.store.getReport(pr.id, id);
|
|
239
|
+
const verdict = r ? decided(r) : null;
|
|
240
|
+
await ans(verdict ?? `Already ${label(status)}.`, true);
|
|
241
|
+
if (verdict && (status === 'accepted' || status === 'declined'))
|
|
242
|
+
await finish(api, token, message, verdict.replace(/^Already /, '').replace(/^./, (c) => c.toUpperCase()));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
await ans(res.status === 409 ? 'This report was merged into another. Decide it in the dashboard.' : 'That didn’t work. Try the dashboard.', true);
|
|
246
|
+
}
|
|
247
|
+
if (m[1] === 't') {
|
|
248
|
+
await answer();
|
|
249
|
+
await say(`${report.type} · ${project.name}\n\n${report.text}`, { reply_parameters: { message_id: cb.message.message_id } });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (m[1] === 'a') {
|
|
253
|
+
const res = await triage(project, report.id, 'accept', email, fakeReq(), deps);
|
|
254
|
+
if (res.status === 200) {
|
|
255
|
+
await answer('Accepted');
|
|
256
|
+
await finish(api, token, cb.message, `Accepted by ${email}`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
await alreadyOrFail(res, project, report.id, answer, cb.message);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
// Decline: ask for the reason first; the reporter reads it.
|
|
263
|
+
if (report.status !== 'open') {
|
|
264
|
+
await alreadyOrFail({ status: 409, body: { status: report.status } }, project, report.id, answer, cb.message);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
await answer('Reply to the next message with your reason.');
|
|
268
|
+
const prompt = await say('Reply with why you’re declining this (the reporter will read it)', {
|
|
269
|
+
reply_parameters: { message_id: cb.message.message_id },
|
|
270
|
+
reply_markup: { force_reply: true, selective: true, input_field_placeholder: 'Why?' },
|
|
271
|
+
});
|
|
272
|
+
const pid = prompt.result?.message_id;
|
|
273
|
+
if (prompt.ok && typeof pid === 'number') {
|
|
274
|
+
await deps.store.putAuth({
|
|
275
|
+
kind: 'decline', id: `${cb.message.chat.id}:${pid}`, expires_at: new Date(deps.now() + DECLINE_TTL_MS).toISOString(),
|
|
276
|
+
data: { user: from.id, project: project.id, report: report.id, message_id: cb.message.message_id, text: cb.message.text ?? '' },
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
// A message: a link code, or the reason for a decline.
|
|
282
|
+
const text = msg.text?.trim() ?? '';
|
|
283
|
+
const cmd = /^\/(?:start|link)(?:@\w+)?(?:\s+(.+))?$/i.exec(text);
|
|
284
|
+
if (cmd) {
|
|
285
|
+
const inPrivate = msg.chat.type === 'private';
|
|
286
|
+
if (!inPrivate && !isConfiguredChat(msg.chat, tg))
|
|
287
|
+
return;
|
|
288
|
+
if (!cmd[1]) {
|
|
289
|
+
if (inPrivate)
|
|
290
|
+
await say('To link your Telegram: in the Heresay dashboard open Notifications, tap “Link my Telegram”, then send me /start and the code.');
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const start = Math.floor(deps.now() / 3600_000) * 3600_000;
|
|
294
|
+
if (!await deps.store.hit(`tg-link-try:${from.id}:${start}`, 10, start + 3600_000)) {
|
|
295
|
+
await say('Too many tries. Wait an hour, then make a new code.');
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const rec = await deps.store.takeAuth('link', codeId(cmd[1])); // one use, however many try at once
|
|
299
|
+
const email = rec && rec.expires_at && Date.parse(rec.expires_at) > deps.now() ? String(rec.data.email) : null;
|
|
300
|
+
const member = email ? members.find((x) => normEmail(x.email) === email) : null;
|
|
301
|
+
if (!email || !member) {
|
|
302
|
+
await say('That code didn’t work, or it expired. Make a new one in the Heresay dashboard under Notifications.');
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
await deps.store.updateInstance((cur) => {
|
|
306
|
+
const n = structuredClone(cur.notifications);
|
|
307
|
+
n.telegram.links = { ...(n.telegram.links ?? {}), [String(from.id)]: member.email };
|
|
308
|
+
return { ...cur, notifications: n };
|
|
309
|
+
});
|
|
310
|
+
deps.log('api.telegram_linked', { ok: true });
|
|
311
|
+
await say(`Linked as ${member.email}`);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const replyTo = msg.reply_to_message?.message_id;
|
|
315
|
+
if (replyTo === undefined || !isConfiguredChat(msg.chat, tg))
|
|
316
|
+
return;
|
|
317
|
+
const key = `${msg.chat.id}:${replyTo}`;
|
|
318
|
+
const pending = await deps.store.getAuth('decline', key);
|
|
319
|
+
if (!pending || pending.data.user !== from.id)
|
|
320
|
+
return; // someone else's prompt, or not ours
|
|
321
|
+
const reply = (t) => say(t, { reply_parameters: { message_id: msg.message_id } });
|
|
322
|
+
if (!pending.expires_at || Date.parse(pending.expires_at) <= deps.now()) {
|
|
323
|
+
await deps.store.deleteAuth('decline', key);
|
|
324
|
+
await reply('That took too long. Tap Decline on the report again.');
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const email = actor(members, tg, from.id);
|
|
328
|
+
if (!email) {
|
|
329
|
+
await reply('Link your Telegram first: Heresay dashboard > Notifications');
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (!text) {
|
|
333
|
+
await reply('Send the reason as text.');
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (text.length > LIMITS.reasonMax) {
|
|
337
|
+
await reply(`That reason is ${text.length} characters; the limit is ${LIMITS.reasonMax}. Send a shorter one.`);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const project = await deps.store.getProject(String(pending.data.project));
|
|
341
|
+
if (!project) {
|
|
342
|
+
await deps.store.deleteAuth('decline', key);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const res = await triage(project, String(pending.data.report), 'decline', email, fakeReq({ reason: text }), deps);
|
|
346
|
+
const original = { message_id: Number(pending.data.message_id), chat: msg.chat, text: String(pending.data.text ?? '') };
|
|
347
|
+
if (res.status === 200) {
|
|
348
|
+
await deps.store.deleteAuth('decline', key);
|
|
349
|
+
await finish(api, token, original, `Declined by ${email}: ${text}`);
|
|
350
|
+
await reply('Declined. The reporter will see your reason.');
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
if (res.status === 400) {
|
|
354
|
+
await reply('A reason is needed to decline. Send it as a reply.');
|
|
355
|
+
return;
|
|
356
|
+
} // stays pending
|
|
357
|
+
await deps.store.deleteAuth('decline', key);
|
|
358
|
+
const status = res.body?.status;
|
|
359
|
+
const r = await deps.store.getReport(project.id, String(pending.data.report));
|
|
360
|
+
await reply(r && status ? (decided(r) ?? `Already ${label(status)}.`) : 'This report was merged into another. Decide it in the dashboard.');
|
|
361
|
+
}
|
|
362
|
+
/** Telegram user id -> the member they're linked to, only while that person is still on the team. */
|
|
363
|
+
function actor(members, tg, telegramId) {
|
|
364
|
+
const linked = tg.links?.[String(telegramId)];
|
|
365
|
+
return linked ? members.find((m) => normEmail(m.email) === normEmail(linked))?.email ?? null : null;
|
|
366
|
+
}
|
|
367
|
+
/** "Already accepted by x" for a report somebody decided, else null. */
|
|
368
|
+
function decided(r) {
|
|
369
|
+
if (r.status === 'open')
|
|
370
|
+
return null;
|
|
371
|
+
const by = r.triaged_by ? ` by ${r.triaged_by}` : '';
|
|
372
|
+
return `Already ${label(r.status)}${by}${r.status === 'declined' && r.decline_reason ? `: ${r.decline_reason}` : ''}`;
|
|
373
|
+
}
|
|
374
|
+
const fakeReq = (body = {}) => ({ method: 'POST', path: '', query: {}, headers: {}, ip: '', body });
|
|
375
|
+
/** Append the outcome to the notification and take the buttons away. */
|
|
376
|
+
async function finish(api, token, message, line) {
|
|
377
|
+
await api(token, 'editMessageText', {
|
|
378
|
+
chat_id: message.chat.id, message_id: message.message_id,
|
|
379
|
+
text: capText(`${(message.text ?? '').replace(/\n\n(Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
|
|
380
|
+
link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [] },
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
//# sourceMappingURL=telegram.js.map
|
|
@@ -9,6 +9,7 @@ import { FirestoreStore } from './firestore-store.js';
|
|
|
9
9
|
import { handle } from '../../core/handler.js';
|
|
10
10
|
import { VERSION } from '../../core/version.js';
|
|
11
11
|
import { notificationSender, telegramLookup, telegramPhoto } from '../../core/notifications.js';
|
|
12
|
+
import { telegramApi } from '../../core/telegram.js';
|
|
12
13
|
const deps = {
|
|
13
14
|
store: new FirestoreStore(db),
|
|
14
15
|
async verifyIdToken(token) {
|
|
@@ -27,6 +28,7 @@ const deps = {
|
|
|
27
28
|
sendNotification: notificationSender(),
|
|
28
29
|
telegramLookup: telegramLookup(),
|
|
29
30
|
telegramPhoto: telegramPhoto(),
|
|
31
|
+
telegramApi: telegramApi(),
|
|
30
32
|
};
|
|
31
33
|
function selfOrigins() {
|
|
32
34
|
const id = process.env.GCLOUD_PROJECT;
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"scripts": {
|
|
10
10
|
"build": "tsc -p tsconfig.json",
|
|
11
11
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
12
|
-
"test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js'",
|
|
12
|
+
"test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js' 'lib-test/test/telegram.test.js'",
|
|
13
13
|
"build:test": "tsc -p tsconfig.test.json"
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
@@ -2050,6 +2050,7 @@
|
|
|
2050
2050
|
view.appendChild(el('p', { class: 'mute', text: 'Know when a report needs a hearing, or when work moves forward. These settings apply to every app in this Heresay.' }));
|
|
2051
2051
|
if (me.role !== 'owner') {
|
|
2052
2052
|
view.appendChild(el('section', { class: 'card' }, [el('p', { text: 'An owner can connect Telegram or Zoho Cliq and choose which events your team receives.' }), el('a', { href: '#/team', text: 'See team owners' })]));
|
|
2053
|
+
telegramActions(view);
|
|
2053
2054
|
return;
|
|
2054
2055
|
}
|
|
2055
2056
|
var content = el('div', {}, [loading()]);
|
|
@@ -2085,6 +2086,7 @@
|
|
|
2085
2086
|
content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
|
|
2086
2087
|
content.appendChild(el('p', { class: 'hint', text: 'Alerts include the app name, event, report ID, and a link to the dashboard. Reporter text and contact details stay in Heresay.' }));
|
|
2087
2088
|
destination('telegram', 'Telegram', settings.telegram);
|
|
2089
|
+
telegramActions(content);
|
|
2088
2090
|
destination('cliq', 'Zoho Cliq', settings.cliq);
|
|
2089
2091
|
|
|
2090
2092
|
function destination(provider, title, saved) {
|
|
@@ -2129,7 +2131,7 @@
|
|
|
2129
2131
|
*/
|
|
2130
2132
|
function telegramGuide() {
|
|
2131
2133
|
var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }) };
|
|
2132
|
-
var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null;
|
|
2134
|
+
var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
|
|
2133
2135
|
var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
|
|
2134
2136
|
var wait = el('div', { class: 'wait', role: 'status' });
|
|
2135
2137
|
var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
|
|
@@ -2198,7 +2200,7 @@
|
|
|
2198
2200
|
else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet. Follow the steps above, then')); wait.appendChild(again); }
|
|
2199
2201
|
wait.hidden = state === 'none';
|
|
2200
2202
|
}
|
|
2201
|
-
function stop() { clearTimeout(timer); timer = null; if (bot) drawWait(address.value ? 'none' : 'idle'); }
|
|
2203
|
+
function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
|
|
2202
2204
|
function watch() {
|
|
2203
2205
|
clearTimeout(timer);
|
|
2204
2206
|
until = Date.now() + 5 * 60 * 1000;
|
|
@@ -2218,11 +2220,12 @@
|
|
|
2218
2220
|
function lookup(quiet) {
|
|
2219
2221
|
return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
|
|
2220
2222
|
var fresh = !bot || bot.username !== b.bot.username;
|
|
2221
|
-
bot = b.bot; chats = b.chats;
|
|
2223
|
+
bot = b.bot; chats = b.chats; connected = !!b.connected;
|
|
2222
2224
|
g.botLine.textContent = '';
|
|
2223
2225
|
g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
|
|
2224
2226
|
if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [el('p', { class: 'hint', text: 'Who should get the alerts?' }), tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
|
|
2225
2227
|
drawChats();
|
|
2228
|
+
if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
|
|
2226
2229
|
}).catch(function (x) {
|
|
2227
2230
|
if (quiet && bot) return;
|
|
2228
2231
|
g.botLine.textContent = '';
|
|
@@ -2233,7 +2236,7 @@
|
|
|
2233
2236
|
function check() {
|
|
2234
2237
|
clearTimeout(checking);
|
|
2235
2238
|
checking = setTimeout(function () {
|
|
2236
|
-
lookup().then(function () { if (!address.value) watch(); else stop(); }).catch(function () {});
|
|
2239
|
+
lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
|
|
2237
2240
|
}, 400);
|
|
2238
2241
|
}
|
|
2239
2242
|
g.step2.appendChild(el('p', { class: 'hint', text: 'Paste your bot token above first. Then this step shows exactly what to tap.' }));
|
|
@@ -2299,6 +2302,56 @@
|
|
|
2299
2302
|
});
|
|
2300
2303
|
}
|
|
2301
2304
|
|
|
2305
|
+
/**
|
|
2306
|
+
* Tapping Accept or Decline in Telegram only counts for someone who linked their Telegram to their
|
|
2307
|
+
* own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only.
|
|
2308
|
+
*/
|
|
2309
|
+
function telegramActions(host) {
|
|
2310
|
+
var body = el('div', {}, [loading()]);
|
|
2311
|
+
host.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'Act from Telegram' }), body]));
|
|
2312
|
+
draw();
|
|
2313
|
+
function draw() {
|
|
2314
|
+
api('GET', '/telegram/link').then(function (b) {
|
|
2315
|
+
body.textContent = '';
|
|
2316
|
+
if (!b.connected) {
|
|
2317
|
+
body.appendChild(el('p', { class: 'hint', text: 'Not connected. Once an owner connects a Telegram bot above and this Heresay has a public https address, new-report alerts get Accept and Decline buttons and you can use them after linking your Telegram here.' }));
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
var msg = el('p', { role: 'status' }), shown = el('div', {});
|
|
2321
|
+
var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'Make a new code' : 'Link my Telegram' });
|
|
2322
|
+
make.onclick = function () {
|
|
2323
|
+
var done = busyButton(make, 'Making a code…');
|
|
2324
|
+
api('POST', '/telegram/link-code', {}).then(function (c) {
|
|
2325
|
+
var at = c.bot_username ? '@' + c.bot_username : 'your Heresay bot';
|
|
2326
|
+
shown.textContent = '';
|
|
2327
|
+
shown.appendChild(codeBlock('/start ' + c.code));
|
|
2328
|
+
shown.appendChild(el('p', {}, ['Send ', el('code', { text: '/start ' + c.code }), ' to ' + at + ', in a private chat or in the alerts group. This code works once and expires ',
|
|
2329
|
+
el('b', { text: 'at ' + new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
|
|
2330
|
+
if (c.bot_username) shown.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(c.bot_username) + '?start=' + encodeURIComponent(c.code), target: '_blank', rel: 'noopener noreferrer', text: 'Open ' + at + ' in Telegram ↗' }));
|
|
2331
|
+
msg.textContent = '';
|
|
2332
|
+
}).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; }).finally(done);
|
|
2333
|
+
};
|
|
2334
|
+
var kids = [
|
|
2335
|
+
el('p', { class: b.linked ? 'ok-msg' : 'hint', text: b.linked
|
|
2336
|
+
? '✓ Your Telegram is linked. You can accept or decline reports from the alerts. Decline asks you for the reason, which the reporter reads.'
|
|
2337
|
+
: 'Link your Telegram to accept or decline reports from the alerts. Only linked team members can; anyone else’s tap is refused.' }),
|
|
2338
|
+
el('div', { class: 'row' }, [make]),
|
|
2339
|
+
];
|
|
2340
|
+
if (b.linked) {
|
|
2341
|
+
var unlink = el('button', { class: 'btn ghost', type: 'button', text: 'Unlink' });
|
|
2342
|
+
unlink.onclick = function () {
|
|
2343
|
+
var done = busyButton(unlink, 'Unlinking…');
|
|
2344
|
+
api('DELETE', '/telegram/link').then(function () { toast('Your Telegram is unlinked.'); draw(); })
|
|
2345
|
+
.catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
|
|
2346
|
+
};
|
|
2347
|
+
kids[1].appendChild(unlink);
|
|
2348
|
+
}
|
|
2349
|
+
kids.push(shown, msg);
|
|
2350
|
+
kids.forEach(function (k) { body.appendChild(k); });
|
|
2351
|
+
}).catch(function (x) { body.textContent = ''; body.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); });
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2302
2355
|
// ---- team ------------------------------------------------------------------------------
|
|
2303
2356
|
|
|
2304
2357
|
/** One numbered step of a setup, in the same style as the install steps. */
|