create-heresay 0.2.16 → 0.2.17

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
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.16
1
+ 0.2.17
@@ -1,4 +1,6 @@
1
1
  export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
2
+ export class TelegramLookupError extends Error {
3
+ }
2
4
  export const defaultNotifications = () => ({
3
5
  events: { new_report: true, accepted: false, fixed: true, handoff: true },
4
6
  telegram: { enabled: false, token: null, chat_id: '' },
@@ -14,6 +16,7 @@ export function notificationView(settings) {
14
16
  }
15
17
  class SettingsError extends Error {
16
18
  }
19
+ const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
17
20
  const object = (v) => {
18
21
  if (!v || typeof v !== 'object' || Array.isArray(v))
19
22
  throw new SettingsError('Invalid notification settings.');
@@ -67,7 +70,7 @@ export function patchNotifications(current, body) {
67
70
  else if (patch.token !== undefined) {
68
71
  const token = field(patch.token, 512);
69
72
  if (token) {
70
- if (provider === 'telegram' ? !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
73
+ if (provider === 'telegram' ? !TELEGRAM_TOKEN.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
71
74
  throw new SettingsError(`Invalid ${provider === 'telegram' ? 'Telegram bot' : 'Cliq webhook'} token.`);
72
75
  }
73
76
  target.token = token;
@@ -113,6 +116,27 @@ export async function notificationSettings(p, req, deps, body) {
113
116
  throw error;
114
117
  }
115
118
  }
119
+ if (p.length === 3 && p[1] === 'telegram' && p[2] === 'lookup' && req.method === 'POST') {
120
+ // A pasted token, or the saved one. The token goes only to Telegram and never comes back.
121
+ const pasted = typeof body.token === 'string' ? body.token.trim() : '';
122
+ const token = pasted || ((await deps.store.getInstance()).notifications ?? defaultNotifications()).telegram.token;
123
+ if (!token)
124
+ return json(400, { error: 'Paste the bot token from BotFather first.' });
125
+ if (!TELEGRAM_TOKEN.test(token))
126
+ return json(400, { error: 'That doesn’t look like a bot token. BotFather sends one like 123456789:AAH…' });
127
+ const now = deps.now(), start = Math.floor(now / 60_000) * 60_000;
128
+ if (!await deps.store.hit(`notification-lookup:telegram:${start}`, 12, start + 60_000)) {
129
+ return json(429, { error: 'Wait a minute before looking again.' });
130
+ }
131
+ if (!deps.telegramLookup)
132
+ return json(503, { error: 'Telegram lookup is unavailable.' });
133
+ try {
134
+ return json(200, await deps.telegramLookup(token));
135
+ }
136
+ catch (error) {
137
+ return json(502, { error: error instanceof TelegramLookupError ? error.message : 'Could not reach Telegram. Try again in a moment.' });
138
+ }
139
+ }
116
140
  if (p.length === 2 && p[1] === 'test' && req.method === 'POST') {
117
141
  const provider = body.provider;
118
142
  if (provider !== 'telegram' && provider !== 'cliq')
@@ -202,4 +226,50 @@ export function notificationSender(http = fetch) {
202
226
  }
203
227
  };
204
228
  }
229
+ /**
230
+ * Telegram has no "list my chats". A bot sees the chats that wrote to it (or added it) in the
231
+ * last day, through getUpdates; that is enough to offer the right one. Read-only: no offset is
232
+ * confirmed, so nothing is consumed.
233
+ */
234
+ export function telegramLookup(http = fetch) {
235
+ const call = async (token, method, body) => {
236
+ const response = await http(`https://api.telegram.org/bot${token}/${method}`, {
237
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body ?? {}),
238
+ signal: AbortSignal.timeout(5000), redirect: 'error',
239
+ });
240
+ const result = await response.json().catch(() => ({}));
241
+ return { status: response.status, ...result };
242
+ };
243
+ return async (token) => {
244
+ const me = await call(token, 'getMe');
245
+ if (me.status === 401 || me.status === 404)
246
+ throw new TelegramLookupError('Telegram doesn’t recognise this token. Copy it again from BotFather.');
247
+ if (!me.ok)
248
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
249
+ const bot = me.result;
250
+ const updates = await call(token, 'getUpdates', { limit: 100, timeout: 0, allowed_updates: ['message', 'channel_post', 'my_chat_member'] });
251
+ if (updates.status === 409) {
252
+ throw new TelegramLookupError('This bot already sends its messages to another service (a webhook), so Heresay can’t see its chats. Enter the chat ID yourself, or use a new bot.');
253
+ }
254
+ if (!updates.ok)
255
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
256
+ const seen = new Map();
257
+ for (const u of updates.result ?? []) {
258
+ const chat = (u.message ?? u.channel_post ?? u.my_chat_member)?.chat;
259
+ if (!chat || (typeof chat.id !== 'number' && typeof chat.id !== 'string'))
260
+ continue;
261
+ const kind = String(chat.type);
262
+ if (!['private', 'group', 'supergroup', 'channel'].includes(kind))
263
+ continue;
264
+ const title = kind === 'private'
265
+ ? [chat.first_name, chat.last_name].filter((x) => typeof x === 'string').join(' ') || (typeof chat.username === 'string' ? '@' + chat.username : 'You')
266
+ : typeof chat.title === 'string' ? chat.title : 'Untitled';
267
+ seen.set(String(chat.id), { id: String(chat.id), title: title.slice(0, 120), kind });
268
+ }
269
+ return {
270
+ bot: { username: typeof bot?.username === 'string' ? bot.username : '', name: typeof bot?.first_name === 'string' ? bot.first_name.slice(0, 120) : '' },
271
+ chats: [...seen.values()].reverse(), // the latest first
272
+ };
273
+ };
274
+ }
205
275
  //# sourceMappingURL=notifications.js.map
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.16';
2
+ export const VERSION = '0.2.17';
3
3
  //# sourceMappingURL=version.js.map
@@ -8,7 +8,7 @@ import { auth, db } from './admin.js';
8
8
  import { FirestoreStore } from './firestore-store.js';
9
9
  import { handle } from '../../core/handler.js';
10
10
  import { VERSION } from '../../core/version.js';
11
- import { notificationSender } from '../../core/notifications.js';
11
+ import { notificationSender, telegramLookup } from '../../core/notifications.js';
12
12
  const deps = {
13
13
  store: new FirestoreStore(db),
14
14
  async verifyIdToken(token) {
@@ -25,6 +25,7 @@ const deps = {
25
25
  version: VERSION,
26
26
  selfOrigins: selfOrigins(),
27
27
  sendNotification: notificationSender(),
28
+ telegramLookup: telegramLookup(),
28
29
  };
29
30
  function selfOrigins() {
30
31
  const id = process.env.GCLOUD_PROJECT;
@@ -10,10 +10,10 @@
10
10
  <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Figtree:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
11
11
  <link rel="stylesheet" href="/dashboard.css">
12
12
  </head>
13
- <body>
13
+ <body class="booting pending">
14
14
 
15
- <!-- Until sign-in state is known -->
16
- <div id="boot" class="loading boot" role="status" aria-label="Loading"><img src="/loader.svg" alt=""></div>
15
+ <!-- The one loader: from first paint until a page has everything it needs -->
16
+ <div id="loader" class="app-loader on" role="status" aria-label="Loading"><img src="/loader.svg" alt="" width="96" height="96"></div>
17
17
 
18
18
  <!-- Signed out -->
19
19
  <div id="gate" class="gate" hidden>
@@ -132,12 +132,19 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
132
132
  .wait.ok .btn { margin-left:auto; }
133
133
  @keyframes pulse { 0%, 100% { opacity:.25; transform:scale(.8); } 50% { opacity:1; transform:scale(1); } }
134
134
  @media (prefers-reduced-motion: reduce) { .wait::before { animation:none; } }
135
- /* loading: the Glance mark, faded in late so quick loads never flash it */
136
- .loading { display:grid; place-items:center; padding:12vh 0; animation:loading-in .2s .3s both; }
137
- .loading img { width:96px; height:96px; }
138
- .loading.boot { padding-top:30vh; }
139
- .loading:not(.boot):not(:only-child) { display:none; }
135
+ /* loading: one Glance mark, fixed in place, faded in late so quick loads never flash it */
136
+ .app-loader { position:fixed; left:50%; top:38vh; z-index:20; width:96px; height:96px; margin:-48px 0 0 -48px; pointer-events:none;
137
+ opacity:0; visibility:hidden; transition:opacity .25s ease, visibility 0s .25s; }
138
+ .app-loader.on { opacity:1; visibility:visible; transition:opacity .25s ease; }
139
+ .booting .app-loader.on { animation:loading-in .25s .3s both; }
140
+ .app-loader img { display:block; width:96px; height:96px; }
140
141
  @keyframes loading-in { from { opacity:0; } }
142
+ /* What a view still waits for. While one is alone in its box, the page stays out of sight. */
143
+ .loading { display:block; min-height:40vh; list-style:none; }
144
+ .loading:not(:only-child) { display:none; }
145
+ #app, #view { transition:opacity .25s ease; }
146
+ .booting.pending #app, .pending #view { opacity:0; visibility:hidden; transition:none; }
147
+ @media (prefers-reduced-motion: reduce) { #app, #view, .app-loader, .app-loader.on { transition:none; } }
141
148
 
142
149
  /* reports */
143
150
  .filters { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
@@ -376,6 +383,25 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
376
383
  .notification-choice .hint { display:block; margin:2px 0 0; }
377
384
  .notification-form input[type=text], .notification-form input[type=password] { width:100%; min-width:0; }
378
385
  .notification-form .row { margin-top:22px; }
386
+ /* a guided setup inside a card */
387
+ .setup-step { margin-top:22px; }
388
+ .setup-step .test-head b { font-size:16px; }
389
+ .setup-body { margin:6px 0 0 34px; }
390
+ .setup-body > .row.tight { margin-top:10px; }
391
+ .setup-body label { margin-top:14px; }
392
+ .chat-finder:empty { display:none; }
393
+ .chat-finder { margin-top:12px; }
394
+ .chat-finder p { margin:0 0 8px; }
395
+ .chat-list { display:flex; flex-direction:column; gap:6px; }
396
+ .notification-form .chat-choice { display:flex; align-items:center; gap:12px; margin:0; padding:10px 14px; border:1px solid var(--line); border-radius:12px; cursor:pointer; font-weight:400; }
397
+ .chat-choice:hover { border-color:var(--acc); }
398
+ .chat-choice:has(input:checked) { border-color:var(--acc); background:var(--mist); }
399
+ .notification-form .chat-choice input:focus { outline:none; }
400
+ .chat-choice:has(input:focus-visible) { outline:2px solid var(--acc); outline-offset:2px; }
401
+ .notification-form .chat-choice input { display:inline-block; width:auto; flex:none; accent-color:var(--acc); margin:0; }
402
+ .chat-choice b { display:block; }
403
+ .chat-choice .mute { font-size:13px; }
404
+ @media (max-width:600px) { .setup-body { margin-left:0; } }
379
405
  @media (max-width:600px) {
380
406
  .top { flex-wrap:wrap; gap:8px 12px; padding:12px 16px; }
381
407
  .top .tabs { order:5; width:100%; }
@@ -42,13 +42,34 @@
42
42
  }
43
43
 
44
44
  function show(which) {
45
- ['boot', 'gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
45
+ ['gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
46
+ syncLoader();
46
47
  }
47
48
 
48
- /** The Glance loader. It shows only while it is alone in its box, so a view's first content hides it. */
49
- function loading() {
50
- return el('div', { class: 'loading', role: 'status', 'aria-label': 'Loading' }, [el('img', { src: '/loader.svg', alt: '' })]);
49
+ /**
50
+ * One Glance loader for the whole dashboard, from the first paint until a page is ready. It is
51
+ * never recreated, so the animation never restarts. A view marks what it is still waiting for
52
+ * with loading(); while any of those is alone in its box the view stays hidden, then the page
53
+ * appears in one go.
54
+ */
55
+ var loader = $('loader'), loaderTimer = null;
56
+ function loading(tag) {
57
+ return el(tag || 'div', { class: 'loading', 'aria-hidden': 'true' });
58
+ }
59
+ function syncLoader() {
60
+ // Signed in: wait for the view. Otherwise wait until we know who this is (sign-in or blocked).
61
+ var waiting = !$('app').hidden ? !!$('view').querySelector('.loading:only-child') : $('gate').hidden && $('blocked').hidden;
62
+ document.body.classList.toggle('pending', waiting);
63
+ if (!waiting) document.body.classList.remove('booting');
64
+ if (waiting && !loader.classList.contains('on')) {
65
+ // A quick page never flashes the loader; it just appears.
66
+ if (!loaderTimer) loaderTimer = setTimeout(function () { loaderTimer = null; loader.classList.add('on'); }, 250);
67
+ } else if (!waiting) {
68
+ clearTimeout(loaderTimer); loaderTimer = null;
69
+ loader.classList.remove('on');
70
+ }
51
71
  }
72
+ new MutationObserver(syncLoader).observe($('view'), { childList: true, subtree: true });
52
73
 
53
74
  function copyButton(getText, label) {
54
75
  var b = el('button', { class: 'btn', type: 'button', text: label || 'Copy' });
@@ -157,8 +178,8 @@
157
178
  api('GET', '/me').then(function (b) {
158
179
  me = b;
159
180
  $('who').textContent = b.email;
181
+ route(); // first, so the view is already waiting when the app is shown
160
182
  show('app');
161
- route();
162
183
  checkForUpdate(b);
163
184
  }).catch(function (x) {
164
185
  show('blocked');
@@ -1272,6 +1293,11 @@
1272
1293
  reports = triageSort([].concat.apply([], sibs.map(function (x) { return ctxs[x.id].reports; })));
1273
1294
  drawPlatforms();
1274
1295
  render();
1296
+ }).catch(function (x) {
1297
+ if (reports.length) return; // a background refresh failed: keep what is on screen
1298
+ list.textContent = '';
1299
+ list.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1300
+ list.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
1275
1301
  });
1276
1302
  }
1277
1303
 
@@ -1655,7 +1681,7 @@
1655
1681
  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' })]));
1656
1682
  return;
1657
1683
  }
1658
- var content = el('div');
1684
+ var content = el('div', {}, [loading()]);
1659
1685
  view.appendChild(content);
1660
1686
  api('GET', '/notifications').then(function (b) {
1661
1687
  var settings = b.notifications;
@@ -1700,13 +1726,64 @@
1700
1726
  var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
1701
1727
  var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
1702
1728
  var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
1703
- var form = el('form', { class: 'form notification-form' }, [
1729
+ // Telegram only: find the chat for them, from the chats that have messaged the bot.
1730
+ var find = el('button', { class: 'btn primary', type: 'button', text: 'Find my chats' });
1731
+ var found = el('div', { class: 'chat-finder', 'aria-live': 'polite' });
1732
+ var botLinks = el('div', { class: 'row tight', hidden: true });
1733
+ find.onclick = function () {
1734
+ found.textContent = '';
1735
+ var undo = busyButton(find, 'Looking…');
1736
+ api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
1737
+ var bot = b.bot.username;
1738
+ botLinks.textContent = '';
1739
+ if (bot) {
1740
+ botLinks.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(bot), target: '_blank', rel: 'noopener noreferrer', text: 'Open @' + bot + ' ↗' }));
1741
+ botLinks.appendChild(el('a', { class: 'btn ghost', href: 'https://t.me/' + encodeURIComponent(bot) + '?startgroup=heresay', target: '_blank', rel: 'noopener noreferrer', text: 'Add it to a group ↗' }));
1742
+ botLinks.hidden = false;
1743
+ }
1744
+ found.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ ' + (b.bot.name || 'Your bot') + (bot ? ' (@' + bot + ')' : '') }), document.createTextNode(' is ready.')]));
1745
+ if (!b.chats.length) {
1746
+ found.appendChild(el('p', { class: 'hint', text: 'No chats yet. Open the bot and press Start, or add it to a group and send a message, then press Find my chats again. Telegram only shows the last day.' }));
1747
+ return;
1748
+ }
1749
+ var KIND = { private: 'You', group: 'Group', supergroup: 'Group', channel: 'Channel' };
1750
+ var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
1751
+ b.chats.forEach(function (c) {
1752
+ var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
1753
+ radio.onchange = function () {
1754
+ address.value = c.id;
1755
+ enabled.checked = true;
1756
+ form.dispatchEvent(new Event('input'));
1757
+ feedback('Chat chosen. Save to start sending alerts there.');
1758
+ };
1759
+ list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] + ' · ' + c.id })])]));
1760
+ });
1761
+ found.appendChild(list);
1762
+ if (b.chats.length === 1 && !address.value) list.querySelector('input').click();
1763
+ }).catch(function (x) { found.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); }).finally(undo);
1764
+ };
1765
+ var form = el('form', { class: 'form notification-form' }, telegram ? [
1766
+ el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1767
+ setupStep(1, 'Make a bot', [
1768
+ el('p', { class: 'hint' }, ['In Telegram, open BotFather and send ', el('code', { text: '/newbot' }),
1769
+ '. Give it any name, then a username that ends in “bot”. BotFather replies with a token: copy it and paste it here.']),
1770
+ el('div', { class: 'row tight' }, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather ↗' })]),
1771
+ el('label', {}, ['Bot token', token]), tokenHint,
1772
+ ]),
1773
+ setupStep(2, 'Choose where alerts go', [
1774
+ el('p', { class: 'hint', text: 'Say hello to your bot so it knows the chat: press Start in a chat with it, or add it to a group and send any message there. For a channel, add it as an administrator and post once.' }),
1775
+ botLinks,
1776
+ el('div', { class: 'row tight' }, [find]),
1777
+ found,
1778
+ el('label', {}, ['Chat ID or channel username', address]),
1779
+ el('p', { class: 'hint', text: 'Filled in when you pick a chat above. You can also type one, like -1001234567890 or @yourchannel.' }),
1780
+ ]),
1781
+ setupStep(3, 'Save and test', [el('div', { class: 'row tight' }, [save, test, remove]), message]),
1782
+ ] : [
1704
1783
  el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1705
- el('label', {}, [telegram ? 'Bot token' : 'Webhook token', token]), tokenHint,
1706
- el('label', {}, [telegram ? 'Chat ID or channel username' : 'Message endpoint', address]),
1707
- el('p', { class: 'hint' }, telegram
1708
- ? ['Create a bot with BotFather, start a conversation with it (or add it to your group), and enter the target chat ID. For a channel, add the bot as an administrator. ', el('a', { href: 'https://core.telegram.org/bots/tutorial', target: '_blank', rel: 'noopener noreferrer', text: 'Telegram setup guide' })]
1709
- : ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1784
+ el('label', {}, ['Webhook token', token]), tokenHint,
1785
+ el('label', {}, ['Message endpoint', address]),
1786
+ el('p', { class: 'hint' }, ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1710
1787
  el('div', { class: 'row' }, [save, test, remove]), message,
1711
1788
  ]);
1712
1789
  function refresh() {
@@ -1759,9 +1836,17 @@
1759
1836
 
1760
1837
  // ---- team ------------------------------------------------------------------------------
1761
1838
 
1839
+ /** One numbered step of a setup, in the same style as the install steps. */
1840
+ function setupStep(n, title, kids) {
1841
+ return el('div', { class: 'setup-step' }, [
1842
+ el('div', { class: 'test-head' }, [el('span', { class: 'stepnum', text: String(n) }), el('b', { text: title })]),
1843
+ el('div', { class: 'setup-body' }, kids),
1844
+ ]);
1845
+ }
1846
+
1762
1847
  function teamView(view) {
1763
1848
  var owner = me.role === 'owner';
1764
- var list = el('ul', { class: 'members' });
1849
+ var list = el('ul', { class: 'members' }, [loading('li')]);
1765
1850
  var err = el('p', { class: 'err', role: 'alert' });
1766
1851
  view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Team' })]));
1767
1852
  view.appendChild(el('p', { class: 'mute', text: 'Everyone here can read and answer reports for every app. Owners can also change the team.' }));